]> git.mxchange.org Git - pizzaservice-ejb.git/blobdiff - src/java/org/mxchange/jusercore/model/user/PizzaUserSessionBean.java
Please cherry-pick:
[pizzaservice-ejb.git] / src / java / org / mxchange / jusercore / model / user / PizzaUserSessionBean.java
index 5745479dc3d5d53dfc6d6f73bee6a586a4423fb4..7c452d6185e225e171e6405743b99302c51ce34b 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2016 Roland Haeder
+ * Copyright (C) 2016 - 2020 Free Software Foundation
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU Affero General Public License as
 package org.mxchange.jusercore.model.user;
 
 import java.text.MessageFormat;
-import java.util.GregorianCalendar;
+import java.util.Date;
 import java.util.List;
+import java.util.Objects;
 import javax.ejb.EJB;
 import javax.ejb.EJBException;
 import javax.ejb.Stateless;
-import javax.mail.Address;
-import javax.mail.internet.AddressException;
-import javax.mail.internet.InternetAddress;
-import javax.persistence.NoResultException;
-import javax.persistence.PersistenceException;
 import javax.persistence.Query;
-import org.mxchange.jcontacts.contact.Contact;
-import org.mxchange.jphone.phonenumbers.cellphone.DialableCellphoneNumber;
-import org.mxchange.jphone.phonenumbers.fax.DialableFaxNumber;
-import org.mxchange.jphone.phonenumbers.landline.DialableLandLineNumber;
-import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
-import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
+import org.mxchange.jcontacts.model.contact.Contact;
+import org.mxchange.jcontacts.model.contact.Contacts;
+import org.mxchange.jphone.model.phonenumbers.fax.DialableFaxNumber;
+import org.mxchange.jphone.model.phonenumbers.fax.FaxNumbers;
+import org.mxchange.jphone.model.phonenumbers.landline.DialableLandLineNumber;
+import org.mxchange.jphone.model.phonenumbers.landline.LandLineNumbers;
+import org.mxchange.jphone.model.phonenumbers.mobile.DialableMobileNumber;
+import org.mxchange.jphone.model.phonenumbers.mobile.MobileNumbers;
 import org.mxchange.jusercore.exceptions.UserNotFoundException;
 import org.mxchange.jusercore.exceptions.UserStatusConfirmedException;
 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
-import org.mxchange.jusercore.model.register.UserRegistrationSessionBeanRemote;
-import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
+import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
+import org.mxchange.jusercore.model.user.password_history.PasswordHistory;
+import org.mxchange.jusercore.model.user.password_history.UserPasswordHistory;
 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
-import org.mxchange.pizzaaplication.database.BasePizzaDatabaseBean;
+import org.mxchange.juserlogincore.model.user.register.UserRegistrationSessionBeanRemote;
+import org.mxchange.pizzaaplication.enterprise.BasePizzaEnterpriseBean;
 
 /**
  * A user EJB
  * <p>
- * @author Roland Haeder<roland@mxchange.org>
+ * @author Roland Hรคder<roland@mxchange.org>
  */
 @Stateless (name = "user", description = "A bean handling the user data")
