]> git.mxchange.org Git - jjobs-ejb.git/blob - src/java/org/mxchange/jusercore/model/user/JobsUserSessionBean.java
Don't cherry-pick:
[jjobs-ejb.git] / src / java / org / mxchange / jusercore / model / user / JobsUserSessionBean.java
1 /*
2  * Copyright (C) 2016 - 2022 Free Software Foundation
3  *
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.
8  *
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.
13  *
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/>.
16  */
17 package org.mxchange.jusercore.model.user;
18
19 import java.text.MessageFormat;
20 import java.util.Date;
21 import java.util.List;
22 import java.util.Objects;
23 import javax.ejb.EJBException;
24 import javax.ejb.Stateless;
25 import javax.persistence.Query;
26 import org.mxchange.jcontacts.model.contact.Contact;
27 import org.mxchange.jjobs.enterprise.BaseJobsEnterpriseBean;
28 import org.mxchange.jphone.model.phonenumbers.fax.DialableFaxNumber;
29 import org.mxchange.jphone.model.phonenumbers.landline.DialableLandLineNumber;
30 import org.mxchange.jphone.model.phonenumbers.mobile.DialableMobileNumber;
31 import org.mxchange.jphone.model.utils.FaxNumberUtils;
32 import org.mxchange.jphone.model.utils.LandLineNumberUtils;
33 import org.mxchange.jphone.model.utils.MobileNumberUtils;
34 import org.mxchange.jusercore.exceptions.UserNotFoundException;
35 import org.mxchange.jusercore.exceptions.UserStatusConfirmedException;
36 import org.mxchange.jusercore.exceptions.UserStatusLockedException;
37 import org.mxchange.jusercore.exceptions.UserStatusUnconfirmedException;
38 import org.mxchange.jusercore.model.user.password_history.PasswordHistory;
39 import org.mxchange.jusercore.model.user.password_history.UserPasswordHistory;
40 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
41 import org.mxchange.jusercore.model.utils.UserUtils;
42
43 /**
44  * A user EJB
45  * <p>
46  * @author Roland Häder<roland@mxchange.org>
47  */
48 @Stateless (name = "user", description = "A bean handling the user data")
49 public class JobsUserSessionBean extends BaseJobsEnterpriseBean implements UserSessionBeanRemote {
50
51         /**
52          * Serial number
53          */
54         private static final long serialVersionUID = 542_145_347_916L;
55
56         /**
57          * Default constructor
58          */
59         public JobsUserSessionBean () {
60                 // Call super constructor
61                 super("jms/jjobs-queue-factory", "jms/jjobs-email-queue"); //NOI18N
62         }
63
64         @Override
65         public User confirmAccount (final User user, final String baseUrl) throws UserStatusConfirmedException, UserStatusLockedException, UserNotFoundException {
66                 // Trace message
67                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.confirmAccount: user={1},baseUrl={2} - CALLED!", this.getClass().getSimpleName(), user, baseUrl)); //NOI18N
68
69                 // Parameter must be valid
70                 if (null == user) {
71                         // Abort here
72                         throw new NullPointerException("user is null"); //NOI18N
73                 } else if (user.getUserId() == null) {
74                         // Abort here
75                         throw new NullPointerException("user.userId is null"); //NOI18N
76                 } else if (user.getUserId() < 1) {
77                         // Invalid number
78                         throw new IllegalArgumentException(MessageFormat.format("userId is not valid: {0}", user.getUserId())); //NOI18N
79                 } else if (user.getUserAccountStatus() == UserAccountStatus.CONFIRMED) {
80                         // Account is already confirmed
81                         throw new UserStatusConfirmedException(user);
82                 } else if (user.getUserAccountStatus() == UserAccountStatus.LOCKED) {
83                         // Account is already confirmed
84                         throw new UserStatusLockedException(user);
85                 } else if (user.getUserConfirmKey() == null) {
86                         // Throw NPE
87                         throw new NullPointerException("user.userConfirmKey is null"); //NOI18N
88                 } else if (null == baseUrl) {
89                         // Throw it again
90                         throw new NullPointerException("baseUrl is null"); //NOI18N
91                 } else if (baseUrl.isEmpty()) {
92                         // Throw IAE
93                         throw new IllegalArgumentException("baseUrl is empty"); //NOI18N
94                 }
95
96                 // Update user account
97                 final User managedUser = this.updateUserData(user);
98
99                 // Update user status and remove confirmation key
100                 managedUser.setUserAccountStatus(UserAccountStatus.CONFIRMED);
101                 managedUser.setUserConfirmKey(null);
102                 managedUser.setUserEntryUpdated(new Date());
103
104                 // Send out email
105                 this.sendEmail("User account confirmed", "user_account_confirmed", managedUser, baseUrl, null); //NOI18N
106
107                 // Trace message
108                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.confirmAccount: managedUser={1} - EXIT!", this.getClass().getSimpleName(), managedUser)); //NOI18N
109
110                 // Return updated instance
111                 return managedUser;
112         }
113
114         @Override
115         @SuppressWarnings ("unchecked")
116         public List<User> fetchAllUsers () {
117                 // Trace message
118                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.allUsers: CALLED!", this.getClass().getSimpleName())); //NOI18N
119
120                 // Get named query
121                 final Query query = this.getEntityManager().createNamedQuery("AllUsers", LoginUser.class); //NOI18N
122
123                 // Get result
124                 final List<User> users = query.getResultList();
125
126                 // Trace message
127                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.allUsers: users.size()={1} - EXIT!", this.getClass().getSimpleName(), users.size())); //NOI18N
128
129                 // Return full list
130                 return users;
131         }
132
133         @Override
134         public boolean ifUserExists (final User user) {
135                 // Trace message
136                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.ifUserExists: user={1} - CALLED!", this.getClass().getSimpleName(), user)); //NOI18N
137
138                 // userId should not be null
139                 if (null == user) {
140                         // Abort here
141                         throw new NullPointerException("user is null"); //NOI18N
142                 } else if (user.getUserId() == null) {
143                         // Abort here
144                         throw new NullPointerException("user.userId is null"); //NOI18N
145                 } else if (user.getUserId() < 1) {
146                         // Invalid number
147                         throw new IllegalArgumentException(MessageFormat.format("userId is not valid: {0}", user.getUserId())); //NOI18N
148                 }
149
150                 // Default is not found
151                 boolean isFound = false;
152
153                 // Fetch whole list
154                 for (final User currentUser : this.fetchAllUsers()) {
155                         /*
156                          * E.g. userAccountStatus can be fifferent because lockUserAccount
157                          * is setting it BEFORE this method is invoked. So this is enough
158                          * for us in this case. But otherwise e.g. when a new user is
159                          * created with same data, then this method must return FALSE even
160                          * when userId is currently NULL.
161                          */
162                         //* NOISY-DEBUG: */ this.getLoggerBeanLocal().logDebug(MessageFormat.format("{0}.ifUserExists: currentUser={1},currentUser.userId={2}", this.getClass(), currentUser, currentUser.getUserId())); //NOI18N
163                         if ((Objects.equals(user.getUserId(), currentUser.getUserId()) && user.getUserId() != null) || Objects.equals(user, currentUser)) {
164                                 // Yes, then set flag and exit iteration
165                                 isFound = true;
166                                 break;
167                         }
168                 }
169
170                 // Trace message
171                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.ifUserExists: isFound={1} - EXIT!", this.getClass().getSimpleName(), isFound)); //NOI18N
172
173                 // Return flag
174                 return isFound;
175         }
176
177         @Override
178         public boolean ifUserNameExists (final String userName) {
179                 // Trace message
180                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.ifUserNameExists: userName={1} - CALLED!", this.getClass().getSimpleName(), userName)); //NOI18N
181
182                 // userId should not be null
183                 if (null == userName) {
184                         // Abort here
185                         throw new NullPointerException("userName is null"); //NOI18N
186                 } else if (userName.isEmpty()) {
187                         // Abort here
188                         throw new NullPointerException("userName is empty"); //NOI18N
189                 }
190
191                 // Default is not registered
192                 boolean isRegistered = false;
193
194                 // Iterate over all records
195                 for (final User currentUser : this.fetchAllUsers()) {
196                         // Does the username match?
197                         if (userName.equals(currentUser.getUserName())) {
198                                 // Yes, then set flag and exit iteration
199                                 isRegistered = true;
200                                 break;
201                         }
202                 }
203
204                 // Trace message
205                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.ifUserNameExists: isRegistered={1} - EXIT!", this.getClass().getSimpleName(), isRegistered)); //NOI18N
206
207                 // Found it
208                 return true;
209         }
210
211         @Override
212         public boolean isEmailAddressRegistered (final User user) {
213                 // Trace message
214                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.isEmailAddressRegistered: user={1} - CALLED!", this.getClass().getSimpleName(), user)); //NOI18N
215
216                 // user should not be null
217                 if (null == user) {
218                         // Abort here
219                         throw new NullPointerException("user is null"); //NOI18N
220                 }
221
222                 // Default is not registered
223                 boolean isRegistered = false;
224
225                 // Iterate over all records
226                 for (final User currentUser : this.fetchAllUsers()) {
227                         // Does the email address match?
228                         if (user.getUserContact().getContactEmailAddress().equals(currentUser.getUserContact().getContactEmailAddress())) {
229                                 // Yes, then set flag and exit iteration
230                                 isRegistered = true;
231                                 break;
232                         }
233                 }
234
235                 // Trace message
236                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.isEmailAddressRegistered: isRegistered={1} - EXIT!", this.getClass().getSimpleName(), isRegistered)); //NOI18N
237
238                 // Found it
239                 return isRegistered;
240         }
241
242         @Override
243         public boolean isUserNameRegistered (final User user) {
244                 // Trace message
245                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.isUserNameRegistered: user={1} - CALLED!", this.getClass().getSimpleName(), user)); //NOI18N
246
247                 // user should not be null
248                 if (null == user) {
249                         // Abort here
250                         throw new NullPointerException("user is null"); //NOI18N
251                 }
252
253                 // Ask other method
254                 final boolean isRegistered = this.ifUserNameExists(user.getUserName());
255
256                 // Trace message
257                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.isUserNameRegistered: isRegistered={1} - EXIT!", this.getClass().getSimpleName(), isRegistered)); //NOI18N
258
259                 // Return flag
260                 return isRegistered;
261         }
262
263         @Override
264         public User updateUserData (final User user) throws UserNotFoundException {
265                 // Trace message
266                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserData: user={1} - CALLED!", this.getClass().getSimpleName(), user)); //NOI18N
267
268                 // user should not be null
269                 if (null == user) {
270                         // Abort here
271                         throw new NullPointerException("user is null"); //NOI18N
272                 } else if (user.getUserId() == null) {
273                         // Throw NPE again
274                         throw new NullPointerException("user.userId is null"); //NOI18N
275                 } else if (user.getUserId() < 1) {
276                         // Not valid
277                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid.", user.getUserId())); //NOI18N
278                 } else if (user.getUserAccountStatus() == null) {
279                         // Throw NPE again
280                         throw new NullPointerException("user.userAccountStatus is null"); //NOI18N
281                 } else if (!this.ifUserExists(user)) {
282                         // User does not exist
283                         throw new UserNotFoundException(user.getUserId());
284                 }
285
286                 // Find the instance
287                 final User foundUser = this.getEntityManager().find(user.getClass(), user.getUserId());
288
289                 // Should be found!
290                 assert (foundUser instanceof User) : MessageFormat.format("User with id {0} not found, but should be.", user.getUserId()); //NOI18N
291
292                 // Copy all data
293                 UserUtils.copyUserData(user, foundUser);
294
295                 // Merge user
296                 final User managedUser = this.getEntityManager().merge(foundUser);
297
298                 // Should be found!
299                 assert (managedUser instanceof User) : MessageFormat.format("User with id {0} not found, but should be.", user.getUserId()); //NOI18N
300
301                 // Set as updated
302                 managedUser.setUserEntryUpdated(new Date());
303
304                 // Trace message
305                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserData: managedUser={1} - EXIT!", this.getClass().getSimpleName(), managedUser)); //NOI18N
306
307                 // Return updated instance
308                 return managedUser;
309         }
310
311         @Override
312         public PasswordHistory updateUserPassword (final User user, final String baseUrl) throws UserNotFoundException, UserStatusUnconfirmedException, UserStatusLockedException {
313                 // Trace message
314                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserPassword: user={1},baseUrl={2} - CALLED!", this.getClass().getSimpleName(), user, baseUrl)); //NOI18N
315
316                 // user should not be null
317                 if (null == user) {
318                         // Throw NPE
319                         throw new NullPointerException("user is null"); //NOI18N
320                 } else if (user.getUserId() == null) {
321                         // Throw NPE again
322                         throw new NullPointerException("user.userId is null"); //NOI18N
323                 } else if (user.getUserId() < 1) {
324                         // Not valid number
325                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid.", user.getUserId())); //NOI18N
326                 } else if (user.getUserName() == null) {
327                         // Throw NPE again
328                         throw new NullPointerException("user.userName is null"); //NOI18N
329                 } else if (user.getUserName().isEmpty()) {
330                         // Empty string
331                         throw new IllegalArgumentException("user.userName is empty"); //NOI18N
332                 } else if (user.getUserAccountStatus() == null) {
333                         // Throw NPE
334                         throw new NullPointerException("user.userAccountStatus is null"); //NOI18N
335                 } else if (user.getUserContact() == null) {
336                         // Throw it again
337                         throw new NullPointerException("user.userContact is null"); //NOI18N
338                 } else if (user.getUserContact().getContactId() == null) {
339                         // .. and again
340                         throw new NullPointerException("user.userContact.contactId is null"); //NOI18N
341                 } else if (user.getUserContact().getContactId() < 1) {
342                         // Invalid id
343                         throw new IllegalArgumentException(MessageFormat.format("user.userContact.contactId={0} is invalid", user.getUserContact().getContactId())); //NOI18N
344                 } else if (user.getUserContact().getContactPersonalTitle() == null) {
345                         // Throw NPE again
346                         throw new NullPointerException("user.userContact.contactPersonalTitle is null"); //NOI18N
347                 } else if (!this.ifUserExists(user)) {
348                         // User does not exist
349                         throw new EJBException(MessageFormat.format("User with id {0} does not exist.", user.getUserId())); //NOI18N
350                 } else if (null == baseUrl) {
351                         // Throw it again
352                         throw new NullPointerException("baseUrl is null"); //NOI18N
353                 } else if (baseUrl.isEmpty()) {
354                         // Invalid parameter
355                         throw new IllegalArgumentException("baseUrl is empty"); //NOI18N
356                 }
357
358                 // Call other method
359                 final User managedUser = this.updateUserData(user);
360
361                 // Update user account
362                 managedUser.setUserEntryUpdated(new Date());
363
364                 // Create history entry
365                 final PasswordHistory entry = new UserPasswordHistory(user.getUserEncryptedPassword(), managedUser);
366
367                 // Set created timestamp
368                 entry.setUserPasswordHistoryCreated(new Date());
369
370                 // Merge user to make sure it is not re-persisted
371                 final User mergedUser = this.getEntityManager().merge(managedUser);
372                 entry.setUserPasswordHistoryUser(mergedUser);
373
374                 // Persist it
375                 this.getEntityManager().persist(entry);
376
377                 // Send email to user
378                 this.sendEmail("User password change", "user_password_change", managedUser, baseUrl, null); //NOI18N
379
380                 // Trace message
381                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserPassword: entry.userPasswordHistoryId={1} - EXIT!", this.getClass().getSimpleName(), entry.getUserPasswordHistoryId())); //NOI18N
382
383                 // Return it
384                 return entry;
385         }
386
387         @Override
388         public User updateUserPersonalData (final User user) {
389                 // Trace message
390                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserPersonalData: user={1} - CALLED!", this.getClass().getSimpleName(), user)); //NOI18N
391
392                 // user should not be null
393                 if (null == user) {
394                         // Abort here
395                         throw new NullPointerException("user is null"); //NOI18N
396                 } else if (user.getUserId() == null) {
397                         // Throw NPE again
398                         throw new NullPointerException("user.userId is null"); //NOI18N
399                 } else if (user.getUserId() < 1) {
400                         // Not valid
401                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid.", user.getUserId())); //NOI18N
402                 } else if (user.getUserAccountStatus() == null) {
403                         // Throw NPE again
404                         throw new NullPointerException("user.userAccountStatus is null"); //NOI18N
405                 } else if (!this.ifUserExists(user)) {
406                         // User does not exist
407                         throw new EJBException(MessageFormat.format("User with id {0} does not exist.", user.getUserId())); //NOI18N
408                 }
409
410                 // Find the instance
411                 final User managedUser = this.getEntityManager().find(user.getClass(), user.getUserId());
412
413                 // Should be found!
414                 assert (managedUser instanceof User) : MessageFormat.format("User with id {0} not found, but should be.", user.getUserId()); //NOI18N
415
416                 // Copy all data
417                 UserUtils.copyUserData(user, managedUser);
418
419                 // Set as updated
420                 managedUser.setUserEntryUpdated(new Date());
421
422                 // Update user data
423                 final Contact managedContact = this.mergeContactData(managedUser.getUserContact());
424
425                 // Set it back in user
426                 managedUser.setUserContact(managedContact);
427
428                 // Should be found!
429                 assert (managedContact instanceof Contact) : MessageFormat.format("Contact with id {0} not merged, but should be.", managedUser.getUserContact().getContactId()); //NOI18N
430
431                 // Get mobile instance
432                 final DialableMobileNumber mobileNumber = managedContact.getContactMobileNumber();
433
434                 // Is there a  mobile instance set?
435                 if (mobileNumber instanceof DialableMobileNumber) {
436                         // Debug message
437                         this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: mobile.phoneId={0} is being updated ...", mobileNumber.getMobileId())); //NOI18N
438
439                         // Then find it, too
440                         final DialableMobileNumber foundMobile = this.getEntityManager().find(mobileNumber.getClass(), mobileNumber.getMobileId());
441
442                         // Should be there
443                         assert (foundMobile instanceof DialableMobileNumber) : MessageFormat.format("Mobile number with id {0} not found but should be.", foundMobile.getMobileId()); //NOI18N
444
445                         // Copy all
446                         MobileNumberUtils.copyMobileNumberData(managedUser.getUserContact().getContactMobileNumber(), foundMobile);
447
448                         // Then merge it, too
449                         final DialableMobileNumber managedMobile = this.getEntityManager().merge(foundMobile);
450
451                         // Should be there
452                         assert (managedMobile instanceof DialableMobileNumber) : MessageFormat.format("Mobile number with id {0} not found but should be.", managedMobile.getMobileId()); //NOI18N
453
454                         // Set it back
455                         managedContact.setContactMobileNumber(managedMobile);
456                 }
457
458                 // Get mobile instance
459                 final DialableFaxNumber faxNumber = managedContact.getContactFaxNumber();
460
461                 // Is there a  fax instance set?
462                 if (faxNumber instanceof DialableFaxNumber) {
463                         // Debug message
464                         this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: fax.phoneId={0} is being updated ...", faxNumber.getPhoneId())); //NOI18N
465
466                         // Then find it, too
467                         final DialableFaxNumber foundFax = this.getEntityManager().find(faxNumber.getClass(), faxNumber.getPhoneId());
468
469                         // Should be there
470                         assert (foundFax instanceof DialableFaxNumber) : MessageFormat.format("Fax number with id {0} not found but should be.", foundFax.getPhoneId()); //NOI18N
471
472                         // Copy all
473                         FaxNumberUtils.copyFaxNumberData(managedUser.getUserContact().getContactFaxNumber(), foundFax);
474
475                         // Then merge it, too
476                         final DialableFaxNumber managedFax = this.getEntityManager().merge(foundFax);
477
478                         // Should be there
479                         assert (managedFax instanceof DialableFaxNumber) : MessageFormat.format("Fax number with id {0} not found but should be.", managedFax.getPhoneId()); //NOI18N
480
481                         // Set it back
482                         managedContact.setContactFaxNumber(managedFax);
483                 }
484
485                 // Get mobile instance
486                 final DialableLandLineNumber landLineNumber = managedContact.getContactLandLineNumber();
487
488                 // Is there a  fax instance set?
489                 if (landLineNumber instanceof DialableLandLineNumber) {
490                         // Debug message
491                         this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: landLine.phoneId={0} is being updated ...", landLineNumber.getPhoneId())); //NOI18N
492
493                         // Then find it, too
494                         final DialableLandLineNumber foundLandLine = this.getEntityManager().find(landLineNumber.getClass(), landLineNumber.getPhoneId());
495
496                         // Should be there
497                         assert (foundLandLine instanceof DialableLandLineNumber) : MessageFormat.format("Land line number with id {0} not found but should be.", foundLandLine.getPhoneId()); //NOI18N
498
499                         // Copy all
500                         LandLineNumberUtils.copyLandLineNumberData(managedUser.getUserContact().getContactLandLineNumber(), foundLandLine);
501
502                         // Then merge it, too
503                         final DialableLandLineNumber managedLandLine = this.getEntityManager().merge(foundLandLine);
504
505                         // Should be there
506                         assert (managedLandLine instanceof DialableLandLineNumber) : MessageFormat.format("Land line number with id {0} not found but should be.", managedLandLine.getPhoneId()); //NOI18N
507
508                         // Set it back
509                         managedContact.setContactLandLineNumber(managedLandLine);
510                 }
511
512                 // Trace message
513                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserPersonalData: entry.managedUser={1} - EXIT!", this.getClass().getSimpleName(), managedUser)); //NOI18N
514
515                 // Return updated user instance
516                 return managedUser;
517         }
518
519 }