2 * Copyright (C) 2016 - 2020 Free Software Foundation
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.Date;
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.jcontacts.model.contact.Contact;
29 import org.mxchange.jjobs.enterprise.BaseJobsEnterpriseBean;
30 import org.mxchange.jphone.model.phonenumbers.fax.DialableFaxNumber;
31 import org.mxchange.jphone.model.phonenumbers.fax.FaxNumbers;
32 import org.mxchange.jphone.model.phonenumbers.landline.DialableLandLineNumber;
33 import org.mxchange.jphone.model.phonenumbers.landline.LandLineNumbers;
34 import org.mxchange.jphone.model.phonenumbers.mobile.DialableMobileNumber;
35 import org.mxchange.jphone.model.phonenumbers.mobile.MobileNumbers;
36 import org.mxchange.jusercore.exceptions.UserNotFoundException;
37 import org.mxchange.jusercore.exceptions.UserStatusConfirmedException;
38 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
39 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
40 import org.mxchange.jusercore.model.user.password_history.PasswordHistory;
41 import org.mxchange.jusercore.model.user.password_history.UserPasswordHistory;
42 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
43 import org.mxchange.juserlogincore.model.user.register.UserRegistrationSessionBeanRemote;
48 * @author Roland Häder<roland@mxchange.org>
50 @Stateless (name = "user", description = "A bean handling the user data")
51 public class JobsUserSessionBean extends BaseJobsEnterpriseBean implements UserSessionBeanRemote {
56 private static final long serialVersionUID = 542_145_347_916L;
61 @EJB (lookup = "java:global/jjobs-ejb/userRegistration!org.mxchange.juserlogincore.model.user.register.UserRegistrationSessionBeanRemote")
62 private UserRegistrationSessionBeanRemote registerBean;
67 public JobsUserSessionBean () {
68 // Call super constructor
69 super("jms/jjobs-queue-factory", "jms/jjobs-email-queue"); //NOI18N
73 @SuppressWarnings ("unchecked")
75 public List<String> allUserNames () {
77 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.getUserNameList: CALLED!", this.getClass().getSimpleName())); //NOI18N
80 final Query query = this.getEntityManager().createNamedQuery("AllUserNames", String.class); //NOI18N
83 final List<String> userNameList = query.getResultList();
86 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.getUserNameList: userNameList.size()={1} - EXIT!", this.getClass().getSimpleName(), userNameList.size())); //NOI18N
93 @SuppressWarnings ("unchecked")
94 public List<User> allUsers () {
96 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.allUsers: CALLED!", this.getClass().getSimpleName())); //NOI18N
99 final Query query = this.getEntityManager().createNamedQuery("AllUsers", LoginUser.class); //NOI18N
102 final List<User> users = query.getResultList();
105 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.allUsers: users.size()={1} - EXIT!", this.getClass().getSimpleName(), users.size())); //NOI18N
112 public User confirmAccount (final User user, final String baseUrl) throws UserStatusConfirmedException, UserStatusLockedException {
114 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.confirmAccount: user={1},baseUrl={2} - CALLED!", this.getClass().getSimpleName(), user, baseUrl)); //NOI18N
116 // Parameter must be valid
119 throw new NullPointerException("user is null"); //NOI18N
120 } else if (user.getUserId() == null) {
122 throw new NullPointerException("user.userId is null"); //NOI18N
123 } else if (user.getUserId() < 1) {
125 throw new IllegalArgumentException(MessageFormat.format("userId is not valid: {0}", user.getUserId())); //NOI18N
126 } else if (user.getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
127 // Account is already confirmed
128 throw new UserStatusConfirmedException(user);
129 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
130 // Account is already confirmed
131 throw new UserStatusLockedException(user);
132 } else if (user.getUserConfirmKey() == null) {
134 throw new NullPointerException("user.userConfirmKey is null"); //NOI18N
135 } else if (null == baseUrl) {
137 throw new NullPointerException("baseUrl is null"); //NOI18N
138 } else if (baseUrl.isEmpty()) {
140 throw new IllegalArgumentException("baseUrl is empty"); //NOI18N
143 // Update user account
144 final User managedUser = this.updateUserData(user);
146 // Update user status and remove confirmation key
147 managedUser.setUserAccountStatus(UserAccountStatus.CONFIRMED);
148 managedUser.setUserConfirmKey(null);
149 managedUser.setUserUpdated(new Date());
152 this.sendEmail("User account confirmed", "user_account_confirmed", managedUser, baseUrl, null); //NOI18N
155 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.confirmAccount: managedUser={1} - EXIT!", this.getClass().getSimpleName(), managedUser)); //NOI18N
157 // Return updated instance
163 public User fillUserData (final User user) throws UserNotFoundException {
165 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.fillUserData: user={1} - CALLED!", this.getClass().getSimpleName(), user)); //NOI18N
167 // user should not be null
170 throw new NullPointerException("user is null"); //NOI18N
171 } else if (user.getUserName() == null) {
173 throw new NullPointerException("user.userName is null");
174 } else if (user.getUserName().isEmpty()) {
176 throw new IllegalArgumentException("user.userName is empty");
177 } else if (!this.ifUserExists(user)) {
178 // User does not exist
179 throw new UserNotFoundException(user);
183 final Query query = this.getEntityManager().createNamedQuery("SearchUserByName", LoginUser.class); //NOI18N
186 query.setParameter("param", user.getUserName()); //NOI18N
188 // Initialize variable
189 final User foundUser;
193 // Try to get single result
194 foundUser = (User) query.getSingleResult();
195 } catch (final NoResultException ex) {
197 this.getLoggerBeanLocal().logException(ex);
202 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.fillUserData: foundUser={1} - EXIT!", this.getClass().getSimpleName(), foundUser)); //NOI18N
204 // Return prepared instance
210 public String generateRandomUserName () {
212 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.generateRandomUserName - CALLED!", this.getClass().getSimpleName())); //NOI18N
215 final List<String> userList = this.allUserNames();
218 String userName = null;
220 // Loop until a user name is found
221 while ((userName == null) || (userList.contains(userName))) {
222 // Generate random name
223 userName = Users.generateRandomUserName();
227 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.generateRandomUserName: userName={1} - EXIT!", this.getClass().getSimpleName(), userName)); //NOI18N
229 // Found one, so return it
235 public boolean ifUserExists (final User user) {
237 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.ifUserExists: user={1} - CALLED!", this.getClass().getSimpleName(), user)); //NOI18N
239 // userId should not be null
242 throw new NullPointerException("user is null"); //NOI18N
243 } else if (user.getUserId() == null) {
245 throw new NullPointerException("user.userId is null"); //NOI18N
246 } else if (user.getUserId() < 1) {
248 throw new IllegalArgumentException(MessageFormat.format("userId is not valid: {0}", user.getUserId())); //NOI18N
252 final Query query = this.getEntityManager().createNamedQuery("SearchUserById", LoginUser.class); //NOI18N
255 query.setParameter("id", user.getUserId()); //NOI18N
259 // Try to get single result
260 final User dummy = (User) query.getSingleResult();
263 this.getLoggerBeanLocal().logDebug(MessageFormat.format("ifUserExists: dummy.id={0} found.", dummy.getUserId())); //NOI18N
264 } catch (final NoResultException ex) {
266 this.getLoggerBeanLocal().logDebug(MessageFormat.format("ifUserExists: getSingleResult() returned no result: {0}", ex)); //NOI18N
268 // User name does not exist
270 } catch (final PersistenceException ex) {
271 // Something bad happened
272 this.getLoggerBeanLocal().logWarning(MessageFormat.format("More than one user {0} found.", user, ex)); //NOI18N
279 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.ifUserExists: Found user {1} - EXIT!", this.getClass().getSimpleName(), user)); //NOI18N
286 public boolean ifUserNameExists (final String userName) {
288 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.ifUserNameExists: userName={1} - CALLED!", this.getClass().getSimpleName(), userName)); //NOI18N
290 // userId should not be null
291 if (null == userName) {
293 throw new NullPointerException("userName is null"); //NOI18N
294 } else if (userName.isEmpty()) {
296 throw new NullPointerException("userName is empty"); //NOI18N
300 final Query query = this.getEntityManager().createNamedQuery("SearchUserByName", LoginUser.class); //NOI18N
303 query.setParameter("param", userName); //NOI18N
307 // Try to get single result
308 final User dummy = (User) query.getSingleResult();
311 this.getLoggerBeanLocal().logDebug(MessageFormat.format("{0}.ifUserNameExists: dummy.userId={1} found.", this.getClass().getSimpleName(), dummy.getUserId())); //NOI18N
312 } catch (final NoResultException ex) {
314 this.getLoggerBeanLocal().logDebug(MessageFormat.format("{0}.ifUserNameExists: getSingleResult() returned no result: {1}", this.getClass().getSimpleName(), ex)); //NOI18N
316 // User name does not exist
321 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.ifUserNameExists: Found userName={1} - EXIT!", this.getClass().getSimpleName(), userName)); //NOI18N
328 public boolean isEmailAddressRegistered (final User user) {
330 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.isEmailAddressRegistered: user={1} - CALLED!", this.getClass().getSimpleName(), user)); //NOI18N
332 // user should not be null
335 throw new NullPointerException("user is null"); //NOI18N
339 final Query query = this.getEntityManager().createNamedQuery("SearchUserByEmailAddress", LoginUser.class); //NOI18N
342 query.setParameter("param", user.getUserContact().getContactEmailAddress()); //NOI18N
346 // Try to get single result
347 final User dummy = (User) query.getSingleResult();
350 this.getLoggerBeanLocal().logDebug(MessageFormat.format("{0}.isEmailAddressRegistered: dummy.userId={1} found.", this.getClass().getSimpleName(), dummy.getUserId())); //NOI18N
351 } catch (final NoResultException ex) {
353 this.getLoggerBeanLocal().logDebug(MessageFormat.format("{0}.isEmailAddressRegistered: getSingleResult() returned no result: {1}", this.getClass().getSimpleName(), ex)); //NOI18N
355 // Email address does not exist
357 } catch (final PersistenceException ex) {
358 // Something bad happened
359 this.getLoggerBeanLocal().logWarning(MessageFormat.format("More than one email address {0} found.", user.getUserContact().getContactEmailAddress()), ex); //NOI18N
366 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.isEmailAddressRegistered: Returning true ... - EXIT!", this.getClass().getSimpleName())); //NOI18N
373 public boolean isUserNameRegistered (final User user) {
375 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.isUserNameRegistered: user={1} - CALLED!", this.getClass().getSimpleName(), user)); //NOI18N
377 // user should not be null
380 throw new NullPointerException("user is null"); //NOI18N
384 final Query query = this.getEntityManager().createNamedQuery("SearchUserByName", LoginUser.class); //NOI18N
387 query.setParameter("param", user.getUserName()); //NOI18N
391 // Try to get single result
392 final User dummy = (User) query.getSingleResult();
395 this.getLoggerBeanLocal().logDebug(MessageFormat.format("{0}.isUserNameRegistered: dummy.userId={1} found.", this.getClass().getSimpleName(), dummy.getUserId())); //NOI18N
396 } catch (final NoResultException ex) {
398 this.getLoggerBeanLocal().logDebug(MessageFormat.format("{0}.isUserNameRegistered: getSingleResult() returned no result: {1}", this.getClass().getSimpleName(), ex)); //NOI18N
400 // User name does not exist
402 } catch (final PersistenceException ex) {
403 // Something bad happened
404 this.getLoggerBeanLocal().logWarning(MessageFormat.format("More than one email address {0} found.", user.getUserContact().getContactEmailAddress()), ex); //NOI18N
411 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.isUserNameRegistered: Returning true ... - EXIT!", this.getClass().getSimpleName())); //NOI18N
418 public User updateUserData (final User user) {
420 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserData: user={1} - CALLED!", this.getClass().getSimpleName(), user)); //NOI18N
422 // user should not be null
425 throw new NullPointerException("user is null"); //NOI18N
426 } else if (user.getUserId() == null) {
428 throw new NullPointerException("user.userId is null"); //NOI18N
429 } else if (user.getUserId() < 1) {
431 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid.", user.getUserId())); //NOI18N
432 } else if (user.getUserAccountStatus() == null) {
434 throw new NullPointerException("user.userAccountStatus is null"); //NOI18N
435 } else if (!this.ifUserExists(user)) {
436 // User does not exist
437 throw new EJBException(MessageFormat.format("User with id {0} does not exist.", user.getUserId())); //NOI18N
441 final User foundUser = this.getEntityManager().find(user.getClass(), user.getUserId());
444 assert (foundUser instanceof User) : MessageFormat.format("User with id {0} not found, but should be.", user.getUserId()); //NOI18N
447 final User managedUser = this.getEntityManager().merge(foundUser);
450 assert (managedUser instanceof User) : MessageFormat.format("User with id {0} not found, but should be.", user.getUserId()); //NOI18N
453 Users.copyAll(managedUser, managedUser);
456 managedUser.setUserUpdated(new Date());
459 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserData: managedUser={1} - EXIT!", this.getClass().getSimpleName(), managedUser)); //NOI18N
461 // Return updated instance
466 public PasswordHistory updateUserPassword (final User user, final String baseUrl) throws UserNotFoundException, UserStatusUnconfirmedException, UserStatusLockedException {
468 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserPassword: user={1},baseUrl={2} - CALLED!", this.getClass().getSimpleName(), user, baseUrl)); //NOI18N
470 // user should not be null
473 throw new NullPointerException("user is null"); //NOI18N
474 } else if (user.getUserId() == null) {
476 throw new NullPointerException("user.userId is null"); //NOI18N
477 } else if (user.getUserId() < 1) {
479 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid.", user.getUserId())); //NOI18N
480 } else if (user.getUserName() == null) {
482 throw new NullPointerException("user.userName is null"); //NOI18N
483 } else if (user.getUserName().isEmpty()) {
485 throw new IllegalArgumentException("user.userName is empty"); //NOI18N
486 } else if (user.getUserAccountStatus() == null) {
488 throw new NullPointerException("user.userAccountStatus is null"); //NOI18N
489 } else if (user.getUserContact() == null) {
491 throw new NullPointerException("user.userContact is null"); //NOI18N
492 } else if (user.getUserContact().getContactId() == null) {
494 throw new NullPointerException("user.userContact.contactId is null"); //NOI18N
495 } else if (user.getUserContact().getContactId() < 1) {
497 throw new IllegalArgumentException(MessageFormat.format("user.userContact.contactId={0} is invalid", user.getUserContact().getContactId())); //NOI18N
498 } else if (user.getUserContact().getContactPersonalTitle() == null) {
500 throw new NullPointerException("user.userContact.contactPersonalTitle is null"); //NOI18N
501 } else if (!this.ifUserExists(user)) {
502 // User does not exist
503 throw new EJBException(MessageFormat.format("User with id {0} does not exist.", user.getUserId())); //NOI18N
504 } else if (null == baseUrl) {
506 throw new NullPointerException("baseUrl is null"); //NOI18N
507 } else if (baseUrl.isEmpty()) {
509 throw new IllegalArgumentException("baseUrl is empty"); //NOI18N
513 final User managedUser = this.updateUserData(user);
515 // Update user account
516 managedUser.setUserUpdated(new Date());
518 // Create history entry
519 PasswordHistory entry = new UserPasswordHistory(user.getUserEncryptedPassword(), managedUser);
521 // Set created timestamp
522 entry.setUserPasswordHistoryCreated(new Date());
524 // Merge user to make sure it is not re-persisted
525 final User mergedUser = this.getEntityManager().merge(managedUser);
526 entry.setUserPasswordHistoryUser(mergedUser);
529 this.getEntityManager().persist(entry);
531 // Send email to user
532 this.sendEmail("User password change", "user_password_change", managedUser, baseUrl, null); //NOI18N
535 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserPassword: entry.userPasswordHistoryId={1} - EXIT!", this.getClass().getSimpleName(), entry.getUserPasswordHistoryId())); //NOI18N
542 public User updateUserPersonalData (final User user) {
544 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserPersonalData: user={1} - CALLED!", this.getClass().getSimpleName(), user)); //NOI18N
546 // user should not be null
549 throw new NullPointerException("user is null"); //NOI18N
550 } else if (user.getUserId() == null) {
552 throw new NullPointerException("user.userId is null"); //NOI18N
553 } else if (user.getUserId() < 1) {
555 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid.", user.getUserId())); //NOI18N
556 } else if (user.getUserAccountStatus() == null) {
558 throw new NullPointerException("user.userAccountStatus is null"); //NOI18N
559 } else if (!this.ifUserExists(user)) {
560 // User does not exist
561 throw new EJBException(MessageFormat.format("User with id {0} does not exist.", user.getUserId())); //NOI18N
565 final User managedUser = this.getEntityManager().find(user.getClass(), user.getUserId());
568 assert (managedUser instanceof User) : MessageFormat.format("User with id {0} not found, but should be.", user.getUserId()); //NOI18N
571 Users.copyAll(user, managedUser);
574 managedUser.setUserUpdated(new Date());
577 final Contact managedContact = this.mergeContactData(managedUser.getUserContact());
579 // Set it back in user
580 managedUser.setUserContact(managedContact);
583 assert (managedContact instanceof Contact) : MessageFormat.format("Contact with id {0} not merged, but should be.", managedUser.getUserContact().getContactId()); //NOI18N
585 // Get mobile instance
586 final DialableMobileNumber mobileNumber = managedContact.getContactMobileNumber();
588 // Is there a mobile instance set?
589 if (mobileNumber instanceof DialableMobileNumber) {
591 this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: mobile.phoneId={0} is being updated ...", mobileNumber.getMobileId())); //NOI18N
594 final DialableMobileNumber foundMobile = this.getEntityManager().find(mobileNumber.getClass(), mobileNumber.getMobileId());
597 assert (foundMobile instanceof DialableMobileNumber) : MessageFormat.format("Mobile number with id {0} not found but should be.", foundMobile.getMobileId()); //NOI18N
600 MobileNumbers.copyMobileNumber(managedUser.getUserContact().getContactMobileNumber(), foundMobile);
602 // Then merge it, too
603 final DialableMobileNumber managedMobile = this.getEntityManager().merge(foundMobile);
606 assert (managedMobile instanceof DialableMobileNumber) : MessageFormat.format("Mobile number with id {0} not found but should be.", managedMobile.getMobileId()); //NOI18N
609 managedContact.setContactMobileNumber(managedMobile);
612 // Get mobile instance
613 final DialableFaxNumber faxNumber = managedContact.getContactFaxNumber();
615 // Is there a fax instance set?
616 if (faxNumber instanceof DialableFaxNumber) {
618 this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: fax.phoneId={0} is being updated ...", faxNumber.getPhoneId())); //NOI18N
621 final DialableFaxNumber foundFax = this.getEntityManager().find(faxNumber.getClass(), faxNumber.getPhoneId());
624 assert (foundFax instanceof DialableFaxNumber) : MessageFormat.format("Fax number with id {0} not found but should be.", foundFax.getPhoneId()); //NOI18N
627 FaxNumbers.copyFaxNumber(managedUser.getUserContact().getContactFaxNumber(), foundFax);
629 // Then merge it, too
630 final DialableFaxNumber managedFax = this.getEntityManager().merge(foundFax);
633 assert (managedFax instanceof DialableFaxNumber) : MessageFormat.format("Fax number with id {0} not found but should be.", managedFax.getPhoneId()); //NOI18N
636 managedContact.setContactFaxNumber(managedFax);
639 // Get mobile instance
640 final DialableLandLineNumber landLineNumber = managedContact.getContactLandLineNumber();
642 // Is there a fax instance set?
643 if (landLineNumber instanceof DialableLandLineNumber) {
645 this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: landLine.phoneId={0} is being updated ...", landLineNumber.getPhoneId())); //NOI18N
648 final DialableLandLineNumber foundLandLine = this.getEntityManager().find(landLineNumber.getClass(), landLineNumber.getPhoneId());
651 assert (foundLandLine instanceof DialableLandLineNumber) : MessageFormat.format("Land line number with id {0} not found but should be.", foundLandLine.getPhoneId()); //NOI18N
654 LandLineNumbers.copyLandLineNumber(managedUser.getUserContact().getContactLandLineNumber(), foundLandLine);
656 // Then merge it, too
657 final DialableLandLineNumber managedLandLine = this.getEntityManager().merge(foundLandLine);
660 assert (managedLandLine instanceof DialableLandLineNumber) : MessageFormat.format("Land line number with id {0} not found but should be.", managedLandLine.getPhoneId()); //NOI18N
663 managedContact.setContactLandLineNumber(managedLandLine);
667 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserPersonalData: entry.managedUser={1} - EXIT!", this.getClass().getSimpleName(), managedUser)); //NOI18N
669 // Return updated user instance