2 * Copyright (C) 2016 Roland Haeder
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.
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.
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/>.
17 package org.mxchange.pizzaapplication.beans.user;
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;
55 * A user bean (controller)
57 * @author Roland Haeder<roland@mxchange.org>
59 @Named ("userController")
61 public class PizzaUserWebSessionBean implements PizzaUserWebSessionController {
66 private static final long serialVersionUID = 542_145_347_916L;
69 * Administrative user controller
72 private PizzaAdminUserWebRequestController adminController;
77 private final ContactSessionBeanRemote contactBean;
80 * General contact controller
83 private PizzaContactWebSessionController contactController;
86 * Login bean (controller)
89 private PizzaUserLoginWebSessionController loginController;
92 * A list of all selectable contacts
94 private List<Contact> selectableContacts;
97 * Event being fired when user updated personal data
101 private Event<UpdatedUserPersonalDataEvent> updatedPersonalDataEvent;
106 private final UserSessionBeanRemote userBean;
114 * A list of all user profiles
116 private List<User> userList;
121 private String userName;
126 private List<String> userNameList;
129 * User password (unencrypted from web form)
131 private String userPassword;
134 * User password repeated (unencrypted from web form)
136 private String userPasswordRepeat;
139 * Whether the user wants a public profile
141 private ProfileMode userProfileMode;
144 * A list of all public user profiles
146 private List<User> visibleUserList;
149 * Default constructor
151 public PizzaUserWebSessionBean () {
154 // Get initial context
155 Context context = new InitialContext();
158 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/PizzaService-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
161 this.contactBean = (ContactSessionBeanRemote) context.lookup("java:global/PizzaService-ejb/contact!org.mxchange.jcontacts.contact.ContactSessionBeanRemote"); //NOI18N
162 } catch (final NamingException e) {
164 throw new FaceletException(e);
169 public void afterRegistrationEvent (final @Observes UserRegisteredEvent event) {
171 System.out.println(MessageFormat.format("UserWebBean:afterRegistration: event={0} - CALLED!", event)); //NOI18N
173 // event should not be null
176 throw new NullPointerException("event is null"); //NOI18N
177 } else if (event.getRegisteredUser() == null) {
179 throw new NullPointerException("event.user is null"); //NOI18N
180 } else if (event.getRegisteredUser().getUserId() == null) {
182 throw new NullPointerException("event.user.userId is null"); //NOI18N
183 } else if (event.getRegisteredUser().getUserId() < 1) {
185 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
189 User registeredUser = event.getRegisteredUser();
192 System.out.println(MessageFormat.format("UserWebBean:afterRegistration: registeredUser={0}", registeredUser)); //NOI18N
194 // Copy all data from registered->user
195 this.copyUser(registeredUser);
197 // Add user name and email address
198 this.addUserNameEmailAddress(registeredUser);
204 this.setUserId(registeredUser.getUserId());
206 // Add user to local list
207 this.userList.add(registeredUser);
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);
216 System.out.println("UserWebBean:afterRegistration: EXIT!"); //NOI18N
220 public void afterAdminAddedUserEvent (@Observes final AdminAddedUserEvent event) {
222 System.out.println(MessageFormat.format("ContactWebBean:afterAdminAddedUserEvent: event={0} - CALLED!", event)); //NOI18N
224 // The event must be valid
227 throw new NullPointerException("event is null"); //NOI18N
228 } else if (event.getAddedUser() == null) {
230 throw new NullPointerException("event.addedUser is null"); //NOI18N
231 } else if (event.getAddedUser().getUserId() == null) {
233 throw new NullPointerException("event.addedUser.userId is null"); //NOI18N
234 } else if (event.getAddedUser().getUserId() < 1) {
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) {
239 throw new NullPointerException("event.addedUser.userContact is null"); //NOI18N
240 } else if (event.getAddedUser().getUserContact().getContactId() == null) {
242 throw new NullPointerException("event.addedUser.userContact.contactId is null"); //NOI18N
243 } else if (event.getAddedUser().getUserContact().getContactId() < 1) {
245 throw new IllegalArgumentException(MessageFormat.format("event.addedUser.userContact.contactId={0} is not valid", event.getAddedUser().getUserContact().getContactId())); //NOI18N
248 // Remove this contact from selectable list
249 assert(this.selectableContacts.remove(event.getAddedUser().getUserContact())) : "contact was not removed"; //NOI18N
251 // Add user to local list
252 this.userList.add(event.getAddedUser());
256 public void afterUserLogin (final @Observes UserLoggedInEvent event) {
258 System.out.println(MessageFormat.format("UserWebBean:afterUserLogin: event={0} - CALLED!", event)); //NOI18N
260 // event should not be null
263 throw new NullPointerException("event is null"); //NOI18N
264 } else if (event.getLoggedInUser() == null) {
266 throw new NullPointerException("event.user is null"); //NOI18N
267 } else if (event.getLoggedInUser().getUserId() == null) {
269 throw new NullPointerException("event.user.userId is null"); //NOI18N
270 } else if (event.getLoggedInUser().getUserId() < 1) {
272 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getLoggedInUser(), event.getLoggedInUser().getUserId())); //NOI18N
275 // Re-initialize list
276 this.visibleUserList = this.userBean.allMemberPublicVisibleUsers();
278 // Copy all data to this bean
279 this.copyUser(event.getLoggedInUser());
282 System.out.println(MessageFormat.format("UserWebBean:afterUserLogin: this.visibleUserList.size()={0} - EXIT!", this.visibleUserList.size())); //NOI18N
286 public List<User> allUsers () {
288 return Collections.unmodifiableList(this.userList);
292 public List<User> allVisibleUsers () {
294 return Collections.unmodifiableList(this.visibleUserList);
298 public User createUserInstance () {
300 //this.getLogger().logTrace("createUserInstance: CALLED!");
302 // Required personal data must be set
303 assert (this.isRequiredPersonalDataSet()) : "not all personal data is set"; //NOI18N
305 // Create new user instance
306 User localUser = new LoginUser();
308 // Update all data ...
309 localUser.setUserName(this.getUserName());
310 localUser.setUserProfileMode(this.getUserProfileMode());
312 // Create contact instance
313 Contact contact = this.contactController.createContactInstance();
315 // Set contact in user
316 localUser.setUserContact(contact);
319 //this.getLogger().logTrace(MessageFormat.format("createUserInstance: user={0} - EXIT!", user));
325 public String doChangePersonalData () {
326 // This method shall only be called if the user is logged-in
327 if (!this.loginController.isUserLoggedIn()) {
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()));
339 User user = this.loginController.getLoggedInUser();
341 // Copy contact data to contact instance
342 this.contactController.updateContactDataFromController(user.getUserContact());
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
353 user.setUserProfileMode(this.getUserProfileMode());
355 // Send it to the EJB
356 User updatedUser = this.userBean.updateUserPersonalData(user);
359 this.updatedPersonalDataEvent.fire(new UserUpdatedPersonalDataEvent(updatedUser));
362 return "user_data_saved"; //NOI18N
366 public Long getUserId () {
371 public void setUserId (final Long userId) {
372 this.userId = userId;
376 public String getUserName () {
377 return this.userName;
381 public void setUserName (final String userName) {
382 this.userName = userName;
386 public String getUserPassword () {
387 return this.userPassword;
391 public void setUserPassword (final String userPassword) {
392 this.userPassword = userPassword;
396 public String getUserPasswordRepeat () {
397 return this.userPasswordRepeat;
401 public void setUserPasswordRepeat (final String userPasswordRepeat) {
402 this.userPasswordRepeat = userPasswordRepeat;
406 public ProfileMode getUserProfileMode () {
407 return this.userProfileMode;
411 public void setUserProfileMode (final ProfileMode userProfileMode) {
412 this.userProfileMode = userProfileMode;
416 public boolean hasUsers () {
417 return (!this.allUsers().isEmpty());
421 * Post-initialization of this class
424 public void init () {
425 // Get full user name list for reducing EJB calls
426 this.userNameList = this.userBean.getUserNameList();
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();
433 // Initialize user list
434 this.visibleUserList = this.userBean.allPublicUsers();
436 // Initialize user list
437 this.userList = this.userBean.allUsers();
440 List<Contact> allContacts = this.contactBean.getAllContacts();
443 Iterator<Contact> iterator = allContacts.iterator();
446 while (iterator.hasNext()) {
448 Contact next = iterator.next();
451 Iterator<User> userIterator = this.userList.iterator();
453 // Loop through all users
454 while (userIterator.hasNext()) {
456 User nextUser = userIterator.next();
459 if (Objects.equals(next, nextUser.getUserContact())) {
468 this.selectableContacts = allContacts;
472 public boolean isContactFound (final Contact contact) {
473 // The contact must be valid
474 if (null == contact) {
476 throw new NullPointerException("contact is null"); //NOI18N
477 } else if (contact.getContactId() == null) {
479 throw new NullPointerException("contact.contactId is null"); //NOI18N
480 } else if (contact.getContactId() < 1) {
482 throw new IllegalArgumentException(MessageFormat.format("contact.contactId={0} is not valid", contact.getContactId())); //NOI18N
485 // Default is not found
486 boolean isFound = false;
489 Iterator<User> iterator = this.allUsers().iterator();
491 // Loop through all entries
492 while (iterator.hasNext()) {
494 User next = iterator.next();
496 // Compare both objects
497 if (Objects.equals(contact, next.getUserContact())) {
509 public void afterUserUpdatedPersonalData (@Observes final UpdatedUserPersonalDataEvent event) {
513 throw new NullPointerException("event is null"); //NOI18N
514 } else if (event.getUpdatedUser() == null) {
516 throw new NullPointerException("event.updatedUser is null"); //NOI18N
517 } else if (event.getUpdatedUser().getUserId() == null) {
519 throw new NullPointerException("event.updatedUser.userId is null"); //NOI18N
520 } else if (event.getUpdatedUser().getUserId() < 1) {
522 throw new IllegalArgumentException(MessageFormat.format("event.updatedUser.userId={0} is in valid", event.getUpdatedUser().getUserId())); //NOI18N
525 // All fine, so update list
526 this.updateList(event.getUpdatedUser());
530 public boolean isRequiredChangePersonalDataSet () {
531 return ((this.getUserProfileMode() != null) &&
532 (this.getUserName() != null) && (!this.getUserName().isEmpty()) &&
533 (this.contactController.isRequiredChangePersonalDataSet()));
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));
546 public boolean isSamePasswordEntered () {
547 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
551 public boolean isUserIdEmpty () {
552 return ((this.getUserId() == null) || (this.getUserId() == 0));
556 public boolean isUserNameRegistered (final User user) {
557 return ((this.userNameList instanceof List) && (this.userNameList.contains(user.getUserName())));
561 public boolean isVisibleUserFound () {
562 return ((this.visibleUserList instanceof List) && (this.visibleUserList.size() > 0));
566 public User lookupUserById (final Long userId) throws UserNotFoundException {
568 User localUser = null;
573 // Try to lookup it in visible user list
574 for (final Iterator<User> iterator = this.visibleUserList.iterator(); iterator.hasNext();) {
576 User next = iterator.next();
578 // Is the user id found?
579 if (Objects.equals(next.getUserId(), userId)) {
580 // Copy to other variable
587 if (null == localUser) {
588 // Not visible for the current user
589 throw new UserNotFoundException(userId);
592 // Copy all data to this bean
593 this.copyUser(localUser);
600 public List<Contact> selectableContacts () {
601 return Collections.unmodifiableList(this.selectableContacts);
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 }
608 * @param user User instance
610 private void addUserNameEmailAddress (final User user) {
611 // Make sure the entry is not added yet
612 if (this.userNameList.contains(user.getUserName())) {
614 throw new IllegalArgumentException(MessageFormat.format("User name {0} already added.", user.getUserName())); //NOI18N
615 } else if (this.contactController.isEmailAddressRegistered(user.getUserContact())) {
617 throw new IllegalArgumentException(MessageFormat.format("Email address {0} already added.", user.getUserContact().getContactEmailAddress())); //NOI18N
621 this.userNameList.add(user.getUserName());
624 this.contactController.addEmailAddress(user.getUserContact().getContactEmailAddress());
628 * Updates list with given user instance
630 * @param user User instance
633 public void updateList (final User user) {
634 // The user should be valid
637 throw new NullPointerException("user is null"); //NOI18N
638 } else if (user.getUserId() == null) {
640 throw new NullPointerException("user.userId is null"); //NOI18N
641 } else if (user.getUserId() < 1) {
643 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is invalid", user.getUserId())); //NOI18N
647 Iterator<User> iterator = this.userList.iterator();
650 while (iterator.hasNext()) {
652 User next = iterator.next();
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);
663 this.userList.add(user);
669 private void clear () {
672 this.setUserId(null);
673 this.setUserProfileMode(null);
676 this.setUserName(null);
677 this.setUserPassword(null);
678 this.setUserPasswordRepeat(null);
682 * Copies given user into the controller
684 * @param user User instance
686 private void copyUser (final User user) {
689 this.setUserId(user.getUserId());
690 this.setUserProfileMode(user.getUserProfileMode());
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();