]> git.mxchange.org Git - pizzaservice-war.git/blob - src/java/org/mxchange/pizzaapplication/beans/user/PizzaUserWebSessionBean.java
Refactured a lot:
[pizzaservice-war.git] / src / java / org / mxchange / pizzaapplication / beans / user / PizzaUserWebSessionBean.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.pizzaapplication.beans.user;
18
19 import java.text.MessageFormat;
20 import java.util.Collections;
21 import java.util.Iterator;
22 import java.util.List;
23 import java.util.Objects;
24 import javax.annotation.PostConstruct;
25 import javax.enterprise.context.SessionScoped;
26 import javax.enterprise.event.Event;
27 import javax.enterprise.event.Observes;
28 import javax.enterprise.inject.Any;
29 import javax.faces.view.facelets.FaceletException;
30 import javax.inject.Inject;
31 import javax.inject.Named;
32 import javax.naming.Context;
33 import javax.naming.InitialContext;
34 import javax.naming.NamingException;
35 import org.mxchange.jcontacts.contact.Contact;
36 import org.mxchange.jcontacts.contact.ContactSessionBeanRemote;
37 import org.mxchange.jphone.phonenumbers.cellphone.DialableCellphoneNumber;
38 import org.mxchange.jphone.phonenumbers.fax.DialableFaxNumber;
39 import org.mxchange.jphone.phonenumbers.landline.DialableLandLineNumber;
40 import org.mxchange.jusercore.events.login.UserLoggedInEvent;
41 import org.mxchange.jusercore.events.registration.UserRegisteredEvent;
42 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
43 import org.mxchange.jusercore.events.user.update.UpdatedUserPersonalDataEvent;
44 import org.mxchange.jusercore.events.user.update.UserUpdatedPersonalDataEvent;
45 import org.mxchange.jusercore.exceptions.UserNotFoundException;
46 import org.mxchange.jusercore.exceptions.UserPasswordMismatchException;
47 import org.mxchange.jusercore.model.user.LoginUser;
48 import org.mxchange.jusercore.model.user.User;
49 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
50 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
51 import org.mxchange.pizzaapplication.beans.contact.PizzaContactWebSessionController;
52 import org.mxchange.pizzaapplication.beans.login.PizzaUserLoginWebSessionController;
53
54 /**
55  * A user bean (controller)
56  * <p>
57  * @author Roland Haeder<roland@mxchange.org>
58  */
59 @Named ("userController")
60 @SessionScoped
61 public class PizzaUserWebSessionBean implements PizzaUserWebSessionController {
62
63         /**
64          * Serial number
65          */
66         private static final long serialVersionUID = 542_145_347_916L;
67
68         /**
69          * Administrative user controller
70          */
71         @Inject
72         private PizzaAdminUserWebRequestController adminController;
73
74         /**
75          * Remote user bean
76          */
77         private final ContactSessionBeanRemote contactBean;
78
79         /**
80          * General contact controller
81          */
82         @Inject
83         private PizzaContactWebSessionController contactController;
84
85         /**
86          * Login bean (controller)
87          */
88         @Inject
89         private PizzaUserLoginWebSessionController loginController;
90
91         /**
92          * A list of all selectable contacts
93          */
94         private List<Contact> selectableContacts;
95
96         /**
97          * Event being fired when user updated personal data
98          */
99         @Inject
100         @Any
101         private Event<UpdatedUserPersonalDataEvent> updatedPersonalDataEvent;
102
103         /**
104          * Remote user bean
105          */
106         private final UserSessionBeanRemote userBean;
107
108         /**
109          * User id
110          */
111         private Long userId;
112
113         /**
114          * A list of all user profiles
115          */
116         private List<User> userList;
117
118         /**
119          * User name
120          */
121         private String userName;
122
123         /**
124          * User name list
125          */
126         private List<String> userNameList;
127
128         /**
129          * User password (unencrypted from web form)
130          */
131         private String userPassword;
132
133         /**
134          * User password repeated (unencrypted from web form)
135          */
136         private String userPasswordRepeat;
137
138         /**
139          * Whether the user wants a public profile
140          */
141         private ProfileMode userProfileMode;
142
143         /**
144          * A list of all public user profiles
145          */
146         private List<User> visibleUserList;
147
148         /**
149          * Default constructor
150          */
151         public PizzaUserWebSessionBean () {
152                 // Try it
153                 try {
154                         // Get initial context
155                         Context context = new InitialContext();
156
157                         // Try to lookup
158                         this.userBean = (UserSessionBeanRemote) context.lookup("java:global/PizzaService-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
159
160                         // Try to lookup
161                         this.contactBean = (ContactSessionBeanRemote) context.lookup("java:global/PizzaService-ejb/contact!org.mxchange.jcontacts.contact.ContactSessionBeanRemote"); //NOI18N
162                 } catch (final NamingException e) {
163                         // Throw again
164                         throw new FaceletException(e);
165                 }
166         }
167
168         @Override
169         public void afterRegistrationEvent (final @Observes UserRegisteredEvent event) {
170                 // Trace message
171                 System.out.println(MessageFormat.format("UserWebBean:afterRegistration: event={0} - CALLED!", event)); //NOI18N
172
173                 // event should not be null
174                 if (null == event) {
175                         // Throw NPE
176                         throw new NullPointerException("event is null"); //NOI18N
177                 } else if (event.getRegisteredUser() == null) {
178                         // Throw NPE again
179                         throw new NullPointerException("event.user is null"); //NOI18N
180                 } else if (event.getRegisteredUser().getUserId() == null) {
181                         // userId is null
182                         throw new NullPointerException("event.user.userId is null"); //NOI18N
183                 } else if (event.getRegisteredUser().getUserId() < 1) {
184                         // Not avalid id
185                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
186                 }
187
188                 // Get user instance
189                 User registeredUser = event.getRegisteredUser();
190
191                 // Debug message
192                 System.out.println(MessageFormat.format("UserWebBean:afterRegistration: registeredUser={0}", registeredUser)); //NOI18N
193
194                 // Copy all data from registered->user
195                 this.copyUser(registeredUser);
196
197                 // Add user name and email address
198                 this.addUserNameEmailAddress(registeredUser);
199
200                 // Clear all data
201                 this.clear();
202
203                 // Set user id again
204                 this.setUserId(registeredUser.getUserId());
205
206                 // Add user to local list
207                 this.userList.add(registeredUser);
208
209                 // Is the account public?
210                 if (Objects.equals(registeredUser.getUserProfileMode(), ProfileMode.PUBLIC)) {
211                         // Also add it to this list
212                         this.visibleUserList.add(registeredUser);
213                 }
214
215                 // Trace message
216                 System.out.println("UserWebBean:afterRegistration: EXIT!"); //NOI18N
217         }
218
219         @Override
220         public void afterAdminAddedUserEvent (@Observes final AdminAddedUserEvent event) {
221                 // Trace message
222                 System.out.println(MessageFormat.format("ContactWebBean:afterAdminAddedUserEvent: event={0} - CALLED!", event)); //NOI18N
223
224                 // The event must be valid
225                 if (null == event) {
226                         // Throw NPE
227                         throw new NullPointerException("event is null"); //NOI18N
228                 } else if (event.getAddedUser() == null) {
229                         // Throw NPE again
230                         throw new NullPointerException("event.addedUser is null"); //NOI18N
231                 } else if (event.getAddedUser().getUserId() == null) {
232                         // userId is null
233                         throw new NullPointerException("event.addedUser.userId is null"); //NOI18N
234                 } else if (event.getAddedUser().getUserId() < 1) {
235                         // Not avalid id
236                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getAddedUser(), event.getAddedUser().getUserId())); //NOI18N
237                 } else if (event.getAddedUser().getUserContact() == null) {
238                         // userId is null
239                         throw new NullPointerException("event.addedUser.userContact is null"); //NOI18N
240                 } else if (event.getAddedUser().getUserContact().getContactId() == null) {
241                         // userId is null
242                         throw new NullPointerException("event.addedUser.userContact.contactId is null"); //NOI18N
243                 } else if (event.getAddedUser().getUserContact().getContactId() < 1) {
244                         // userId is null
245                         throw new IllegalArgumentException(MessageFormat.format("event.addedUser.userContact.contactId={0} is not valid", event.getAddedUser().getUserContact().getContactId())); //NOI18N
246                 }
247
248                 // Remove this contact from selectable list
249                 assert(this.selectableContacts.remove(event.getAddedUser().getUserContact())) : "contact was not removed"; //NOI18N
250
251                 // Add user to local list
252                 this.userList.add(event.getAddedUser());
253         }
254
255         @Override
256         public void afterUserLogin (final @Observes UserLoggedInEvent event) {
257                 // Trace message
258                 System.out.println(MessageFormat.format("UserWebBean:afterUserLogin: event={0} - CALLED!", event)); //NOI18N
259
260                 // event should not be null
261                 if (null == event) {
262                         // Throw NPE
263                         throw new NullPointerException("event is null"); //NOI18N
264                 } else if (event.getLoggedInUser() == null) {
265                         // Throw NPE again
266                         throw new NullPointerException("event.user is null"); //NOI18N
267                 } else if (event.getLoggedInUser().getUserId() == null) {
268                         // userId is null
269                         throw new NullPointerException("event.user.userId is null"); //NOI18N
270                 } else if (event.getLoggedInUser().getUserId() < 1) {
271                         // Not avalid id
272                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getLoggedInUser(), event.getLoggedInUser().getUserId())); //NOI18N
273                 }
274
275                 // Re-initialize list
276                 this.visibleUserList = this.userBean.allMemberPublicVisibleUsers();
277
278                 // Copy all data to this bean
279                 this.copyUser(event.getLoggedInUser());
280
281                 // Trace message
282                 System.out.println(MessageFormat.format("UserWebBean:afterUserLogin: this.visibleUserList.size()={0} - EXIT!", this.visibleUserList.size())); //NOI18N
283         }
284
285         @Override
286         public List<User> allUsers () {
287                 // Return it
288                 return Collections.unmodifiableList(this.userList);
289         }
290
291         @Override
292         public List<User> allVisibleUsers () {
293                 // Return it
294                 return Collections.unmodifiableList(this.visibleUserList);
295         }
296
297         @Override
298         public User createUserInstance () {
299                 // User message
300                 //this.getLogger().logTrace("createUserInstance: CALLED!");
301
302                 // Required personal data must be set
303                 assert (this.isRequiredPersonalDataSet()) : "not all personal data is set"; //NOI18N
304
305                 // Create new user instance
306                 User localUser = new LoginUser();
307
308                 // Update all data ...
309                 localUser.setUserName(this.getUserName());
310                 localUser.setUserProfileMode(this.getUserProfileMode());
311
312                 // Create contact instance
313                 Contact contact = this.contactController.createContactInstance();
314
315                 // Set contact in user
316                 localUser.setUserContact(contact);
317
318                 // Trace message
319                 //this.getLogger().logTrace(MessageFormat.format("createUserInstance: user={0} - EXIT!", user));
320                 // Return it
321                 return localUser;
322         }
323
324         @Override
325         public String doChangePersonalData () {
326                 // This method shall only be called if the user is logged-in
327                 if (!this.loginController.isUserLoggedIn()) {
328                         // Not logged-in
329                         throw new IllegalStateException("User is not logged-in"); //NOI18N
330                 } else if (!this.isRequiredChangePersonalDataSet()) {
331                         // Not all required fields are set
332                         throw new FaceletException("Not all required fields are set."); //NOI18N
333                 } else if (!this.loginController.ifCurrentPasswordMatches()) {
334                         // Password not matching
335                         throw new FaceletException(new UserPasswordMismatchException(this.loginController.getLoggedInUser()));
336                 }
337
338                 // Get user instance
339                 User user = this.loginController.getLoggedInUser();
340
341                 // Copy contact data to contact instance
342                 this.contactController.updateContactDataFromController(user.getUserContact());
343
344                 // It should be there, so run some tests on it
345                 assert (user instanceof User) : "Instance loginController.loggedInUser is null"; //NOI18N
346                 assert (user.getUserId() instanceof Long) : "Instance loginController.loggedInUser.userId is null"; //NOI18N
347                 assert (user.getUserId() > 0) : MessageFormat.format("loginController.loggedInUser.userId={0} is invalid", user.getUserId()); //NOI18N
348                 assert (user.getUserContact() instanceof Contact) : "Instance loginController.loggedInUser.userContact is null"; //NOI18N
349                 assert (user.getUserContact().getContactId() instanceof Long) : "Instance loginController.userContact.contactId is null"; //NOI18N
350                 assert (user.getUserContact().getContactId() > 0) : MessageFormat.format("Instance loginController.userContact.contactId={0} is invalid", user.getUserContact().getContactId()); //NOI18N
351
352                 // Update all fields
353                 user.setUserProfileMode(this.getUserProfileMode());
354
355                 // Send it to the EJB
356                 User updatedUser = this.userBean.updateUserPersonalData(user);
357
358                 // Fire event
359                 this.updatedPersonalDataEvent.fire(new UserUpdatedPersonalDataEvent(updatedUser));
360
361                 // All fine
362                 return "user_data_saved"; //NOI18N
363         }
364
365         @Override
366         public Long getUserId () {
367                 return this.userId;
368         }
369
370         @Override
371         public void setUserId (final Long userId) {
372                 this.userId = userId;
373         }
374
375         @Override
376         public String getUserName () {
377                 return this.userName;
378         }
379
380         @Override
381         public void setUserName (final String userName) {
382                 this.userName = userName;
383         }
384
385         @Override
386         public String getUserPassword () {
387                 return this.userPassword;
388         }
389
390         @Override
391         public void setUserPassword (final String userPassword) {
392                 this.userPassword = userPassword;
393         }
394
395         @Override
396         public String getUserPasswordRepeat () {
397                 return this.userPasswordRepeat;
398         }
399
400         @Override
401         public void setUserPasswordRepeat (final String userPasswordRepeat) {
402                 this.userPasswordRepeat = userPasswordRepeat;
403         }
404
405         @Override
406         public ProfileMode getUserProfileMode () {
407                 return this.userProfileMode;
408         }
409
410         @Override
411         public void setUserProfileMode (final ProfileMode userProfileMode) {
412                 this.userProfileMode = userProfileMode;
413         }
414
415         @Override
416         public boolean hasUsers () {
417                 return (!this.allUsers().isEmpty());
418         }
419
420         /**
421          * Post-initialization of this class
422          */
423         @PostConstruct
424         public void init () {
425                 // Get full user name list for reducing EJB calls
426                 this.userNameList = this.userBean.getUserNameList();
427
428                 // Is the user logged-in?
429                 if (this.loginController.isUserLoggedIn()) {
430                         // Is logged-in, so load also users visible to memebers
431                         this.visibleUserList = this.userBean.allMemberPublicVisibleUsers();
432                 } else {
433                         // Initialize user list
434                         this.visibleUserList = this.userBean.allPublicUsers();
435                 }
436                 // Initialize user list
437                 this.userList = this.userBean.allUsers();
438
439                 // Get all contacts
440                 List<Contact> allContacts = this.contactBean.getAllContacts();
441
442                 // Get iterator
443                 Iterator<Contact> iterator = allContacts.iterator();
444
445                 // Loop through it
446                 while (iterator.hasNext()) {
447                         // Get next element
448                         Contact next = iterator.next();
449
450                         // Get iterator
451                         Iterator<User> userIterator = this.userList.iterator();
452
453                         // Loop through all users
454                         while (userIterator.hasNext()) {
455                                 // Get user instance
456                                 User nextUser = userIterator.next();
457
458                                 // Is contact same?
459                                 if (Objects.equals(next, nextUser.getUserContact())) {
460                                         // Found same
461                                         iterator.remove();
462                                         break;
463                                 }
464                         }
465                 }
466
467                 // Set contact list
468                 this.selectableContacts = allContacts;
469         }
470
471         @Override
472         public boolean isContactFound (final Contact contact) {
473                 // The contact must be valid
474                 if (null == contact) {
475                         // Throw NPE
476                         throw new NullPointerException("contact is null"); //NOI18N
477                 } else if (contact.getContactId() == null) {
478                         // Throw again ...
479                         throw new NullPointerException("contact.contactId is null"); //NOI18N
480                 } else if (contact.getContactId() < 1) {
481                         // Not valid
482                         throw new IllegalArgumentException(MessageFormat.format("contact.contactId={0} is not valid", contact.getContactId())); //NOI18N
483                 }
484
485                 // Default is not found
486                 boolean isFound = false;
487
488                 // Get iterator
489                 Iterator<User> iterator = this.allUsers().iterator();
490
491                 // Loop through all entries
492                 while (iterator.hasNext()) {
493                         // Get user
494                         User next = iterator.next();
495
496                         // Compare both objects
497                         if (Objects.equals(contact, next.getUserContact())) {
498                                 // Found it
499                                 isFound = true;
500                                 break;
501                         }
502                 }
503
504                 // Return status
505                 return isFound;
506         }
507
508         @Override
509         public void afterUserUpdatedPersonalData (@Observes final UpdatedUserPersonalDataEvent event) {
510                 // Check parameter
511                 if (null == event) {
512                         // Throw NPE
513                         throw new NullPointerException("event is null"); //NOI18N
514                 } else if (event.getUpdatedUser() == null) {
515                         // Throw NPE again
516                         throw new NullPointerException("event.updatedUser is null"); //NOI18N
517                 } else if (event.getUpdatedUser().getUserId() == null) {
518                         // ... and again
519                         throw new NullPointerException("event.updatedUser.userId is null"); //NOI18N
520                 } else if (event.getUpdatedUser().getUserId() < 1) {
521                         // Invalid value
522                         throw new IllegalArgumentException(MessageFormat.format("event.updatedUser.userId={0} is in valid", event.getUpdatedUser().getUserId())); //NOI18N
523                 }
524
525                 // All fine, so update list
526                 this.updateList(event.getUpdatedUser());
527         }
528
529         @Override
530         public boolean isRequiredChangePersonalDataSet () {
531                 return ((this.getUserProfileMode() != null) &&
532                                 (this.getUserName() != null) && (!this.getUserName().isEmpty()) &&
533                                 (this.contactController.isRequiredChangePersonalDataSet()));
534         }
535
536         @Override
537         public boolean isRequiredPersonalDataSet () {
538                 return ((this.getUserName() != null) &&
539                                 (this.getUserProfileMode() != null) &&
540                                 (this.contactController.isRequiredPersonalDataSet()) &&
541                                 (this.getUserPassword() != null) &&
542                                 (this.getUserPasswordRepeat() != null));
543         }
544
545         @Override
546         public boolean isSamePasswordEntered () {
547                 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
548         }
549
550         @Override
551         public boolean isUserIdEmpty () {
552                 return ((this.getUserId() == null) || (this.getUserId() == 0));
553         }
554
555         @Override
556         public boolean isUserNameRegistered (final User user) {
557                 return ((this.userNameList instanceof List) && (this.userNameList.contains(user.getUserName())));
558         }
559
560         @Override
561         public boolean isVisibleUserFound () {
562                 return ((this.visibleUserList instanceof List) && (this.visibleUserList.size() > 0));
563         }
564
565         @Override
566         public User lookupUserById (final Long userId) throws UserNotFoundException {
567                 // Init variable
568                 User localUser = null;
569
570                 // Clear this bean
571                 this.clear();
572
573                 // Try to lookup it in visible user list
574                 for (final Iterator<User> iterator = this.visibleUserList.iterator(); iterator.hasNext();) {
575                         // Get next user
576                         User next = iterator.next();
577
578                         // Is the user id found?
579                         if (Objects.equals(next.getUserId(), userId)) {
580                                 // Copy to other variable
581                                 localUser = next;
582                                 break;
583                         }
584                 }
585
586                 // Is it still null?
587                 if (null == localUser) {
588                         // Not visible for the current user
589                         throw new UserNotFoundException(userId);
590                 }
591
592                 // Copy all data to this bean
593                 this.copyUser(localUser);
594
595                 // Return it
596                 return localUser;
597         }
598
599         @Override
600         public List<Contact> selectableContacts () {
601                 return Collections.unmodifiableList(this.selectableContacts);
602         }
603
604         /**
605          * Adds user's name and email address to bean's internal list. It also
606          * updates the public user list if the user has decided to ha   }
607          * <p>
608          * @param user User instance
609          */
610         private void addUserNameEmailAddress (final User user) {
611                 // Make sure the entry is not added yet
612                 if (this.userNameList.contains(user.getUserName())) {
613                         // Abort here
614                         throw new IllegalArgumentException(MessageFormat.format("User name {0} already added.", user.getUserName())); //NOI18N
615                 } else if (this.contactController.isEmailAddressRegistered(user.getUserContact())) {
616                         // Already added
617                         throw new IllegalArgumentException(MessageFormat.format("Email address {0} already added.", user.getUserContact().getContactEmailAddress())); //NOI18N
618                 }
619
620                 // Add user name
621                 this.userNameList.add(user.getUserName());
622
623                 // Add email addres
624                 this.contactController.addEmailAddress(user.getUserContact().getContactEmailAddress());
625         }
626
627         /**
628          * Updates list with given user instance
629          * <p>
630          * @param user User instance
631          */
632         @Override
633         public void updateList (final User user) {
634                 // The user should be valid
635                 if (null == user) {
636                         // Throw NPE
637                         throw new NullPointerException("user is null"); //NOI18N
638                 } else if (user.getUserId() == null) {
639                         // ... again NPE
640                         throw new NullPointerException("user.userId is null"); //NOI18N
641                 } else if (user.getUserId() < 1) {
642                         // Invalid id
643                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is invalid", user.getUserId())); //NOI18N
644                 }
645
646                 // Get iterator
647                 Iterator<User> iterator = this.userList.iterator();
648
649                 // Look whole list
650                 while (iterator.hasNext()) {
651                         // Get next element
652                         User next = iterator.next();
653
654                         // Is the same user id?
655                         if (Objects.equals(user.getUserId(), next.getUserId())) {
656                                 // Found it, so remove it
657                                 this.userList.remove(next);
658                                 break;
659                         }
660                 }
661
662                 // Re-add item
663                 this.userList.add(user);
664         }
665
666         /**
667          * Clears this bean
668          */
669         private void clear () {
670                 // Clear all data
671                 // - personal data
672                 this.setUserId(null);
673                 this.setUserProfileMode(null);
674
675                 // - other data
676                 this.setUserName(null);
677                 this.setUserPassword(null);
678                 this.setUserPasswordRepeat(null);
679         }
680
681         /**
682          * Copies given user into the controller
683          * <p>
684          * @param user User instance
685          */
686         private void copyUser (final User user) {
687                 // Copy all fields:
688                 // - base data
689                 this.setUserId(user.getUserId());
690                 this.setUserProfileMode(user.getUserProfileMode());
691
692                 // Get cellphone, phone and fax instance
693                 DialableCellphoneNumber cellphone = user.getUserContact().getContactCellphoneNumber();
694                 DialableFaxNumber fax = user.getUserContact().getContactFaxNumber();
695                 DialableLandLineNumber phone = user.getUserContact().getContactLandLineNumber();
696         }
697
698 }