]> git.mxchange.org Git - jjobs-ejb.git/blob - src/java/org/mxchange/jusercore/model/user/JobsUserSessionBean.java
Implemented new business method findUserById() + ignored strings for i18n
[jjobs-ejb.git] / src / java / org / mxchange / jusercore / model / user / JobsUserSessionBean.java
1 /*
2  * Copyright (C) 2016 Roland Haeder
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.GregorianCalendar;
21 import java.util.List;
22 import javax.ejb.EJB;
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.contact.Contact;
29 import org.mxchange.jcoreee.database.BaseDatabaseBean;
30 import org.mxchange.jphone.phonenumbers.cellphone.DialableCellphoneNumber;
31 import org.mxchange.jphone.phonenumbers.fax.DialableFaxNumber;
32 import org.mxchange.jphone.phonenumbers.landline.DialableLandLineNumber;
33 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
34 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
35 import org.mxchange.jusercore.exceptions.UserNotFoundException;
36 import org.mxchange.jusercore.model.register.UserRegistrationSessionBeanRemote;
37 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
38 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
39
40 /**
41  * A user EJB
42  * <p>
43  * @author Roland Haeder<roland@mxchange.org>
44  */
45 @Stateless (name = "user", mappedName = "ejb/stateless-jjobs-user", description = "A bean handling the user data")
46 public class JobsUserSessionBean extends BaseDatabaseBean implements UserSessionBeanRemote {
47
48         /**
49          * Serial number
50          */
51         private static final long serialVersionUID = 542_145_347_916L;
52
53         /**
54          * Registration EJB
55          */
56         @EJB
57         private UserRegistrationSessionBeanRemote registerBean;
58
59         /**
60          * Default constructor
61          */
62         public JobsUserSessionBean () {
63         }
64
65         @Override
66         public User addUser (final User user) throws UserNameAlreadyRegisteredException, EmailAddressAlreadyRegisteredException {
67                 // Trace message
68                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("addUser: user={0} - CALLED!", user)); //NOI18N
69
70                 // user should not be null
71                 if (null == user) {
72                         // Abort here
73                         throw new NullPointerException("user is null"); //NOI18N
74                 }
75
76                 // Check if user is registered
77                 if (this.registerBean.isUserNameRegistered(user)) {
78                         // Abort here
79                         throw new UserNameAlreadyRegisteredException(user);
80                 } else if (this.registerBean.isEmailAddressRegistered(user)) {
81                         // Abort here
82                         throw new EmailAddressAlreadyRegisteredException(user);
83                 }
84
85                 // Set created timestamp
86                 user.setUserCreated(new GregorianCalendar());
87                 user.getUserContact().setContactCreated(new GregorianCalendar());
88
89                 // Get all phone instances
90                 DialableLandLineNumber landLineNumber = user.getUserContact().getContactLandLineNumber();
91                 DialableFaxNumber faxNumber = user.getUserContact().getContactFaxNumber();
92                 DialableCellphoneNumber cellphoneNumber = user.getUserContact().getContactCellphoneNumber();
93
94                 // Is a phone number instance set?
95                 if (landLineNumber instanceof DialableLandLineNumber) {
96                         // Set created timestamp
97                         landLineNumber.setPhoneEntryCreated(new GregorianCalendar());
98                 }
99
100                 // Is a fax number instance set?
101                 if (faxNumber instanceof DialableFaxNumber) {
102                         // Set created timestamp
103                         faxNumber.setPhoneEntryCreated(new GregorianCalendar());
104                 }
105
106                 // Is a mobile number instance set?
107                 if (cellphoneNumber instanceof DialableCellphoneNumber) {
108                         // Set created timestamp
109                         cellphoneNumber.setPhoneEntryCreated(new GregorianCalendar());
110                 }
111
112                         // Persist it
113                 this.getEntityManager().persist(user);
114
115                 // Flush to get id back
116                 this.getEntityManager().flush();
117
118                 // Trace message
119                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("addUser: user={0},user.id={1} - EXIT!", user, user.getUserId())); //NOI18N
120
121                 // Return it
122                 return user;
123         }
124
125         @Override
126         @SuppressWarnings ("unchecked")
127         public List<User> allMemberPublicVisibleUsers () {
128                 // Trace message
129                 this.getLoggerBeanLocal().logTrace("allMemberPublicVisibleUsers: CALLED!"); //NOI18N
130
131                 // Get named query
132                 Query query = this.getEntityManager().createNamedQuery("AllMemberPublicUsers", List.class); //NOI18N
133
134                 // Set parameters
135                 query.setParameter("status", UserAccountStatus.CONFIRMED); //NOI18N
136                 query.setParameter("members", ProfileMode.MEMBERS); //NOI18N
137                 query.setParameter("public", ProfileMode.PUBLIC); //NOI18N
138
139                 // Get result
140                 List<User> users = query.getResultList();
141
142                 // Trace message
143                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("allMemberPublicVisibleUsers: users.size()={0} - EXIT!", users.size())); //NOI18N
144
145                 // Return full list
146                 return users;
147         }
148
149         @Override
150         @SuppressWarnings ("unchecked")
151         public List<User> allPublicUsers () {
152                 // Trace message
153                 this.getLoggerBeanLocal().logTrace("allPublicUsers: CALLED!"); //NOI18N
154
155                 // Get named query
156                 Query query = this.getEntityManager().createNamedQuery("AllPublicUsers", List.class); //NOI18N
157
158                 // Set parameters
159                 query.setParameter("status", UserAccountStatus.CONFIRMED); //NOI18N
160                 query.setParameter("mode", ProfileMode.PUBLIC); //NOI18N
161
162                 // Get result
163                 List<User> users = query.getResultList();
164
165                 // Trace message
166                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("allPublicUsers: users.size()={0} - EXIT!", users.size())); //NOI18N
167
168                 // Return full list
169                 return users;
170         }
171
172         @Override
173         @SuppressWarnings ("unchecked")
174         public List<User> allUsers () {
175                 // Trace message
176                 this.getLoggerBeanLocal().logTrace("allUsers: CALLED!"); //NOI18N
177
178                 // Get named query
179                 Query query = this.getEntityManager().createNamedQuery("AllUsers", List.class); //NOI18N
180
181                 // Get result
182                 List<User> users = query.getResultList();
183
184                 // Trace message
185                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("allUsers: users.size()={0} - EXIT!", users.size())); //NOI18N
186
187                 // Return full list
188                 return users;
189         }
190
191         @Override
192         public User fillUserData (final User user) {
193                 // Trace message
194                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("fillUserData: user={0} - CALLED!", user)); //NOI18N
195
196                 // user should not be null
197                 if (null == user) {
198                         // Abort here
199                         throw new NullPointerException("user is null"); //NOI18N
200                 }
201
202                 // Try to locate it
203                 Query query = this.getEntityManager().createNamedQuery("SearchUserName", LoginUser.class); //NOI18N
204
205                 // Set parameter
206                 query.setParameter("param", user.getUserName()); //NOI18N
207
208                 // Initialize variable
209                 User foundUser = null;
210
211                 // Try it
212                 try {
213                         // Try to get single result
214                         foundUser = (User) query.getSingleResult();
215                 } catch (final NoResultException ex) {
216                         // Log it
217                         this.getLoggerBeanLocal().logException(ex);
218                 }
219
220                 // Trace message
221                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("fillUserData: foundUser={0} - EXIT!", foundUser)); //NOI18N
222
223                 // Return prepared instance
224                 return foundUser;
225         }
226
227         @Override
228         public User findUserById (final Long userId) throws UserNotFoundException {
229                 // Is the parameter valid?
230                 if (null == userId) {
231                         // Throw NPE
232                         throw new NullPointerException("userId is null"); //NOI18N
233                 } else if (userId < 1) {
234                         // Not valid
235                         throw new IllegalArgumentException(MessageFormat.format("userId={0} is not valid.", userId)); //NOI18N
236                 } else if (!this.ifUserIdExists(userId)) {
237                         // Does not exist
238                         throw new UserNotFoundException(userId);
239                 }
240
241                 // Create query instance
242                 Query query = this.getEntityManager().createNamedQuery("SearchUserId", LoginUser.class); //NOI18N
243
244                 // Set user id
245                 query.setParameter("id", userId); //NOI18N
246
247                 // Fetch the result, it should be there by now
248                 User user = (User) query.getSingleResult();
249
250                 // Should be there
251                 assert(user instanceof User) : "user is null"; //NOI18N
252
253                 // Return found user
254                 return user;
255         }
256
257         @Override
258         @SuppressWarnings ("unchecked")
259         public List<String> getEmailAddressList () {
260                 // Get query
261                 Query query = this.getEntityManager().createNamedQuery("AllEmailAddresses", String.class); //NOI18N
262
263                 // Get result list
264                 List<String> emailAddressList = query.getResultList();
265
266                 // Return it
267                 return emailAddressList;
268         }
269
270         @Override
271         @SuppressWarnings ("unchecked")
272         public List<String> getUserNameList () {
273                 // Get query
274                 Query query = this.getEntityManager().createNamedQuery("AllUserNames", String.class); //NOI18N
275
276                 // Get result list
277                 List<String> userNameList = query.getResultList();
278
279                 // Return it
280                 return userNameList;
281         }
282
283         @Override
284         public boolean ifUserExists (final User user) {
285                 // Trace message
286                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("ifUserExists: user={0} - CALLED!", user)); //NOI18N
287
288                 // userId should not be null
289                 if (null == user) {
290                         // Abort here
291                         throw new NullPointerException("user is null"); //NOI18N
292                 } else if (user.getUserId() == null) {
293                         // Abort here
294                         throw new NullPointerException("user.userId is null"); //NOI18N
295                 } else if (user.getUserId() < 1) {
296                         // Invalid number
297                         throw new IllegalArgumentException(MessageFormat.format("userId is not valid: {0}", user.getUserId())); //NOI18N
298                 }
299
300                 // Generate query
301                 Query query = this.getEntityManager().createNamedQuery("SearchUserId", LoginUser.class); //NOI18N
302
303                 // Set parameter
304                 query.setParameter("id", user.getUserId()); //NOI18N
305
306                 // Try this
307                 try {
308                         User dummy = (User) query.getSingleResult();
309
310                         // Debug message
311                         this.getLoggerBeanLocal().logDebug(MessageFormat.format("ifUserExists: dummy.id={0} found.", dummy.getUserId())); //NOI18N
312                 } catch (final NoResultException ex) {
313                         // Log it
314                         this.getLoggerBeanLocal().logDebug(MessageFormat.format("ifUserExists: getSingleResult() returned no result: {0}", ex)); //NOI18N
315
316                         // User name does not exist
317                         return false;
318                 } catch (final PersistenceException ex) {
319                         // Something bad happened
320                         this.getLoggerBeanLocal().logWarning(MessageFormat.format("More than one user {0} found.", user, ex)); //NOI18N
321
322                         // Throw again
323                         throw ex;
324                 }
325
326                 // Trace message
327                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("ifUserExists: Found user {0} - EXIT!", user)); //NOI18N
328
329                 // Found it
330                 return true;
331         }
332
333         @Override
334         public boolean ifUserIdExists (final Long userId) {
335                 // Trace message
336                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("ifUserIdExists: userId={0} - CALLED!", userId)); //NOI18N
337
338                 // userId should not be null
339                 if (null == userId) {
340                         // Abort here
341                         throw new NullPointerException("userId is null"); //NOI18N
342                 } else if (userId < 1) {
343                         // Invalid number
344                         throw new IllegalArgumentException(MessageFormat.format("userId is not valid: {0}", userId)); //NOI18N
345                 }
346
347                 // Generate query
348                 Query query = this.getEntityManager().createNamedQuery("SearchUserId", LoginUser.class); //NOI18N
349
350                 // Set parameter
351                 query.setParameter("id", userId); //NOI18N
352
353                 // Try this
354                 try {
355                         User dummy = (User) query.getSingleResult();
356
357                         // Debug message
358                         this.getLoggerBeanLocal().logDebug(MessageFormat.format("ifUserIdExists: dummy.id={0} found.", dummy.getUserId())); //NOI18N
359                 } catch (final NoResultException ex) {
360                         // Log it
361                         this.getLoggerBeanLocal().logDebug(MessageFormat.format("ifUserIdExists: getSingleResult() returned no result: {0}", ex)); //NOI18N
362
363                         // User name does not exist
364                         return false;
365                 } catch (final PersistenceException ex) {
366                         // Something bad happened
367                         this.getLoggerBeanLocal().logWarning(MessageFormat.format("More than one user id {0} found.", userId, ex)); //NOI18N
368
369                         // Throw again
370                         throw ex;
371                 }
372
373                 // Trace message
374                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("ifUserIdExists: Found user id {0} - EXIT!", userId)); //NOI18N
375
376                 // Found it
377                 return true;
378         }
379
380         @Override
381         public boolean isEmailAddressReqistered (final User user) {
382                 // Trace message
383                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("isEmailAddressReqistered: user={0} - CALLED!", user)); //NOI18N
384
385                 // user should not be null
386                 if (null == user) {
387                         // Abort here
388                         throw new NullPointerException("user is null"); //NOI18N
389                 }
390
391                 // Generate query
392                 Query query = this.getEntityManager().createNamedQuery("SearchEmailAddress", LoginUser.class); //NOI18N
393
394                 // Set parameter
395                 query.setParameter("param", user.getUserContact().getContactEmailAddress()); //NOI18N
396
397                 // Search for it
398                 try {
399                         User dummy = (User) query.getSingleResult();
400
401                         // Debug message
402                         this.getLoggerBeanLocal().logDebug(MessageFormat.format("isEmailAddressReqistered: dummy.id={0} found.", dummy.getUserId())); //NOI18N
403                 } catch (final NoResultException ex) {
404                         // Log it
405                         this.getLoggerBeanLocal().logDebug(MessageFormat.format("isEmailAddressReqistered: getSingleResult() returned no result: {0}", ex)); //NOI18N
406
407                         // Email address does not exist
408                         return false;
409                 } catch (final PersistenceException ex) {
410                         // Something bad happened
411                         this.getLoggerBeanLocal().logWarning(MessageFormat.format("More than one email address {0} found.", user.getUserContact().getContactEmailAddress()), ex); //NOI18N
412
413                         // Throw again
414                         throw ex;
415                 }
416
417                 // Found it
418                 return true;
419         }
420
421         @Override
422         public boolean isUserNameReqistered (final User user) {
423                 // Trace message
424                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("isUserNameReqistered: user={0} - CALLED!", user)); //NOI18N
425
426                 // user should not be null
427                 if (null == user) {
428                         // Abort here
429                         throw new NullPointerException("user is null"); //NOI18N
430                 }
431
432                 // Generate query
433                 Query query = this.getEntityManager().createNamedQuery("SearchUserName", LoginUser.class); //NOI18N
434
435                 // Set parameter
436                 query.setParameter("param", user.getUserName()); //NOI18N
437
438                 // Try this
439                 try {
440                         User dummy = (User) query.getSingleResult();
441
442                         // Debug message
443                         this.getLoggerBeanLocal().logDebug(MessageFormat.format("isUserNameReqistered: dummy.id={0} found.", dummy.getUserId())); //NOI18N
444                 } catch (final NoResultException ex) {
445                         // Log it
446                         this.getLoggerBeanLocal().logDebug(MessageFormat.format("isUserNameReqistered: getSingleResult() returned no result: {0}", ex)); //NOI18N
447
448                         // User name does not exist
449                         return false;
450                 } catch (final PersistenceException ex) {
451                         // Something bad happened
452                         this.getLoggerBeanLocal().logWarning(MessageFormat.format("More than one email address {0} found.", user.getUserContact().getContactEmailAddress()), ex); //NOI18N
453
454                         // Throw again
455                         throw ex;
456                 }
457
458                 // Found it
459                 return true;
460         }
461
462         @Override
463         public void updateUserPersonalData (final User user) {
464                 // Trace message
465                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("updateUserPersonalData: user={0} - CALLED!", user)); //NOI18N
466
467                 // user should not be null
468                 if (null == user) {
469                         // Abort here
470                         throw new NullPointerException("user is null"); //NOI18N
471                 } else if (user.getUserId() == null) {
472                         // Throw NPE again
473                         throw new NullPointerException("user.userId is null"); //NOI18N
474                 } else if (user.getUserId() < 1) {
475                         // Not valid
476                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is not valid.", user.getUserId())); //NOI18N
477                 } else if (user.getUserAccountStatus() == null) {
478                         // Throw NPE again
479                         throw new NullPointerException("user.userAccountStatus is null"); //NOI18N
480                 } else if (!this.ifUserExists(user)) {
481                         // User does not exist
482                         throw new EJBException(MessageFormat.format("User with id {0} does not exist.", user.getUserId())); //NOI18N
483                 }
484
485                 // Find the instance
486                 User foundUser = this.getEntityManager().find(user.getClass(), user.getUserId());
487
488                 // Should be found!
489                 assert (foundUser instanceof User) : MessageFormat.format("User with id {0} not found, but should be.", user.getUserId()); //NOI18N
490
491                 // Merge user
492                 User detachedUser = this.getEntityManager().merge(foundUser);
493
494                 // Should be found!
495                 assert (detachedUser instanceof User) : MessageFormat.format("User with id {0} not merged, but should be.", user.getUserId()); //NOI18N
496
497                 // Copy all data
498                 detachedUser.copyAll(user);
499
500                 // Set as updated
501                 detachedUser.setUserUpdated(new GregorianCalendar());
502                 detachedUser.getUserContact().setContactUpdated(new GregorianCalendar());
503
504                 // Get contact from it and find it
505                 Contact foundContact = this.getEntityManager().find(user.getUserContact().getClass(), user.getUserContact().getContactId());
506
507                 // Should be found
508                 assert (foundContact instanceof Contact) : MessageFormat.format("Contact with id {0} not found, but should be.", user.getUserContact().getContactId()); //NOI18N
509
510                 // Debug message
511                 this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: contact.contactId={0}", foundContact.getContactId())); //NOI18N
512
513                 // Merge contact instance
514                 Contact detachedContact = this.getEntityManager().merge(foundContact);
515
516                 // Copy all
517                 detachedContact.copyAll(user.getUserContact());
518
519                 // Set it back in user
520                 user.setUserContact(detachedContact);
521
522                 // Should be found!
523                 assert (detachedContact instanceof Contact) : MessageFormat.format("Contact with id {0} not merged, but should be.", user.getUserContact().getContactId()); //NOI18N
524
525                 // Get cellphone instance
526                 DialableCellphoneNumber cellphone = detachedContact.getContactCellphoneNumber();
527
528                 // Is there a  cellphone instance set?
529                 if (cellphone instanceof DialableCellphoneNumber) {
530                         // Debug message
531                         this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: cellphone.phoneId={0} is being updated ...", cellphone.getPhoneId())); //NOI18N
532
533                         // Then find it, too
534                         DialableCellphoneNumber foundCellphone = this.getEntityManager().find(cellphone.getClass(), cellphone.getPhoneId());
535
536                         // Should be there
537                         assert (foundCellphone instanceof DialableCellphoneNumber) : MessageFormat.format("Cellphone number with id {0} not found but should be.", foundCellphone.getPhoneId()); //NOI18N
538
539                         // Then merge it, too
540                         DialableCellphoneNumber detachedCellphone = this.getEntityManager().merge(foundCellphone);
541
542                         // Should be there
543                         assert (detachedCellphone instanceof DialableCellphoneNumber) : MessageFormat.format("Cellphone number with id {0} not found but should be.", detachedCellphone.getPhoneId()); //NOI18N
544
545                         // Copy all
546                         detachedCellphone.copyAll(user.getUserContact().getContactCellphoneNumber());
547
548                         // Set it back
549                         detachedContact.setContactCellphoneNumber(detachedCellphone);
550                 }
551
552                 // Get cellphone instance
553                 DialableFaxNumber fax = detachedContact.getContactFaxNumber();
554
555                 // Is there a  fax instance set?
556                 if (fax instanceof DialableFaxNumber) {
557                         // Debug message
558                         this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: fax.phoneId={0} is being updated ...", fax.getPhoneId())); //NOI18N
559
560                         // Then find it, too
561                         DialableFaxNumber foundFax = this.getEntityManager().find(fax.getClass(), fax.getPhoneId());
562
563                         // Should be there
564                         assert (foundFax instanceof DialableFaxNumber) : MessageFormat.format("Fax number with id {0} not found but should be.", foundFax.getPhoneId()); //NOI18N
565
566                         // Then merge it, too
567                         DialableFaxNumber detachedFax = this.getEntityManager().merge(foundFax);
568
569                         // Should be there
570                         assert (detachedFax instanceof DialableFaxNumber) : MessageFormat.format("Fax number with id {0} not found but should be.", detachedFax.getPhoneId()); //NOI18N
571
572                         // Copy all
573                         detachedFax.copyAll(user.getUserContact().getContactFaxNumber());
574
575                         // Set it back
576                         detachedContact.setContactFaxNumber(detachedFax);
577                 }
578
579                 // Get cellphone instance
580                 DialableLandLineNumber landLine = detachedContact.getContactLandLineNumber();
581
582                 // Is there a  fax instance set?
583                 if (landLine instanceof DialableLandLineNumber) {
584                         // Debug message
585                         this.getLoggerBeanLocal().logDebug(MessageFormat.format("updateUserPersonalData: landLine.phoneId={0} is being updated ...", landLine.getPhoneId())); //NOI18N
586
587                         // Then find it, too
588                         DialableLandLineNumber foundLandLine = this.getEntityManager().find(landLine.getClass(), landLine.getPhoneId());
589
590                         // Should be there
591                         assert (foundLandLine instanceof DialableLandLineNumber) : MessageFormat.format("Land line number with id {0} not found but should be.", foundLandLine.getPhoneId()); //NOI18N
592
593                         // Then merge it, too
594                         DialableLandLineNumber detachedLandLine = this.getEntityManager().merge(foundLandLine);
595
596                         // Should be there
597                         assert (detachedLandLine instanceof DialableLandLineNumber) : MessageFormat.format("Land line number with id {0} not found but should be.", detachedLandLine.getPhoneId()); //NOI18N
598
599                         // Copy all
600                         detachedLandLine.copyAll(user.getUserContact().getContactLandLineNumber());
601
602                         // Set it back
603                         detachedContact.setContactLandLineNumber(detachedLandLine);
604                 }
605         }
606
607 }