]> git.mxchange.org Git - addressbook-ejb.git/blob - src/java/org/mxchange/jusercore/model/user/AddressbookUserSessionBean.java
Updated copyright year
[addressbook-ejb.git] / src / java / org / mxchange / jusercore / model / user / AddressbookUserSessionBean.java
1 /*
2  * Copyright (C) 2016 - 2024 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.addressbook.enterprise.BaseAddressbookEnterpriseBean;
27 import org.mxchange.jcontacts.model.contact.Contact;
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 AddressbookUserSessionBean extends BaseAddressbookEnterpriseBean implements UserSessionBeanRemote {
50
51         /**
52          * Serial number
53          */
54         private static final long serialVersionUID = 542_145_350_001L;
55
56         /**
57          * Default constructor
58          */
59         public AddressbookUserSessionBean () {
60                 // Call super constructor
61                 super("jms/addressbook-queue-factory", "jms/addressbook-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 NPE 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 detachedUser) throws UserNotFoundException {
265                 // Trace message
266                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserData: detachedUser={1} - CALLED!", this.getClass().getSimpleName(), detachedUser)); //NOI18N
267
268                 // user should not be null
269                 if (null == detachedUser) {
270                         // Abort here
271                         throw new NullPointerException("detachedUser is null"); //NOI18N
272                 } else if (detachedUser.getUserId() == null) {
273                         // Throw NPE again
274                         throw new NullPointerException("detachedUser.userId is null"); //NOI18N
275                 } else if (detachedUser.getUserId() < 1) {
276                         // Not valid
277                         throw new IllegalArgumentException(MessageFormat.format("detachedUser.userId={0} is not valid.", detachedUser.getUserId())); //NOI18N
278                 } else if (detachedUser.getUserAccountStatus() == null) {
279                         // Throw NPE again
280                         throw new NullPointerException("detachedUser.userAccountStatus is null"); //NOI18N
281                 } else if (!this.ifUserExists(detachedUser)) {
282                         // User does not exist
283                         throw new UserNotFoundException(detachedUser.getUserId());
284                 }
285
286                 // Remove contact instance as this is not updated
287                 detachedUser.setUserContact(null);
288
289                 // Find the instance
290                 final User foundUser = this.getEntityManager().find(detachedUser.getClass(), detachedUser.getUserId());
291
292                 // Should be found!
293                 assert (foundUser instanceof User) : MessageFormat.format("User with id {0} not found, but should be.", detachedUser.getUserId()); //NOI18N
294
295                 // Copy all data
296                 UserUtils.copyUserData(detachedUser, foundUser);
297
298                 // Merge user
299                 final User managedUser = this.getEntityManager().merge(foundUser);
300
301                 // Should be found!
302                 assert (managedUser instanceof User) : MessageFormat.format("User with id {0} not merged, but should be.", managedUser.getUserId()); //NOI18N
303
304                 // Set as updated
305                 managedUser.setUserEntryUpdated(new Date());
306
307                 // Trace message
308                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserData: managedUser={1} - CALLED!", this.getClass().getSimpleName(), managedUser)); //NOI18N
309
310                 // Return updated instance
311                 return managedUser;
312         }
313
314         @Override
315         public PasswordHistory updateUserPassword (final User user, final String baseUrl) throws UserNotFoundException, UserStatusUnconfirmedException, UserStatusLockedException {
316                 // Trace message
317                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserPassword: user={1},baseUrl={2} - CALLED!", this.getClass().getSimpleName(), user, baseUrl)); //NOI18N
318
319                 // user should not be null
320                 if (null == user) {
321                         // Throw NPE
322                         throw new NullPointerException("user is null"); //NOI18N
323                 } else if (user.getUserId() == null) {
324                         // Throw NPE again
325                         throw new NullPointerException("user.userId is null"); //NOI18N
326                 } else if (user.getUserId() < 1) {
327                         // Not valid number
328                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid.", user.getUserId())); //NOI18N
329                 } else if (user.getUserName() == null) {
330                         // Throw NPE again
331                         throw new NullPointerException("user.userName is null"); //NOI18N
332                 } else if (user.getUserName().isEmpty()) {
333                         // Empty string
334                         throw new IllegalArgumentException("user.userName is empty"); //NOI18N
335                 } else if (user.getUserAccountStatus() == null) {
336                         // Throw NPE
337                         throw new NullPointerException("user.userAccountStatus is null"); //NOI18N
338                 } else if (user.getUserContact() == null) {
339                         // Throw it again
340                         throw new NullPointerException("user.userContact is null"); //NOI18N
341                 } else if (user.getUserContact().getContactId() == null) {
342                         // .. and again
343                         throw new NullPointerException("user.userContact.contactId is null"); //NOI18N
344                 } else if (user.getUserContact().getContactId() < 1) {
345                         // Invalid id
346                         throw new IllegalArgumentException(MessageFormat.format("user.userContact.contactId={0} is invalid", user.getUserContact().getContactId())); //NOI18N
347                 } else if (user.getUserContact().getContactPersonalTitle() == null) {
348                         // Throw NPE again
349                         throw new NullPointerException("user.userContact.contactPersonalTitle is null"); //NOI18N
350                 } else if (!this.ifUserExists(user)) {
351                         // User does not exist
352                         throw new EJBException(MessageFormat.format("User with id {0} does not exist.", user.getUserId())); //NOI18N
353                 } else if (null == baseUrl) {
354                         // Throw it again
355                         throw new NullPointerException("baseUrl is null"); //NOI18N
356                 } else if (baseUrl.isEmpty()) {
357                         // Invalid parameter
358                         throw new IllegalArgumentException("baseUrl is empty"); //NOI18N
359                 }
360
361                 // Call other method
362                 final User managedUser = this.updateUserData(user);
363
364                 // Update user account
365                 managedUser.setUserEntryUpdated(new Date());
366
367                 // Create history entry
368                 final PasswordHistory entry = new UserPasswordHistory(user.getUserEncryptedPassword(), managedUser);
369
370                 // Set created timestamp
371                 entry.setUserPasswordHistoryCreated(new Date());
372
373                 // Merge user to make sure it is not re-persisted
374                 final User mergedUser = this.getEntityManager().merge(managedUser);
375                 entry.setUserPasswordHistoryUser(mergedUser);
376
377                 // Persist it
378                 this.getEntityManager().persist(entry);
379
380                 // Send email to user
381                 this.sendEmail("User password change", "user_password_change", managedUser, baseUrl, null); //NOI18N
382
383                 // Trace message
384                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserPassword: entry.userPasswordHistoryId={1} - EXIT!", this.getClass().getSimpleName(), entry.getUserPasswordHistoryId())); //NOI18N
385
386                 // Return it
387                 return entry;
388         }
389
390         @Override
391         public User updateUserPersonalData (final User user) {
392                 // Trace message
393                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserPersonalData: user={1} - CALLED!", this.getClass().getSimpleName(), user)); //NOI18N
394
395                 // user should not be null
396                 if (null == user) {
397                         // Abort here
398                         throw new NullPointerException("user is null"); //NOI18N
399                 } else if (user.getUserId() == null) {
400                         // Throw NPE again
401                         throw new NullPointerException("user.userId is null"); //NOI18N
402                 } else if (user.getUserId() < 1) {
403                         // Not valid
404                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid.", user.getUserId())); //NOI18N
405                 } else if (user.getUserAccountStatus() == null) {
406                         // Throw NPE again
407                         throw new NullPointerException("user.userAccountStatus is null"); //NOI18N
408                 } else if (!this.ifUserExists(user)) {
409                         // User does not exist
410                         throw new EJBException(MessageFormat.format("User with id {0} does not exist.", user.getUserId())); //NOI18N
411                 }
412
413                 // Find the instance
414                 final User managedUser = this.getEntityManager().find(user.getClass(), user.getUserId());
415
416                 // Should be found!
417                 assert (managedUser instanceof User) : MessageFormat.format("User with id {0} not found, but should be.", user.getUserId()); //NOI18N
418
419                 // Copy all data
420                 UserUtils.copyUserData(user, managedUser);
421
422                 // Set as updated
423                 managedUser.setUserEntryUpdated(new Date());
424
425                 // Update user data
426                 final Contact managedContact = this.mergeContactData(managedUser.getUserContact());
427
428                 // Set it back in user
429                 managedUser.setUserContact(managedContact);
430
431                 // Should be found!
432                 assert (managedContact instanceof Contact) : MessageFormat.format("Contact with id {0} not merged, but should be.", managedUser.getUserContact().getContactId()); //NOI18N
433
434                 // Get mobile instance
435                 final DialableMobileNumber mobileNumber = managedContact.getContactMobileNumber();
436
437                 // Is there a  mobile instance set?
438                 if (mobileNumber instanceof DialableMobileNumber) {
439                         // Debug message
440                         this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: mobile.phoneId={0} is being updated ...", mobileNumber.getMobileId())); //NOI18N
441
442                         // Then find it, too
443                         final DialableMobileNumber foundMobile = this.getEntityManager().find(mobileNumber.getClass(), mobileNumber.getMobileId());
444
445                         // Should be there
446                         assert (foundMobile instanceof DialableMobileNumber) : MessageFormat.format("Mobile number with id {0} not found but should be.", foundMobile.getMobileId()); //NOI18N
447
448                         // Copy all
449                         MobileNumberUtils.copyMobileNumberData(managedUser.getUserContact().getContactMobileNumber(), foundMobile);
450
451                         // Then merge it, too
452                         final DialableMobileNumber managedMobile = this.getEntityManager().merge(foundMobile);
453
454                         // Should be there
455                         assert (managedMobile instanceof DialableMobileNumber) : MessageFormat.format("Mobile number with id {0} not found but should be.", managedMobile.getMobileId()); //NOI18N
456
457                         // Set it back
458                         managedContact.setContactMobileNumber(managedMobile);
459                 }
460
461                 // Get mobile instance
462                 final DialableFaxNumber faxNumber = managedContact.getContactFaxNumber();
463
464                 // Is there a  fax instance set?
465                 if (faxNumber instanceof DialableFaxNumber) {
466                         // Debug message
467                         this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: fax.phoneId={0} is being updated ...", faxNumber.getPhoneId())); //NOI18N
468
469                         // Then find it, too
470                         final DialableFaxNumber foundFax = this.getEntityManager().find(faxNumber.getClass(), faxNumber.getPhoneId());
471
472                         // Should be there
473                         assert (foundFax instanceof DialableFaxNumber) : MessageFormat.format("Fax number with id {0} not found but should be.", foundFax.getPhoneId()); //NOI18N
474
475                         // Copy all
476                         FaxNumberUtils.copyFaxNumberData(managedUser.getUserContact().getContactFaxNumber(), foundFax);
477
478                         // Then merge it, too
479                         final DialableFaxNumber managedFax = this.getEntityManager().merge(foundFax);
480
481                         // Should be there
482                         assert (managedFax instanceof DialableFaxNumber) : MessageFormat.format("Fax number with id {0} not found but should be.", managedFax.getPhoneId()); //NOI18N
483
484                         // Set it back
485                         managedContact.setContactFaxNumber(managedFax);
486                 }
487
488                 // Get mobile instance
489                 final DialableLandLineNumber landLineNumber = managedContact.getContactLandLineNumber();
490
491                 // Is there a  fax instance set?
492                 if (landLineNumber instanceof DialableLandLineNumber) {
493                         // Debug message
494                         this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: landLine.phoneId={0} is being updated ...", landLineNumber.getPhoneId())); //NOI18N
495
496                         // Then find it, too
497                         final DialableLandLineNumber foundLandLine = this.getEntityManager().find(landLineNumber.getClass(), landLineNumber.getPhoneId());
498
499                         // Should be there
500                         assert (foundLandLine instanceof DialableLandLineNumber) : MessageFormat.format("Land line number with id {0} not found but should be.", foundLandLine.getPhoneId()); //NOI18N
501
502                         // Copy all
503                         LandLineNumberUtils.copyLandLineNumberData(managedUser.getUserContact().getContactLandLineNumber(), foundLandLine);
504
505                         // Then merge it, too
506                         final DialableLandLineNumber managedLandLine = this.getEntityManager().merge(foundLandLine);
507
508                         // Should be there
509                         assert (managedLandLine instanceof DialableLandLineNumber) : MessageFormat.format("Land line number with id {0} not found but should be.", managedLandLine.getPhoneId()); //NOI18N
510
511                         // Set it back
512                         managedContact.setContactLandLineNumber(managedLandLine);
513                 }
514
515                 // Trace message
516                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateUserPersonalData: entry.managedUser={1} - EXIT!", this.getClass().getSimpleName(), managedUser)); //NOI18N
517
518                 // Return updated user instance
519                 return managedUser;
520         }
521
522 }