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