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