2 * Copyright (C) 2016 Roland Haeder
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as
6 * published by the Free Software Foundation, either version 3 of the
7 * License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
14 * You should have received a copy of the GNU Affero General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org.mxchange.jusercore.model.user;
19 import java.text.MessageFormat;
20 import java.util.GregorianCalendar;
21 import java.util.List;
23 import javax.ejb.EJBException;
24 import javax.ejb.Stateless;
25 import javax.persistence.NoResultException;
26 import javax.persistence.PersistenceException;
27 import javax.persistence.Query;
28 import org.mxchange.addressbook.database.BaseAddressbookDatabaseBean;
29 import org.mxchange.jcontacts.contact.Contact;
30 import org.mxchange.jphone.phonenumbers.cellphone.DialableCellphoneNumber;
31 import org.mxchange.jphone.phonenumbers.fax.DialableFaxNumber;
32 import org.mxchange.jphone.phonenumbers.landline.DialableLandLineNumber;
33 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
34 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
35 import org.mxchange.jusercore.exceptions.UserNotFoundException;
36 import org.mxchange.jusercore.model.register.UserRegistrationSessionBeanRemote;
37 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
38 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
43 * @author Roland Haeder<roland@mxchange.org>
45 @Stateless (name = "user", description = "A bean handling the user data")
46 public class AddressbookUserSessionBean extends BaseAddressbookDatabaseBean implements UserSessionBeanRemote {
51 private static final long serialVersionUID = 542_145_347_916L;
57 private UserRegistrationSessionBeanRemote registerBean;
62 public AddressbookUserSessionBean () {
66 public User addUser (final User user) throws UserNameAlreadyRegisteredException, EmailAddressAlreadyRegisteredException {
68 this.getLoggerBeanLocal().logTrace(MessageFormat.format("addUser: user={0} - CALLED!", user)); //NOI18N
70 // user should not be null
73 throw new NullPointerException("user is null"); //NOI18N
74 } else if (user.getUserId() != null) {
76 throw new IllegalStateException(MessageFormat.format("user.userId must be null, is: {0}", user.getUserId())); //NOI18N
79 // Check if user is registered
80 if (this.registerBean.isUserNameRegistered(user)) {
82 throw new UserNameAlreadyRegisteredException(user);
83 } else if (this.registerBean.isEmailAddressRegistered(user)) {
85 throw new EmailAddressAlreadyRegisteredException(user);
88 // Set created timestamp
89 user.setUserCreated(new GregorianCalendar());
90 user.getUserContact().setContactCreated(new GregorianCalendar());
92 // Update cellphone, land-line and fax instance
93 this.setAllContactPhoneEntriesCreated(user.getUserContact());
96 this.getEntityManager().persist(user);
98 // Flush to get id back
99 this.getEntityManager().flush();
102 this.getLoggerBeanLocal().logTrace(MessageFormat.format("addUser: user={0},user.id={1} - EXIT!", user, user.getUserId())); //NOI18N
109 @SuppressWarnings ("unchecked")
110 public List<User> allMemberPublicVisibleUsers () {
112 this.getLoggerBeanLocal().logTrace("allMemberPublicVisibleUsers: CALLED!"); //NOI18N
115 Query query = this.getEntityManager().createNamedQuery("AllMemberPublicUsers", List.class); //NOI18N
118 query.setParameter("status", UserAccountStatus.CONFIRMED); //NOI18N
119 query.setParameter("members", ProfileMode.MEMBERS); //NOI18N
120 query.setParameter("public", ProfileMode.PUBLIC); //NOI18N
123 List<User> users = query.getResultList();
126 this.getLoggerBeanLocal().logTrace(MessageFormat.format("allMemberPublicVisibleUsers: users.size()={0} - EXIT!", users.size())); //NOI18N
133 @SuppressWarnings ("unchecked")
134 public List<User> allPublicUsers () {
136 this.getLoggerBeanLocal().logTrace("allPublicUsers: CALLED!"); //NOI18N
139 Query query = this.getEntityManager().createNamedQuery("AllPublicUsers", List.class); //NOI18N
142 query.setParameter("status", UserAccountStatus.CONFIRMED); //NOI18N
143 query.setParameter("mode", ProfileMode.PUBLIC); //NOI18N
146 List<User> users = query.getResultList();
149 this.getLoggerBeanLocal().logTrace(MessageFormat.format("allPublicUsers: users.size()={0} - EXIT!", users.size())); //NOI18N
156 @SuppressWarnings ("unchecked")
157 public List<User> allUsers () {
159 this.getLoggerBeanLocal().logTrace("allUsers: CALLED!"); //NOI18N
162 Query query = this.getEntityManager().createNamedQuery("AllUsers", List.class); //NOI18N
165 List<User> users = query.getResultList();
168 this.getLoggerBeanLocal().logTrace(MessageFormat.format("allUsers: users.size()={0} - EXIT!", users.size())); //NOI18N
175 public User fillUserData (final User user) {
177 this.getLoggerBeanLocal().logTrace(MessageFormat.format("fillUserData: user={0} - CALLED!", user)); //NOI18N
179 // user should not be null
182 throw new NullPointerException("user is null"); //NOI18N
186 Query query = this.getEntityManager().createNamedQuery("SearchUserByName", User.class); //NOI18N
189 query.setParameter("param", user.getUserName()); //NOI18N
191 // Initialize variable
192 User foundUser = null;
196 // Try to get single result
197 foundUser = (User) query.getSingleResult();
198 } catch (final NoResultException ex) {
200 this.getLoggerBeanLocal().logException(ex);
204 this.getLoggerBeanLocal().logTrace(MessageFormat.format("fillUserData: foundUser={0} - EXIT!", foundUser)); //NOI18N
206 // Return prepared instance
211 public User findUserById (final Long userId) throws UserNotFoundException {
213 this.getLoggerBeanLocal().logTrace(MessageFormat.format("findUserById: userId={0} - CALLED!", userId)); //NOI18N
215 // Is the parameter valid?
216 if (null == userId) {
218 throw new NullPointerException("userId is null"); //NOI18N
219 } else if (userId < 1) {
221 throw new IllegalArgumentException(MessageFormat.format("userId={0} is not valid.", userId)); //NOI18N
222 } else if (!this.ifUserIdExists(userId)) {
224 throw new UserNotFoundException(userId);
227 // Create query instance
228 Query query = this.getEntityManager().createNamedQuery("SearchUserById", User.class); //NOI18N
231 query.setParameter("id", userId); //NOI18N
233 // Fetch the result, it should be there by now
234 User user = (User) query.getSingleResult();
237 // @TODO This assertion tests the JPA
238 assert (user instanceof User) : "user is null"; //NOI18N
241 this.getLoggerBeanLocal().logTrace(MessageFormat.format("findUserById: user={0} - EXIT!", user)); //NOI18N
248 public String generateRandomUserName () {
250 this.getLoggerBeanLocal().logTrace("generateRandomUserName - CALLED!"); //NOI18N
253 List<String> userList = this.getUserNameList();
256 String userName = null;
258 // Loop until a user name is found
259 while ((userName == null) || (userList.contains(userName))) {
260 // Generate random name
261 userName = UserUtils.generateRandomUserName();
265 this.getLoggerBeanLocal().logTrace(MessageFormat.format("generateRandomUserName: userName={0} - EXIT!", userName)); //NOI18N
267 // Found one, so return it
272 @SuppressWarnings ("unchecked")
273 public List<String> getEmailAddressList () {
275 Query query = this.getEntityManager().createNamedQuery("AllEmailAddresses", String.class); //NOI18N
278 List<String> emailAddressList = query.getResultList();
281 return emailAddressList;
285 @SuppressWarnings ("unchecked")
286 public List<String> getUserNameList () {
288 Query query = this.getEntityManager().createNamedQuery("AllUserNames", String.class); //NOI18N
291 List<String> userNameList = query.getResultList();
298 public boolean ifUserExists (final User user) {
300 this.getLoggerBeanLocal().logTrace(MessageFormat.format("ifUserExists: user={0} - CALLED!", user)); //NOI18N
302 // userId should not be null
305 throw new NullPointerException("user is null"); //NOI18N
306 } else if (user.getUserId() == null) {
308 throw new NullPointerException("user.userId is null"); //NOI18N
309 } else if (user.getUserId() < 1) {
311 throw new IllegalArgumentException(MessageFormat.format("userId is not valid: {0}", user.getUserId())); //NOI18N
315 Query query = this.getEntityManager().createNamedQuery("SearchUserById", User.class); //NOI18N
318 query.setParameter("id", user.getUserId()); //NOI18N
322 User dummy = (User) query.getSingleResult();
325 this.getLoggerBeanLocal().logDebug(MessageFormat.format("ifUserExists: dummy.id={0} found.", dummy.getUserId())); //NOI18N
326 } catch (final NoResultException ex) {
328 this.getLoggerBeanLocal().logDebug(MessageFormat.format("ifUserExists: getSingleResult() returned no result: {0}", ex)); //NOI18N
330 // User name does not exist
332 } catch (final PersistenceException ex) {
333 // Something bad happened
334 this.getLoggerBeanLocal().logWarning(MessageFormat.format("More than one user {0} found.", user, ex)); //NOI18N
341 this.getLoggerBeanLocal().logTrace(MessageFormat.format("ifUserExists: Found user {0} - EXIT!", user)); //NOI18N
348 public boolean ifUserIdExists (final Long userId) {
350 this.getLoggerBeanLocal().logTrace(MessageFormat.format("ifUserIdExists: userId={0} - CALLED!", userId)); //NOI18N
352 // userId should not be null
353 if (null == userId) {
355 throw new NullPointerException("userId is null"); //NOI18N
356 } else if (userId < 1) {
358 throw new IllegalArgumentException(MessageFormat.format("userId is not valid: {0}", userId)); //NOI18N
362 Query query = this.getEntityManager().createNamedQuery("SearchUserById", User.class); //NOI18N
365 query.setParameter("id", userId); //NOI18N
369 User dummy = (User) query.getSingleResult();
372 this.getLoggerBeanLocal().logDebug(MessageFormat.format("ifUserIdExists: dummy.id={0} found.", dummy.getUserId())); //NOI18N
373 } catch (final NoResultException ex) {
375 this.getLoggerBeanLocal().logDebug(MessageFormat.format("ifUserIdExists: getSingleResult() returned no result: {0}", ex)); //NOI18N
377 // User name does not exist
379 } catch (final PersistenceException ex) {
380 // Something bad happened
381 this.getLoggerBeanLocal().logWarning(MessageFormat.format("More than one user id {0} found.", userId, ex)); //NOI18N
388 this.getLoggerBeanLocal().logTrace(MessageFormat.format("ifUserIdExists: Found user id {0} - EXIT!", userId)); //NOI18N
395 public boolean ifUserNameExists (final String userName) {
397 this.getLoggerBeanLocal().logTrace(MessageFormat.format("ifUserNameExists: userName={0} - CALLED!", userName)); //NOI18N
399 // userId should not be null
400 if (null == userName) {
402 throw new NullPointerException("userName is null"); //NOI18N
403 } else if (userName.isEmpty()) {
405 throw new NullPointerException("userName is empty"); //NOI18N
409 Query query = this.getEntityManager().createNamedQuery("SearchUserByName", User.class); //NOI18N
412 query.setParameter("param", userName); //NOI18N
416 User dummy = (User) query.getSingleResult();
419 this.getLoggerBeanLocal().logDebug(MessageFormat.format("ifUserNameExists: dummy.id={0} found.", dummy.getUserId())); //NOI18N
420 } catch (final NoResultException ex) {
422 this.getLoggerBeanLocal().logDebug(MessageFormat.format("ifUserNameExists: getSingleResult() returned no result: {0}", ex)); //NOI18N
424 // User name does not exist
429 this.getLoggerBeanLocal().logTrace(MessageFormat.format("ifUserNameExists: Found user name {0} - EXIT!", userName)); //NOI18N
436 public boolean isEmailAddressRegistered (final User user) {
438 this.getLoggerBeanLocal().logTrace(MessageFormat.format("isEmailAddressRegistered: user={0} - CALLED!", user)); //NOI18N
440 // user should not be null
443 throw new NullPointerException("user is null"); //NOI18N
447 Query query = this.getEntityManager().createNamedQuery("SearchUserByEmailAddress", User.class); //NOI18N
450 query.setParameter("param", user.getUserContact().getContactEmailAddress()); //NOI18N
454 User dummy = (User) query.getSingleResult();
457 this.getLoggerBeanLocal().logDebug(MessageFormat.format("isEmailAddressRegistered: dummy.id={0} found.", dummy.getUserId())); //NOI18N
458 } catch (final NoResultException ex) {
460 this.getLoggerBeanLocal().logDebug(MessageFormat.format("isEmailAddressRegistered: getSingleResult() returned no result: {0}", ex)); //NOI18N
462 // Email address does not exist
464 } catch (final PersistenceException ex) {
465 // Something bad happened
466 this.getLoggerBeanLocal().logWarning(MessageFormat.format("More than one email address {0} found.", user.getUserContact().getContactEmailAddress()), ex); //NOI18N
477 public boolean isUserNameRegistered (final User user) {
479 this.getLoggerBeanLocal().logTrace(MessageFormat.format("isUserNameRegistered: user={0} - CALLED!", user)); //NOI18N
481 // user should not be null
484 throw new NullPointerException("user is null"); //NOI18N
488 Query query = this.getEntityManager().createNamedQuery("SearchUserByName", User.class); //NOI18N
491 query.setParameter("param", user.getUserName()); //NOI18N
495 User dummy = (User) query.getSingleResult();
498 this.getLoggerBeanLocal().logDebug(MessageFormat.format("isUserNameRegistered: dummy.id={0} found.", dummy.getUserId())); //NOI18N
499 } catch (final NoResultException ex) {
501 this.getLoggerBeanLocal().logDebug(MessageFormat.format("isUserNameRegistered: getSingleResult() returned no result: {0}", ex)); //NOI18N
503 // User name does not exist
505 } catch (final PersistenceException ex) {
506 // Something bad happened
507 this.getLoggerBeanLocal().logWarning(MessageFormat.format("More than one email address {0} found.", user.getUserContact().getContactEmailAddress()), ex); //NOI18N
518 public User linkUser (final User user) throws UserNameAlreadyRegisteredException, EmailAddressAlreadyRegisteredException {
520 this.getLoggerBeanLocal().logTrace(MessageFormat.format("linkUser: user={0} - CALLED!", user)); //NOI18N
522 // user should not be null
523 // @TODO Add check for email address
526 throw new NullPointerException("user is null"); //NOI18N
527 } else if (user.getUserId() instanceof Long) {
529 throw new IllegalArgumentException("user.userId is not null"); //NOI18N
530 } else if (user.getUserContact() == null) {
532 throw new NullPointerException("user.userContact is null"); //NOI18N
533 } else if (user.getUserContact().getContactId() == null) {
535 throw new NullPointerException("user.userContact.contactId is null"); //NOI18N
536 } else if (user.getUserContact().getContactId() < 1) {
537 // Not valid id number
538 throw new IllegalArgumentException(MessageFormat.format("user.userContact.contactId={0} is not valid", user.getUserContact().getContactId())); //NOI18N
539 } else if (user.getUserAccountStatus() == null) {
541 throw new NullPointerException("user.userAccountStatus is null"); //NOI18N
542 } else if (this.ifUserNameExists(user.getUserName())) {
543 // Name already found
544 throw new UserNameAlreadyRegisteredException(user.getUserName());
545 } else if (this.ifUserExists(user)) {
546 // User does not exist
547 throw new IllegalStateException("User does already exist."); //NOI18N
550 // Try to find the contact
551 Contact foundContact = this.getEntityManager().find(user.getUserContact().getClass(), user.getUserContact().getContactId());
553 // Set detached object in rexcruiter instance
554 user.setUserContact(foundContact);
557 user.setUserCreated(new GregorianCalendar());
560 this.getEntityManager().persist(user);
562 // Flush it to get updated instance back
563 this.getEntityManager().flush();
566 this.getLoggerBeanLocal().logTrace(MessageFormat.format("linkUser: user={0} - EXIT!", user)); //NOI18N
568 // Return updated instanc
573 public User updateUserData (final User user) {
575 this.getLoggerBeanLocal().logTrace(MessageFormat.format("updateUserData: user={0} - CALLED!", user)); //NOI18N
577 // user should not be null
580 throw new NullPointerException("user is null"); //NOI18N
581 } else if (user.getUserId() == null) {
583 throw new NullPointerException("user.userId is null"); //NOI18N
584 } else if (user.getUserId() < 1) {
586 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid.", user.getUserId())); //NOI18N
587 } else if (user.getUserAccountStatus() == null) {
589 throw new NullPointerException("user.userAccountStatus is null"); //NOI18N
590 } else if (!this.ifUserExists(user)) {
591 // User does not exist
592 throw new EJBException(MessageFormat.format("User with id {0} does not exist.", user.getUserId())); //NOI18N
595 // Remove contact instance as this is not updatedf
596 user.setUserContact(null);
599 User foundUser = this.getEntityManager().find(user.getClass(), user.getUserId());
602 assert (foundUser instanceof User) : MessageFormat.format("User with id {0} not found, but should be.", user.getUserId()); //NOI18N
605 User detachedUser = this.getEntityManager().merge(foundUser);
608 assert (detachedUser instanceof User) : MessageFormat.format("User with id {0} not merged, but should be.", user.getUserId()); //NOI18N
611 detachedUser.copyAll(user);
614 detachedUser.setUserUpdated(new GregorianCalendar());
616 // Return updated instance
621 public User updateUserPersonalData (final User user) {
623 this.getLoggerBeanLocal().logTrace(MessageFormat.format("updateUserPersonalData: user={0} - CALLED!", user)); //NOI18N
625 // user should not be null
628 throw new NullPointerException("user is null"); //NOI18N
629 } else if (user.getUserId() == null) {
631 throw new NullPointerException("user.userId is null"); //NOI18N
632 } else if (user.getUserId() < 1) {
634 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid.", user.getUserId())); //NOI18N
635 } else if (user.getUserAccountStatus() == null) {
637 throw new NullPointerException("user.userAccountStatus is null"); //NOI18N
638 } else if (!this.ifUserExists(user)) {
639 // User does not exist
640 throw new EJBException(MessageFormat.format("User with id {0} does not exist.", user.getUserId())); //NOI18N
644 User foundUser = this.getEntityManager().find(user.getClass(), user.getUserId());
647 assert (foundUser instanceof User) : MessageFormat.format("User with id {0} not found, but should be.", user.getUserId()); //NOI18N
650 User detachedUser = this.getEntityManager().merge(foundUser);
653 assert (detachedUser instanceof User) : MessageFormat.format("User with id {0} not merged, but should be.", user.getUserId()); //NOI18N
656 detachedUser.copyAll(user);
659 detachedUser.setUserUpdated(new GregorianCalendar());
660 detachedUser.getUserContact().setContactUpdated(new GregorianCalendar());
662 // Get contact from it and find it
663 Contact foundContact = this.getEntityManager().find(user.getUserContact().getClass(), user.getUserContact().getContactId());
666 assert (foundContact instanceof Contact) : MessageFormat.format("Contact with id {0} not found, but should be.", user.getUserContact().getContactId()); //NOI18N
669 this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: contact.contactId={0}", foundContact.getContactId())); //NOI18N
671 // Merge contact instance
672 Contact detachedContact = this.getEntityManager().merge(foundContact);
675 detachedContact.copyAll(user.getUserContact());
677 // Set it back in user
678 user.setUserContact(detachedContact);
681 assert (detachedContact instanceof Contact) : MessageFormat.format("Contact with id {0} not merged, but should be.", user.getUserContact().getContactId()); //NOI18N
683 // Get cellphone instance
684 DialableCellphoneNumber cellphone = detachedContact.getContactCellphoneNumber();
686 // Is there a cellphone instance set?
687 if (cellphone instanceof DialableCellphoneNumber) {
689 this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: cellphone.phoneId={0} is being updated ...", cellphone.getPhoneId())); //NOI18N
692 DialableCellphoneNumber foundCellphone = this.getEntityManager().find(cellphone.getClass(), cellphone.getPhoneId());
695 assert (foundCellphone instanceof DialableCellphoneNumber) : MessageFormat.format("Cellphone number with id {0} not found but should be.", foundCellphone.getPhoneId()); //NOI18N
697 // Then merge it, too
698 DialableCellphoneNumber detachedCellphone = this.getEntityManager().merge(foundCellphone);
701 assert (detachedCellphone instanceof DialableCellphoneNumber) : MessageFormat.format("Cellphone number with id {0} not found but should be.", detachedCellphone.getPhoneId()); //NOI18N
704 detachedCellphone.copyAll(user.getUserContact().getContactCellphoneNumber());
707 detachedContact.setContactCellphoneNumber(detachedCellphone);
710 // Get cellphone instance
711 DialableFaxNumber fax = detachedContact.getContactFaxNumber();
713 // Is there a fax instance set?
714 if (fax instanceof DialableFaxNumber) {
716 this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: fax.phoneId={0} is being updated ...", fax.getPhoneId())); //NOI18N
719 DialableFaxNumber foundFax = this.getEntityManager().find(fax.getClass(), fax.getPhoneId());
722 assert (foundFax instanceof DialableFaxNumber) : MessageFormat.format("Fax number with id {0} not found but should be.", foundFax.getPhoneId()); //NOI18N
724 // Then merge it, too
725 DialableFaxNumber detachedFax = this.getEntityManager().merge(foundFax);
728 assert (detachedFax instanceof DialableFaxNumber) : MessageFormat.format("Fax number with id {0} not found but should be.", detachedFax.getPhoneId()); //NOI18N
731 detachedFax.copyAll(user.getUserContact().getContactFaxNumber());
734 detachedContact.setContactFaxNumber(detachedFax);
737 // Get cellphone instance
738 DialableLandLineNumber landLine = detachedContact.getContactLandLineNumber();
740 // Is there a fax instance set?
741 if (landLine instanceof DialableLandLineNumber) {
743 this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: landLine.phoneId={0} is being updated ...", landLine.getPhoneId())); //NOI18N
746 DialableLandLineNumber foundLandLine = this.getEntityManager().find(landLine.getClass(), landLine.getPhoneId());
749 assert (foundLandLine instanceof DialableLandLineNumber) : MessageFormat.format("Land line number with id {0} not found but should be.", foundLandLine.getPhoneId()); //NOI18N
751 // Then merge it, too
752 DialableLandLineNumber detachedLandLine = this.getEntityManager().merge(foundLandLine);
755 assert (detachedLandLine instanceof DialableLandLineNumber) : MessageFormat.format("Land line number with id {0} not found but should be.", detachedLandLine.getPhoneId()); //NOI18N
758 detachedLandLine.copyAll(user.getUserContact().getContactLandLineNumber());
761 detachedContact.setContactLandLineNumber(detachedLandLine);
764 // Return updated user instance