-public class PizzaUserSessionBean extends BasePizzaDatabaseBean implements UserSessionBeanRemote {
+public class PizzaUserSessionBean extends BasePizzaEnterpriseBean implements UserSessionBeanRemote {
 
        /**
         * Serial number
@@ -58,131 +58,21 @@ public class PizzaUserSessionBean extends BasePizzaDatabaseBean implements UserS
        /**
         * Registration EJB
         */
-       @EJB
+       @EJB (lookup = "java:global/pizzaservice-ejb/userRegistration!org.mxchange.juserlogincore.model.user.register.UserRegistrationSessionBeanRemote")
        private UserRegistrationSessionBeanRemote registerBean;
 
        /**
         * Default constructor
         */
        public PizzaUserSessionBean () {
-       }
-
-       @Override
-       public User addUser (final User user) throws UserNameAlreadyRegisteredException, EmailAddressAlreadyRegisteredException {
-               // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("addUser: user={0} - CALLED!", user)); //NOI18N
-
-               // userId should not be null
-               if (null == user) {
-                       // Abort here
-                       throw new NullPointerException("user is null"); //NOI18N
-               } else if (user.getUserId() == null) {
-                       // Abort here
-                       throw new NullPointerException("user.userId is null"); //NOI18N
-               } else if (user.getUserId() < 1) {
-                       // Invalid number
-                       throw new IllegalArgumentException(MessageFormat.format("userId is not valid: {0}", user.getUserId())); //NOI18N
-               }
-
-               // Check if user is registered
-               if (this.registerBean.isUserNameRegistered(user)) {
-                       // Abort here
-                       throw new UserNameAlreadyRegisteredException(user);
-               } else if (this.registerBean.isEmailAddressRegistered(user)) {
-                       // Abort here
-                       throw new EmailAddressAlreadyRegisteredException(user);
-               }
-
-               // Set created timestamp
-               user.setUserCreated(new GregorianCalendar());
-               user.getUserContact().setContactCreated(new GregorianCalendar());
-
-               // Update cellphone, land-line and fax instance
-               this.setAllContactPhoneEntriesCreated(user.getUserContact());
-
-               // Persist it
-               this.getEntityManager().persist(user);
-
-               // Flush to get id back
-               this.getEntityManager().flush();
-
-               // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("addUser: user={0},user.id={1} - EXIT!", user, user.getUserId())); //NOI18N
-
-               // Return it
-               return user;
-       }
-
-       @Override
-       @SuppressWarnings ("unchecked")
-       public List<User> allMemberPublicVisibleUsers () {
-               // Trace message
-               this.getLoggerBeanLocal().logTrace("allMemberPublicVisibleUsers: CALLED!"); //NOI18N
-
-               // Get named query
-               Query query = this.getEntityManager().createNamedQuery("AllMemberPublicUsers", List.class); //NOI18N
-
-               // Set parameters
-               query.setParameter("status", UserAccountStatus.CONFIRMED); //NOI18N
-               query.setParameter("members", ProfileMode.MEMBERS); //NOI18N
-               query.setParameter("public", ProfileMode.PUBLIC); //NOI18N
-
-               // Get result
-               List<User> users = query.getResultList();
-
-               // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("allMemberPublicVisibleUsers: users.size()={0} - EXIT!", users.size())); //NOI18N
-
-               // Return full list
-               return users;
-       }
-
-       @Override
-       @SuppressWarnings ("unchecked")
-       public List<User> allPublicUsers () {
-               // Trace message
-               this.getLoggerBeanLocal().logTrace("allPublicUsers: CALLED!"); //NOI18N
-
-               // Get named query
-               Query query = this.getEntityManager().createNamedQuery("AllPublicUsers", List.class); //NOI18N
-
-               // Set parameters
-               query.setParameter("status", UserAccountStatus.CONFIRMED); //NOI18N
-               query.setParameter("mode", ProfileMode.PUBLIC); //NOI18N
-
-               // Get result
-               List<User> users = query.getResultList();
-
-               // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("allPublicUsers: users.size()={0} - EXIT!", users.size())); //NOI18N
-
-               // Return full list
-               return users;
-       }
-
-       @Override
-       @SuppressWarnings ("unchecked")
-       public List<User> allUsers () {
-               // Trace message
-               this.getLoggerBeanLocal().logTrace("allUsers: CALLED!"); //NOI18N
-
-               // Get named query
-               Query query = this.getEntityManager().createNamedQuery("AllUsers", List.class); //NOI18N
-
-               // Get result
-               List<User> users = query.getResultList();
-
-               // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("allUsers: users.size()={0} - EXIT!", users.size())); //NOI18N
-
-               // Return full list
-               return users;
+               // Call super constructor
+               super("jms/pizzaservice-queue-factory", "jms/pizzaservice-email-queue"); //NOI18N
        }
 
        @Override
        public User confirmAccount (final User user, final String baseUrl) throws UserStatusConfirmedException, UserStatusLockedException {
                // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("confirmAccount: user={0},baseUrl={1} - CALLED!", user, baseUrl)); //NOI18N
+               this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.confirmAccount: user={1},baseUrl={2} - CALLED!", this.getClass().getSimpleName(), user, baseUrl)); //NOI18N
 
                // Parameter must be valid
                if (null == user) {
@@ -193,7 +83,7 @@ public class PizzaUserSessionBean extends BasePizzaDatabaseBean implements UserS
                        throw new NullPointerException("user.userId is null"); //NOI18N
                } else if (user.getUserId() < 1) {
                        // Invalid number
-                       throw new IllegalArgumentException(MessageFormat.format("userId is not valid: {0}", user.getUserId())); //NOI18N
+                       throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
                } else if (user.getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
                        // Account is already confirmed
                        throw new UserStatusConfirmedException(user);
@@ -203,160 +93,55 @@ public class PizzaUserSessionBean extends BasePizzaDatabaseBean implements UserS
                } else if (user.getUserConfirmKey() == null) {
                        // Throw NPE
                        throw new NullPointerException("user.userConfirmKey is null"); //NOI18N
+               } else if (null == baseUrl) {
+                       // Throw it again
+                       throw new NullPointerException("baseUrl is null"); //NOI18N
+               } else if (baseUrl.isEmpty()) {
+                       // Invalid parameter
+                       throw new IllegalArgumentException("baseUrl is empty"); //NOI18N
                }
 
-               // Update user status and remove confirmation key
-               user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
-               user.setUserConfirmKey(null);
-               user.setUserUpdated(new GregorianCalendar());
-
                // Update user account
-               User updatedUser = this.updateUserData(user);
-
-               // Init variable
-               Address emailAddress;
+               final User managedUser = this.updateUserData(user);
 
-               try {
-                       // Create email address and set
-                       emailAddress = new InternetAddress(updatedUser.getUserContact().getContactEmailAddress());
-               } catch (final AddressException ex) {
-                       // Throw again
-                       throw new EJBException(ex);
-               }
+               // Update user status and remove confirmation key
+               managedUser.setUserAccountStatus(UserAccountStatus.CONFIRMED);
+               managedUser.setUserConfirmKey(null);
+               managedUser.setUserUpdated(new Date());
 
                // Send out email
-               this.sendEmail("Account confirmed", "account_confirmed", emailAddress, updatedUser, baseUrl); //NOI18N
+               this.sendEmail("User account confirmed", "user_account_confirmed", managedUser, baseUrl, null); //NOI18N
 
                // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("confirmAccount: updatedUser={0} - EXIT!", updatedUser)); //NOI18N
+               this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.confirmAccount: managedUser={1} - EXIT!", this.getClass().getSimpleName(), managedUser)); //NOI18N
 
                // Return updated instance
-               return updatedUser;
-       }
-
-       @Override
-       public User fillUserData (final User user) {
-               // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("fillUserData: user={0} - CALLED!", user)); //NOI18N
-
-               // user should not be null
-               if (null == user) {
-                       // Abort here
-                       throw new NullPointerException("user is null"); //NOI18N
-               }
-
-               // Try to locate it
-               Query query = this.getEntityManager().createNamedQuery("SearchUserByName", LoginUser.class); //NOI18N
-
-               // Set parameter
-               query.setParameter("userName", user.getUserName()); //NOI18N
-
-               // Initialize variable
-               User foundUser = null;
-
-               // Try it
-               try {
-                       // Try to get single result
-                       foundUser = (User) query.getSingleResult();
-               } catch (final NoResultException ex) {
-                       // Log it
-                       this.getLoggerBeanLocal().logException(ex);
-               }
-
-               // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("fillUserData: foundUser={0} - EXIT!", foundUser)); //NOI18N
-
-               // Return prepared instance
-               return foundUser;
+               return managedUser;
        }
 
        @Override
-       public User findUserById (final Long userId) throws UserNotFoundException {
-               // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("findUserById: userId={0} - CALLED!", userId)); //NOI18N
-
-               // Is the parameter valid?
-               if (null == userId) {
-                       // Throw NPE
-                       throw new NullPointerException("userId is null"); //NOI18N
-               } else if (userId < 1) {
-                       // Not valid
-                       throw new IllegalArgumentException(MessageFormat.format("userId={0} is not valid.", userId)); //NOI18N
-               } else if (!this.ifUserIdExists(userId)) {
-                       // Does not exist
-                       throw new UserNotFoundException(userId);
-               }
-
-               // Create query instance
-               Query query = this.getEntityManager().createNamedQuery("SearchUserById", LoginUser.class); //NOI18N
-
-               // Set user id
-               query.setParameter("id", userId); //NOI18N
-
-               // Fetch the result, it should be there by now
-               User user = (User) query.getSingleResult();
-
-               // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("findUserById: user={0} - EXIT!", user)); //NOI18N
-
-               // Return found user
-               return user;
-       }
-
-       @Override
-       public String generateRandomUserName () {
+       @SuppressWarnings ("unchecked")
+       public List<User> fetchAllUsers () {
                // Trace message
-               this.getLoggerBeanLocal().logTrace("generateRandomUserName - CALLED!"); //NOI18N
-
-               // Get full list
-               List<String> userList = this.getUserNameList();
+               this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.allUsers: CALLED!", this.getClass().getSimpleName())); //NOI18N
 
-               // Init variable
-               String userName = null;
+               // Get named query
+               final Query query = this.getEntityManager().createNamedQuery("AllUsers", LoginUser.class); //NOI18N
 
-               // Loop until a user name is found
-               while ((userName == null) || (userList.contains(userName))) {
-                       // Generate random name
-                       userName = UserUtils.generateRandomUserName();
-               }
+               // Get result
+               final List<User> users = query.getResultList();
 
                // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("generateRandomUserName: userName={0} - EXIT!", userName)); //NOI18N
-
-               // Found one, so return it
-               return userName;
-       }
+               this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.allUsers: users.size()={1} - EXIT!", this.getClass().getSimpleName(), users.size())); //NOI18N
 
-       @Override
-       @SuppressWarnings ("unchecked")
-       public List<String> getEmailAddressList () {
-               // Get query
-               Query query = this.getEntityManager().createNamedQuery("AllEmailAddresses", String.class); //NOI18N
-
-               // Get result list
-               List<String> emailAddressList = query.getResultList();
-
-               // Return it
-               return emailAddressList;
-       }
-
-       @Override
-       @SuppressWarnings ("unchecked")
-       public List<String> getUserNameList () {
-               // Get query
-               Query query = this.getEntityManager().createNamedQuery("AllUserNames", String.class); //NOI18N
-
-               // Get result list
-               List<String> userNameList = query.getResultList();
-
-               // Return it
-               return userNameList;
+               // Return full list
+               return users;
        }
 
        @Override
        public boolean ifUserExists (final User user) {
                // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("ifUserExists: user={0} - CALLED!", user)); //NOI18N
+               this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.ifUserExists: user={1} - CALLED!", this.getClass().getSimpleName(), user)); //NOI18N
 
                // userId should not be null
                if (null == user) {
@@ -367,93 +152,33 @@ public class PizzaUserSessionBean extends BasePizzaDatabaseBean implements UserS
                        throw new NullPointerException("user.userId is null"); //NOI18N
                } else if (user.getUserId() < 1) {
                        // Invalid number
-                       throw new IllegalArgumentException(MessageFormat.format("userId is not valid: {0}", user.getUserId())); //NOI18N
+                       throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
                }
 
-               // Generate query
-               Query query = this.getEntityManager().createNamedQuery("SearchUserById", LoginUser.class); //NOI18N
-
-               // Set parameter
-               query.setParameter("id", user.getUserId()); //NOI18N
-
-               // Try this
-               try {
-                       User dummy = (User) query.getSingleResult();
-
-                       // Debug message
-                       this.getLoggerBeanLocal().logDebug(MessageFormat.format("ifUserExists: dummy.id={0} found.", dummy.getUserId())); //NOI18N
-               } catch (final NoResultException ex) {
-                       // Log it
-                       this.getLoggerBeanLocal().logDebug(MessageFormat.format("ifUserExists: getSingleResult() returned no result: {0}", ex)); //NOI18N
-
-                       // User name does not exist
-                       return false;
-               } catch (final PersistenceException ex) {
-                       // Something bad happened
-                       this.getLoggerBeanLocal().logWarning(MessageFormat.format("More than one user {0} found.", user, ex)); //NOI18N
-
-                       // Throw again
-                       throw ex;
+               // Default is not found
+               boolean isFound = false;
+
+               // Fetch whole list
+               for (final User currentUser : this.fetchAllUsers()) {
+                       // Is found?
+                       if (Objects.equals(user, currentUser)) {
+                               // Yes, then set flag and exit iteration
+                               isFound = true;
+                               break;
+                       }
                }
 
                // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("ifUserExists: Found user {0} - EXIT!", user)); //NOI18N
+               this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.ifUserExists: isFound={1} - EXIT!", this.getClass().getSimpleName(), isFound)); //NOI18N
 
-               // Found it
-               return true;
-       }
-
-       @Override
-       public boolean ifUserIdExists (final Long userId) {
-               // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("ifUserIdExists: userId={0} - CALLED!", userId)); //NOI18N
-
-               // userId should not be null
-               if (null == userId) {
-                       // Abort here
-                       throw new NullPointerException("userId is null"); //NOI18N
-               } else if (userId < 1) {
-                       // Invalid number
-                       throw new IllegalArgumentException(MessageFormat.format("userId is not valid: {0}", userId)); //NOI18N
-               }
-
-               // Generate query
-               Query query = this.getEntityManager().createNamedQuery("SearchUserById", LoginUser.class); //NOI18N
-
-               // Set parameter
-               query.setParameter("id", userId); //NOI18N
-
-               // Try this
-               try {
-                       User dummy = (User) query.getSingleResult();
-
-                       // Debug message
-                       this.getLoggerBeanLocal().logDebug(MessageFormat.format("ifUserIdExists: dummy.id={0} found.", dummy.getUserId())); //NOI18N
-               } catch (final NoResultException ex) {
-                       // Log it
-                       this.getLoggerBeanLocal().logDebug(MessageFormat.format("ifUserIdExists: getSingleResult() returned no result: {0}", ex)); //NOI18N
-
-                       // User name does not exist
-                       return false;
-               } catch (final PersistenceException ex) {
-                       // Something bad happened
-                       this.getLoggerBeanLocal().logWarning(MessageFormat.format("More than one user id {0} found.", userId, ex)); //NOI18N
-
-                       // Throw again
-                       throw ex;
-               }
-
-               // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("ifUserIdExists: Found user id {0} - EXIT!", userId)); //NOI18N
-
-               // Found it
-               return true;
+               // Return flag
+               return isFound;
        }
 
        @Override
        public boolean ifUserNameExists (final String userName) {
                // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("ifUserNameExists: userName={0} - CALLED!", userName)); //NOI18N
+               this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.ifUserNameExists: userName={1} - CALLED!", this.getClass().getSimpleName(), userName)); //NOI18N
 
                // userId should not be null
                if (null == userName) {
@@ -464,28 +189,21 @@ public class PizzaUserSessionBean extends BasePizzaDatabaseBean implements UserS
                        throw new NullPointerException("userName is empty"); //NOI18N
                }
 
-               // Generate query
-               Query query = this.getEntityManager().createNamedQuery("SearchUserByName", LoginUser.class); //NOI18N
-
-               // Set parameter
-               query.setParameter("userName", userName); //NOI18N
-
-               // Try this
-               try {
-                       User dummy = (User) query.getSingleResult();
-
-                       // Debug message
-                       this.getLoggerBeanLocal().logDebug(MessageFormat.format("ifUserNameExists: dummy.id={0} found.", dummy.getUserId())); //NOI18N
-               } catch (final NoResultException ex) {
-                       // Log it
-                       this.getLoggerBeanLocal().logDebug(MessageFormat.format("ifUserNameExists: getSingleResult() returned no result: {0}", ex)); //NOI18N
-
-                       // User name does not exist
-                       return false;
+               // Default is not registered
+               boolean isRegistered = false;
+
+               // Iterate over all records
+               for (final User currentUser : this.fetchAllUsers()) {
+                       // Does the username match?
+                       if (userName.equals(currentUser.getUserName())) {
+                               // Yes, then set flag and exit iteration
+                               isRegistered = true;
+                               break;
+                       }
                }
 
                // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("ifUserNameExists: Found user name {0} - EXIT!", userName)); //NOI18N
+               this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.ifUserNameExists: isRegistered={1} - EXIT!", this.getClass().getSimpleName(), isRegistered)); //NOI18N
 
                // Found it
                return true;
@@ -494,7 +212,7 @@ public class PizzaUserSessionBean extends BasePizzaDatabaseBean implements UserS
        @Override
        public boolean isEmailAddressRegistered (final User user) {
                // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("isEmailAddressRegistered: user={0} - CALLED!", user)); //NOI18N
+               this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.isEmailAddressRegistered: user={1} - CALLED!", this.getClass().getSimpleName(), user)); //NOI18N
 
                // user should not be null
                if (null == user) {
@@ -502,40 +220,30 @@ public class PizzaUserSessionBean extends BasePizzaDatabaseBean implements UserS
                        throw new NullPointerException("user is null"); //NOI18N
                }
 
-               // Generate query
-               Query query = this.getEntityManager().createNamedQuery("SearchUserByEmailAddress", LoginUser.class); //NOI18N
-
-               // Set parameter
-               query.setParameter("emailAddress", user.getUserContact().getContactEmailAddress()); //NOI18N
-
-               // Search for it
-               try {
-                       User dummy = (User) query.getSingleResult();
-
-                       // Debug message
-                       this.getLoggerBeanLocal().logDebug(MessageFormat.format("isEmailAddressRegistered: dummy.id={0} found.", dummy.getUserId())); //NOI18N
-               } catch (final NoResultException ex) {
-                       // Log it
-                       this.getLoggerBeanLocal().logDebug(MessageFormat.format("isEmailAddressRegistered: getSingleResult() returned no result: {0}", ex)); //NOI18N
-
-                       // Email address does not exist
-                       return false;
-               } catch (final PersistenceException ex) {
-                       // Something bad happened
-                       this.getLoggerBeanLocal().logWarning(MessageFormat.format("More than one email address {0} found.", user.getUserContact().getContactEmailAddress()), ex); //NOI18N
-
-                       // Throw again
-                       throw ex;
+               // Default is not registered
+               boolean isRegistered = false;
+
+               // Iterate over all records
+               for (final User currentUser : this.fetchAllUsers()) {
+                       // Does the email address match?
+                       if (user.getUserContact().getContactEmailAddress().equals(currentUser.getUserContact().getContactEmailAddress())) {
+                               // Yes, then set flag and exit iteration
+                               isRegistered = true;
+                               break;
+                       }
                }
 
+               // Trace message
+               this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.isEmailAddressRegistered: isRegistered={1} - EXIT!", this.getClass().getSimpleName(), isRegistered)); //NOI18N
+
                // Found it
-               return true;
+               return isRegistered;
        }
 
        @Override
        public boolean isUserNameRegistered (final User user) {
                // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("isUserNameRegistered: user={0} - CALLED!", user)); //NOI18N
+               this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.isUserNameRegistered: user={1} - CALLED!", this.getClass().getSimpleName(), user)); //NOI18N
 
                // user should not be null
                if (null == user) {
@@ -543,142 +251,144 @@ public class PizzaUserSessionBean extends BasePizzaDatabaseBean implements UserS
                        throw new NullPointerException("user is null"); //NOI18N
                }
 
-               // Generate query
-               Query query = this.getEntityManager().createNamedQuery("SearchUserByName", LoginUser.class); //NOI18N
+               // Ask other method
+               final boolean isRegistered = this.ifUserNameExists(user.getUserName());
 
-               // Set parameter
-               query.setParameter("userName", user.getUserName()); //NOI18N
-
-               // Try this
-               try {
-                       User dummy = (User) query.getSingleResult();
-
-                       // Debug message
-                       this.getLoggerBeanLocal().logDebug(MessageFormat.format("isUserNameRegistered: dummy.id={0} found.", dummy.getUserId())); //NOI18N
-               } catch (final NoResultException ex) {
-                       // Log it
-                       this.getLoggerBeanLocal().logDebug(MessageFormat.format("isUserNameRegistered: getSingleResult() returned no result: {0}", ex)); //NOI18N
-
-                       // User name does not exist
-                       return false;
-               } catch (final PersistenceException ex) {
-                       // Something bad happened
-                       this.getLoggerBeanLocal().logWarning(MessageFormat.format("More than one email address {0} found.", user.getUserContact().getContactEmailAddress()), ex); //NOI18N
-
-                       // Throw again
-                       throw ex;
-               }
+               // Trace message
+               this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.isUserNameRegistered: isRegistered={1} - EXIT!", this.getClass().getSimpleName(), isRegistered)); //NOI18N
 
-               // Found it
-               return true;
+               // Return flag
+               return isRegistered;
        }
 
        @Override
-       public User linkUser (final User user) throws UserNameAlreadyRegisteredException, EmailAddressAlreadyRegisteredException {
+       public User updateUserData (final User detachedUser) {
                // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("linkUser: user={0} - CALLED!", user)); //NOI18N
+               this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserData: detachedUser={1} - CALLED!", this.getClass().getSimpleName(), detachedUser)); //NOI18N
 
                // user should not be null
-               if (null == user) {
+               if (null == detachedUser) {
                        // Abort here
-                       throw new NullPointerException("user is null"); //NOI18N
-               } else if (user.getUserId() instanceof Long) {
-                       // Id is set
-                       throw new IllegalArgumentException("user.userId is not null"); //NOI18N
-               } else if (user.getUserContact() == null) {
-                       // Throw NPE again
-                       throw new NullPointerException("user.userContact is null"); //NOI18N
-               } else if (user.getUserContact().getContactId() == null) {
+                       throw new NullPointerException("detachedUser is null"); //NOI18N
+               } else if (detachedUser.getUserId() == null) {
                        // Throw NPE again
-                       throw new NullPointerException("user.userContact.contactId is null"); //NOI18N
-               } else if (user.getUserContact().getContactId() < 1) {
-                       // Not valid id number
-                       throw new IllegalArgumentException(MessageFormat.format("user.userContact.contactId={0} is not valid", user.getUserContact().getContactId())); //NOI18N
-               } else if (user.getUserAccountStatus() == null) {
+                       throw new NullPointerException("detachedUser.userId is null"); //NOI18N
+               } else if (detachedUser.getUserId() < 1) {
+                       // Not valid
+                       throw new IllegalArgumentException(MessageFormat.format("detachedUser.userId={0} is not valid", detachedUser.getUserId())); //NOI18N
+               } else if (detachedUser.getUserAccountStatus() == null) {
                        // Throw NPE again
-                       throw new NullPointerException("user.userAccountStatus is null"); //NOI18N
-               } else if (this.ifUserNameExists(user.getUserName())) {
-                       // Name already found
-                       throw new UserNameAlreadyRegisteredException(user.getUserName());
-               } else if (this.ifUserExists(user)) {
+                       throw new NullPointerException("detachedUser.userAccountStatus is null"); //NOI18N
+               } else if (!this.ifUserExists(detachedUser)) {
                        // User does not exist
-                       throw new IllegalStateException("User does already exist."); //NOI18N
+                       throw new EJBException(MessageFormat.format("User with id {0} does not exist.", detachedUser.getUserId())); //NOI18N
                }
 
-               // Try to find the contact
-               Contact foundContact = this.getEntityManager().find(user.getUserContact().getClass(), user.getUserContact().getContactId());
+               // Find the instance
+               final User foundUser = this.getEntityManager().find(detachedUser.getClass(), detachedUser.getUserId());
 
-               // Set detached object in rexcruiter instance
-               user.setUserContact(foundContact);
+               // Should be found!
+               assert (foundUser instanceof User) : MessageFormat.format("User with id {0} not found, but should be.", detachedUser.getUserId()); //NOI18N
 
-               // Set timestamp
-               user.setUserCreated(new GregorianCalendar());
+               // Merge user
+               final User managedUser = this.getEntityManager().merge(foundUser);
 
-               // Perist it
-               this.getEntityManager().persist(user);
+               // Should be found!
+               assert (managedUser instanceof User) : MessageFormat.format("User with id {0} not merged, but should be.", managedUser.getUserId()); //NOI18N
 
-               // Flush it to get updated instance back
-               this.getEntityManager().flush();
+               // Copy all data
+               Users.copyAll(detachedUser, managedUser);
+
+               // Set as updated
+               managedUser.setUserUpdated(new Date());
 
-               // Log trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("linkUser: user={0} - EXIT!", user)); //NOI18N
+               // Trace message
+               this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserData: managedUser={1} - EXIT!", this.getClass().getSimpleName(), managedUser)); //NOI18N
 
-               // Return updated instanc
-               return user;
+               // Return updated instance
+               return managedUser;
        }
 
        @Override
-       public User updateUserData (final User user) {
+       public PasswordHistory updateUserPassword (final User user, final String baseUrl) throws UserNotFoundException, UserStatusUnconfirmedException, UserStatusLockedException {
                // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("updateUserData: user={0} - CALLED!", user)); //NOI18N
+               this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserPassword: user={1},baseUrl={2} - CALLED!", this.getClass().getSimpleName(), user, baseUrl)); //NOI18N
 
                // user should not be null
                if (null == user) {
-                       // Abort here
+                       // Throw NPE
                        throw new NullPointerException("user is null"); //NOI18N
                } else if (user.getUserId() == null) {
                        // Throw NPE again
                        throw new NullPointerException("user.userId is null"); //NOI18N
                } else if (user.getUserId() < 1) {
-                       // Not valid
+                       // Not valid number
                        throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid.", user.getUserId())); //NOI18N
-               } else if (user.getUserAccountStatus() == null) {
+               } else if (user.getUserName() == null) {
                        // Throw NPE again
+                       throw new NullPointerException("user.userName is null"); //NOI18N
+               } else if (user.getUserName().isEmpty()) {
+                       // Empty string
+                       throw new IllegalArgumentException("user.userName is empty"); //NOI18N
+               } else if (user.getUserAccountStatus() == null) {
+                       // Throw NPE
                        throw new NullPointerException("user.userAccountStatus is null"); //NOI18N
+               } else if (user.getUserContact() == null) {
+                       // Throw it again
+                       throw new NullPointerException("user.userContact is null"); //NOI18N
+               } else if (user.getUserContact().getContactId() == null) {
+                       // .. and again
+                       throw new NullPointerException("user.userContact.contactId is null"); //NOI18N
+               } else if (user.getUserContact().getContactId() < 1) {
+                       // Invalid id
+                       throw new IllegalArgumentException(MessageFormat.format("user.userContact.contactId={0} is invalid", user.getUserContact().getContactId())); //NOI18N
+               } else if (user.getUserContact().getContactPersonalTitle() == null) {
+                       // Throw NPE again
+                       throw new NullPointerException("user.userContact.contactPersonalTitle is null"); //NOI18N
                } else if (!this.ifUserExists(user)) {
                        // User does not exist
                        throw new EJBException(MessageFormat.format("User with id {0} does not exist.", user.getUserId())); //NOI18N
+               } else if (null == baseUrl) {
+                       // Throw it again
+                       throw new NullPointerException("baseUrl is null"); //NOI18N
+               } else if (baseUrl.isEmpty()) {
+                       // Invalid parameter
+                       throw new IllegalArgumentException("baseUrl is empty"); //NOI18N
                }
 
-               // Remove contact instance as this is not updatedf
-               user.setUserContact(null);
+               // Call other method
+               final User managedUser = this.updateUserData(user);
 
-               // Find the instance
-               User foundUser = this.getEntityManager().find(user.getClass(), user.getUserId());
+               // Update user account
+               managedUser.setUserUpdated(new Date());
 
-               // Should be found!
-               assert (foundUser instanceof User) : MessageFormat.format("User with id {0} not found, but should be.", user.getUserId()); //NOI18N
+               // Create history entry
+               PasswordHistory entry = new UserPasswordHistory(user.getUserEncryptedPassword(), managedUser);
 
-               // Merge user
-               User detachedUser = this.getEntityManager().merge(foundUser);
+               // Set created timestamp
+               entry.setUserPasswordHistoryCreated(new Date());
 
-               // Should be found!
-               assert (detachedUser instanceof User) : MessageFormat.format("User with id {0} not merged, but should be.", user.getUserId()); //NOI18N
+               // Merge user to make sure it is not re-persisted
+               final User mergedUser = this.getEntityManager().merge(managedUser);
+               entry.setUserPasswordHistoryUser(mergedUser);
 
-               // Copy all data
-               detachedUser.copyAll(user);
+               // Persist it
+               this.getEntityManager().persist(entry);
 
-               // Set as updated
-               detachedUser.setUserUpdated(new GregorianCalendar());
+               // Send email to user
+               this.sendEmail("User password change", "user_password_change", managedUser, baseUrl, null); //NOI18N
 
-               // Return updated instance
-               return detachedUser;
+               // Trace message
+               this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserPassword: entry.userPasswordHistoryId={1} - EXIT!", this.getClass().getSimpleName(), entry.getUserPasswordHistoryId())); //NOI18N
+
+               // Return it
+               return entry;
        }
 
        @Override
        public User updateUserPersonalData (final User user) {
                // Trace message
-               this.getLoggerBeanLocal().logTrace(MessageFormat.format("updateUserPersonalData: user={0} - CALLED!", user)); //NOI18N
+               this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserPersonalData: user={1} - CALLED!", this.getClass().getSimpleName(), user)); //NOI18N
 
                // user should not be null
                if (null == user) {
@@ -689,7 +399,7 @@ public class PizzaUserSessionBean extends BasePizzaDatabaseBean implements UserS
                        throw new NullPointerException("user.userId is null"); //NOI18N
                } else if (user.getUserId() < 1) {
                        // Not valid
-                       throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid.", user.getUserId())); //NOI18N
+                       throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid", user.getUserId())); //NOI18N
                } else if (user.getUserAccountStatus() == null) {
                        // Throw NPE again
                        throw new NullPointerException("user.userAccountStatus is null"); //NOI18N
@@ -699,26 +409,20 @@ public class PizzaUserSessionBean extends BasePizzaDatabaseBean implements UserS
                }
 
                // Find the instance
-               User foundUser = this.getEntityManager().find(user.getClass(), user.getUserId());
+               final User managedUser = this.getEntityManager().find(user.getClass(), user.getUserId());
 
                // Should be found!
-               assert (foundUser instanceof User) : MessageFormat.format("User with id {0} not found, but should be.", user.getUserId()); //NOI18N
-
-               // Merge user
-               User detachedUser = this.getEntityManager().merge(foundUser);
-
-               // Should be found!
-               assert (detachedUser instanceof User) : MessageFormat.format("User with id {0} not merged, but should be.", user.getUserId()); //NOI18N
+               assert (managedUser instanceof User) : MessageFormat.format("User with id {0} not found, but should be.", user.getUserId()); //NOI18N
 
                // Copy all data
-               detachedUser.copyAll(user);
+               Users.copyAll(user, managedUser);
 
                // Set as updated
-               detachedUser.setUserUpdated(new GregorianCalendar());
-               detachedUser.getUserContact().setContactUpdated(new GregorianCalendar());
+               managedUser.setUserUpdated(new Date());
+               managedUser.getUserContact().setContactUpdated(new Date());
 
                // Get contact from it and find it
-               Contact foundContact = this.getEntityManager().find(user.getUserContact().getClass(), user.getUserContact().getContactId());
+               final Contact foundContact = this.getEntityManager().find(managedUser.getUserContact().getClass(), managedUser.getUserContact().getContactId());
 
                // Should be found
                assert (foundContact instanceof Contact) : MessageFormat.format("Contact with id {0} not found, but should be.", user.getUserContact().getContactId()); //NOI18N
@@ -727,100 +431,112 @@ public class PizzaUserSessionBean extends BasePizzaDatabaseBean implements UserS
                this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: contact.contactId={0}", foundContact.getContactId())); //NOI18N
 
                // Merge contact instance
-               Contact detachedContact = this.getEntityManager().merge(foundContact);
+               final Contact managedContact = this.getEntityManager().merge(foundContact);
 
                // Copy all
-               detachedContact.copyAll(user.getUserContact());
+               Contacts.copyAll(managedUser.getUserContact(), managedContact);
 
                // Set it back in user
-               user.setUserContact(detachedContact);
+               user.setUserContact(managedContact);
 
                // Should be found!
-               assert (detachedContact instanceof Contact) : MessageFormat.format("Contact with id {0} not merged, but should be.", user.getUserContact().getContactId()); //NOI18N
+               assert (managedContact instanceof Contact) : MessageFormat.format("Contact with id {0} not merged, but should be.", user.getUserContact().getContactId()); //NOI18N
 
-               // Get cellphone instance
-               DialableCellphoneNumber cellphone = detachedContact.getContactCellphoneNumber();
+               // Get mobile instance
+               final DialableMobileNumber mobileNumber = managedContact.getContactMobileNumber();
 
-               // Is there a  cellphone instance set?
-               if (cellphone instanceof DialableCellphoneNumber) {
+               // Is there a  mobile instance set?
+               if (mobileNumber instanceof DialableMobileNumber) {
                        // Debug message
-                       this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: cellphone.phoneId={0} is being updated ...", cellphone.getPhoneId())); //NOI18N
+                       this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: mobile.phoneId={0} is being updated ...", mobileNumber.getMobileId())); //NOI18N
 
                        // Then find it, too
-                       DialableCellphoneNumber foundCellphone = this.getEntityManager().find(cellphone.getClass(), cellphone.getPhoneId());
+                       final DialableMobileNumber foundMobile = this.getEntityManager().find(mobileNumber.getClass(), mobileNumber.getMobileId());
 
                        // Should be there
-                       assert (foundCellphone instanceof DialableCellphoneNumber) : MessageFormat.format("Cellphone number with id {0} not found but should be.", foundCellphone.getPhoneId()); //NOI18N
+                       assert (foundMobile instanceof DialableMobileNumber) : MessageFormat.format("Mobile number with id {0} not found but should be.", foundMobile.getMobileId()); //NOI18N
+
+                       // Copy all
+                       MobileNumbers.copyMobileNumber(managedUser.getUserContact().getContactMobileNumber(), foundMobile);
 
                        // Then merge it, too
-                       DialableCellphoneNumber detachedCellphone = this.getEntityManager().merge(foundCellphone);
+                       final DialableMobileNumber managedMobile = this.getEntityManager().merge(foundMobile);
 
                        // Should be there
-                       assert (detachedCellphone instanceof DialableCellphoneNumber) : MessageFormat.format("Cellphone number with id {0} not found but should be.", detachedCellphone.getPhoneId()); //NOI18N
+                       assert (managedMobile instanceof DialableMobileNumber) : MessageFormat.format("Mobile number with id {0} not found but should be.", managedMobile.getMobileId()); //NOI18N
 
                        // Copy all
-                       detachedCellphone.copyAll(user.getUserContact().getContactCellphoneNumber());
+                       MobileNumbers.copyAll(managedUser.getUserContact().getContactMobileNumber(), managedMobile);
 
                        // Set it back
-                       detachedContact.setContactCellphoneNumber(detachedCellphone);
+                       managedContact.setContactMobileNumber(this.createManaged(mobileNumber, mobileNumber));
                }
 
-               // Get cellphone instance
-               DialableFaxNumber fax = detachedContact.getContactFaxNumber();
+               // Get mobile instance
+               final DialableFaxNumber faxNumber = managedContact.getContactFaxNumber();
 
                // Is there a  fax instance set?
-               if (fax instanceof DialableFaxNumber) {
+               if (faxNumber instanceof DialableFaxNumber) {
                        // Debug message
-                       this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: fax.phoneId={0} is being updated ...", fax.getPhoneId())); //NOI18N
+                       this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: faxNumber.phoneId={0} is being updated ...", faxNumber.getPhoneId())); //NOI18N
 
                        // Then find it, too
-                       DialableFaxNumber foundFax = this.getEntityManager().find(fax.getClass(), fax.getPhoneId());
+                       final DialableFaxNumber foundFax = this.getEntityManager().find(faxNumber.getClass(), faxNumber.getPhoneId());
 
                        // Should be there
                        assert (foundFax instanceof DialableFaxNumber) : MessageFormat.format("Fax number with id {0} not found but should be.", foundFax.getPhoneId()); //NOI18N
 
+                       // Copy all
+                       FaxNumbers.copyFaxNumber(managedUser.getUserContact().getContactFaxNumber(), foundFax);
+
                        // Then merge it, too
-                       DialableFaxNumber detachedFax = this.getEntityManager().merge(foundFax);
+                       final DialableFaxNumber managedFax = this.getEntityManager().merge(foundFax);
 
                        // Should be there
-                       assert (detachedFax instanceof DialableFaxNumber) : MessageFormat.format("Fax number with id {0} not found but should be.", detachedFax.getPhoneId()); //NOI18N
+                       assert (managedFax instanceof DialableFaxNumber) : MessageFormat.format("Fax number with id {0} not found but should be.", managedFax.getPhoneId()); //NOI18N
 
                        // Copy all
-                       detachedFax.copyAll(user.getUserContact().getContactFaxNumber());
+                       FaxNumbers.copyAll(managedUser.getUserContact().getContactFaxNumber(), managedFax);
 
                        // Set it back
-                       detachedContact.setContactFaxNumber(detachedFax);
+                       managedContact.setContactFaxNumber(managedFax);
                }
 
-               // Get cellphone instance
-               DialableLandLineNumber landLine = detachedContact.getContactLandLineNumber();
+               // Get mobile instance
+               final DialableLandLineNumber landLineNumber = managedContact.getContactLandLineNumber();
 
                // Is there a  fax instance set?
-               if (landLine instanceof DialableLandLineNumber) {
+               if (landLineNumber instanceof DialableLandLineNumber) {
                        // Debug message
-                       this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: landLine.phoneId={0} is being updated ...", landLine.getPhoneId())); //NOI18N
+                       this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: landLineNumber.phoneId={0} is being updated ...", landLineNumber.getPhoneId())); //NOI18N
 
                        // Then find it, too
-                       DialableLandLineNumber foundLandLine = this.getEntityManager().find(landLine.getClass(), landLine.getPhoneId());
+                       final DialableLandLineNumber foundLandLine = this.getEntityManager().find(landLineNumber.getClass(), landLineNumber.getPhoneId());
 
                        // Should be there
                        assert (foundLandLine instanceof DialableLandLineNumber) : MessageFormat.format("Land line number with id {0} not found but should be.", foundLandLine.getPhoneId()); //NOI18N
 
+                       // Copy all
+                       LandLineNumbers.copyLandLineNumber(managedUser.getUserContact().getContactLandLineNumber(), foundLandLine);
+
                        // Then merge it, too
-                       DialableLandLineNumber detachedLandLine = this.getEntityManager().merge(foundLandLine);
+                       final DialableLandLineNumber managedLandLine = this.getEntityManager().merge(foundLandLine);
 
                        // Should be there
-                       assert (detachedLandLine instanceof DialableLandLineNumber) : MessageFormat.format("Land line number with id {0} not found but should be.", detachedLandLine.getPhoneId()); //NOI18N
+                       assert (managedLandLine instanceof DialableLandLineNumber) : MessageFormat.format("Land line number with id {0} not found but should be.", managedLandLine.getPhoneId()); //NOI18N
 
                        // Copy all
-                       detachedLandLine.copyAll(user.getUserContact().getContactLandLineNumber());
+                       LandLineNumbers.copyAll(managedUser.getUserContact().getContactLandLineNumber(), managedLandLine);
 
                        // Set it back
-                       detachedContact.setContactLandLineNumber(detachedLandLine);
+                       managedContact.setContactLandLineNumber(managedLandLine);
                }
 
+               // Trace message
+               this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserPersonalData: entry.managedUser={1} - EXIT!", this.getClass().getSimpleName(), managedUser)); //NOI18N
+
                // Return updated user instance
-               return detachedUser;
+               return managedUser;
        }
 
 }