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