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.addressbook.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.addressbook.beans.contact.AddressbookContactWebSessionController;
36 import org.mxchange.addressbook.beans.login.AddressbookUserLoginWebSessionController;
37 import org.mxchange.jcontacts.contact.Contact;
38 import org.mxchange.jphone.phonenumbers.cellphone.DialableCellphoneNumber;
39 import org.mxchange.jphone.phonenumbers.fax.DialableFaxNumber;
40 import org.mxchange.jphone.phonenumbers.landline.DialableLandLineNumber;
41 import org.mxchange.jusercore.events.login.UserLoggedInEvent;
42 import org.mxchange.jusercore.events.registration.UserRegisteredEvent;
43 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
44 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
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.exceptions.UserPasswordMismatchException;
49 import org.mxchange.jusercore.model.user.LoginUser;
50 import org.mxchange.jusercore.model.user.User;
51 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
52 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
55 * A user bean (controller)
57 * @author Roland Haeder<roland@mxchange.org>
59 @Named ("userController")
61 public class AddressbookUserWebSessionBean implements AddressbookUserWebSessionController {
66 private static final long serialVersionUID = 542_145_347_916L;
69 * General contact controller
72 private AddressbookContactWebSessionController contactController;
75 * Login bean (controller)
78 private AddressbookUserLoginWebSessionController loginController;
81 * A list of all selectable contacts
83 private List<Contact> selectableContacts;
86 * Event being fired when user updated personal data
90 private Event<UpdatedUserPersonalDataEvent> updatedPersonalDataEvent;
95 private final UserSessionBeanRemote userBean;
103 * A list of all user profiles
105 private List<User> userList;
108 * Login bean (controller)
111 private AddressbookUserLoginWebSessionController userLoginController;
116 private String userName;
121 private List<String> userNameList;
124 * User password (unencrypted from web form)
126 private String userPassword;
129 * User password repeated (unencrypted from web form)
131 private String userPasswordRepeat;
134 * Whether the user wants a public profile
136 private ProfileMode userProfileMode;
139 * A list of all public user profiles
141 private List<User> visibleUserList;
144 * Default constructor
146 public AddressbookUserWebSessionBean () {
149 // Get initial context
150 Context context = new InitialContext();
153 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/addressbook-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
154 } catch (final NamingException e) {
156 throw new FaceletException(e);
161 public void afterAdminAddedUserEvent (@Observes final AdminAddedUserEvent event) {
163 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterAdminAddedUserEvent: event={0} - CALLED!", event)); //NOI18N
165 // event should not be null
168 throw new NullPointerException("event is null"); //NOI18N
169 } else if (event.getAddedUser() == null) {
171 throw new NullPointerException("event.addedUser is null"); //NOI18N
172 } else if (event.getAddedUser().getUserId() == null) {
174 throw new NullPointerException("event.addedUser.userId is null"); //NOI18N
175 } else if (event.getAddedUser().getUserId() < 1) {
177 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getAddedUser(), event.getAddedUser().getUserId())); //NOI18N
180 // Add user to local list
181 this.userList.add(event.getAddedUser());
187 this.setUserId(event.getAddedUser().getUserId());
190 //* NOISY-DEBUG: */ System.out.println("UserWebBean:afterAdminAddedUserEvent: EXIT!"); //NOI18N
194 public void afterAdminUpdatedUserDataEvent (@Observes final AdminUpdatedUserDataEvent event) {
196 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterAdminUpdatedUserEvent: event={0} - CALLED!", event)); //NOI18N
198 // event should not be null
201 throw new NullPointerException("event is null"); //NOI18N
202 } else if (event.getUpdatedUser() == null) {
204 throw new NullPointerException("event.updatedUser is null"); //NOI18N
205 } else if (event.getUpdatedUser().getUserId() == null) {
207 throw new NullPointerException("event.updatedUser.userId is null"); //NOI18N
208 } else if (event.getUpdatedUser().getUserId() < 1) {
210 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getUpdatedUser(), event.getUpdatedUser().getUserId())); //NOI18N
214 this.updateList(event.getUpdatedUser());
220 //* NOISY-DEBUG: */ System.out.println("UserWebBean:afterAdminUpdatedUserEvent: EXIT!"); //NOI18N
224 public void afterRegistrationEvent (@Observes final UserRegisteredEvent event) {
226 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterRegistration: event={0} - CALLED!", event)); //NOI18N
228 // event should not be null
231 throw new NullPointerException("event is null"); //NOI18N
232 } else if (event.getRegisteredUser() == null) {
234 throw new NullPointerException("event.registeredUser is null"); //NOI18N
235 } else if (event.getRegisteredUser().getUserId() == null) {
237 throw new NullPointerException("event.registeredUser.userId is null"); //NOI18N
238 } else if (event.getRegisteredUser().getUserId() < 1) {
240 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
244 User registeredUser = event.getRegisteredUser();
247 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterRegistration: registeredUser={0}", registeredUser)); //NOI18N
249 // Copy all data from registered->user
250 this.copyUser(registeredUser);
255 // Add user to local list
256 this.userList.add(registeredUser);
259 this.addUserName(registeredUser);
261 // Is the account public?
262 if (Objects.equals(registeredUser.getUserProfileMode(), ProfileMode.PUBLIC)) {
263 // Also add it to this list
264 this.visibleUserList.add(registeredUser);
268 this.setUserId(registeredUser.getUserId());
271 //* NOISY-DEBUG: */ System.out.println("UserWebBean:afterRegistration: EXIT!"); //NOI18N
275 public void afterUserLogin (final @Observes UserLoggedInEvent event) {
277 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterUserLogin: event={0} - CALLED!", event)); //NOI18N
279 // event should not be null
282 throw new NullPointerException("event is null"); //NOI18N
283 } else if (event.getLoggedInUser() == null) {
285 throw new NullPointerException("event.registeredUser is null"); //NOI18N
286 } else if (event.getLoggedInUser().getUserId() == null) {
288 throw new NullPointerException("event.registeredUser.userId is null"); //NOI18N
289 } else if (event.getLoggedInUser().getUserId() < 1) {
291 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getLoggedInUser(), event.getLoggedInUser().getUserId())); //NOI18N
294 // Copy all data to this bean
295 this.copyUser(event.getLoggedInUser());
297 // Re-initialize list
298 this.visibleUserList = this.userBean.allMemberPublicVisibleUsers();
304 public void afterUserUpdatedPersonalData (@Observes final UpdatedUserPersonalDataEvent event) {
308 throw new NullPointerException("event is null"); //NOI18N
309 } else if (event.getUpdatedUser() == null) {
311 throw new NullPointerException("event.updatedUser is null"); //NOI18N
312 } else if (event.getUpdatedUser().getUserId() == null) {
314 throw new NullPointerException("event.updatedUser.userId is null"); //NOI18N
315 } else if (event.getUpdatedUser().getUserId() < 1) {
317 throw new IllegalArgumentException(MessageFormat.format("event.updatedUser.userId={0} is in valid", event.getUpdatedUser().getUserId())); //NOI18N
320 // All fine, so update list
321 this.updateList(event.getUpdatedUser());
325 public List<User> allUsers () {
327 return Collections.unmodifiableList(this.userList);
331 public List<User> allVisibleUsers () {
333 return Collections.unmodifiableList(this.visibleUserList);
337 public User createUserInstance () {
339 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("{0}.createUserInstance: CALLED!", this.getClass().getSimpleName()));
341 // Required personal data must be set
342 assert (this.isRequiredPersonalDataSet()) : "not all personal data is set"; //NOI18N
344 // Create new user instance
345 User localUser = new LoginUser();
347 // Update all data ...
348 localUser.setUserName(this.getUserName());
349 localUser.setUserProfileMode(this.getUserProfileMode());
351 // Create contact instance
352 Contact contact = this.contactController.createContactInstance();
355 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("{0}.createUserInstance: contact={1}", this.getClass().getSimpleName(), contact));
357 // Set contact in user
358 localUser.setUserContact(contact);
361 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("{0}.createUserInstance: user={1} - EXIT!", this.getClass().getSimpleName(), user));
368 public String doChangePersonalData () {
369 // This method shall only be called if the user is logged-in
370 if (!this.loginController.isUserLoggedIn()) {
372 throw new IllegalStateException("User is not logged-in"); //NOI18N
373 } else if (!this.isRequiredChangePersonalDataSet()) {
374 // Not all required fields are set
375 throw new FaceletException("Not all required fields are set."); //NOI18N
376 } else if (!this.loginController.ifCurrentPasswordMatches()) {
377 // Password not matching
378 throw new FaceletException(new UserPasswordMismatchException(this.loginController.getLoggedInUser()));
382 User user = this.loginController.getLoggedInUser();
384 // Copy contact data to contact instance
385 this.contactController.updateContactDataFromController(user.getUserContact());
387 // It should be there, so run some tests on it
388 assert (user instanceof User) : "Instance loginController.loggedInUser is null";
389 assert (user.getUserId() instanceof Long) : "Instance loginController.loggedInUser.userId is null";
390 assert (user.getUserId() > 0) : MessageFormat.format("loginController.loggedInUser.userId={0} is invalid", user.getUserId());
391 assert (user.getUserContact() instanceof Contact) : "Instance loginController.loggedInUser.userContact is null";
392 assert (user.getUserContact().getContactId() instanceof Long) : "Instance loginController.userContact.contactId is null";
393 assert (user.getUserContact().getContactId() > 0) : MessageFormat.format("Instance loginController.userContact.contactId={0} is invalid", user.getUserContact().getContactId());
396 user.setUserProfileMode(this.getUserProfileMode());
398 // Send it to the EJB
399 User updatedUser = this.userBean.updateUserPersonalData(user);
402 this.updatedPersonalDataEvent.fire(new UserUpdatedPersonalDataEvent(updatedUser));
405 return "user_data_saved"; //NOI18N
409 public Long getUserId () {
414 public void setUserId (final Long userId) {
415 this.userId = userId;
419 public String getUserName () {
420 return this.userName;
424 public void setUserName (final String userName) {
425 this.userName = userName;
429 public String getUserPassword () {
430 return this.userPassword;
434 public void setUserPassword (final String userPassword) {
435 this.userPassword = userPassword;
439 public String getUserPasswordRepeat () {
440 return this.userPasswordRepeat;
444 public void setUserPasswordRepeat (final String userPasswordRepeat) {
445 this.userPasswordRepeat = userPasswordRepeat;
449 public ProfileMode getUserProfileMode () {
450 return this.userProfileMode;
454 public void setUserProfileMode (final ProfileMode userProfileMode) {
455 this.userProfileMode = userProfileMode;
459 public boolean hasUsers () {
460 return (!this.allUsers().isEmpty());
464 * Post-initialization of this class
467 public void init () {
468 // Initialize user list
469 this.userList = this.userBean.allUsers();
471 // Get full user name list for reducing EJB calls
472 this.userNameList = this.userBean.getUserNameList();
474 // Is the user logged-in?
475 if (this.userLoginController.isUserLoggedIn()) {
476 // Is logged-in, so load also users visible to memebers
477 this.visibleUserList = this.userBean.allMemberPublicVisibleUsers();
479 // Initialize user list
480 this.visibleUserList = this.userBean.allPublicUsers();
484 List<User> allUsers = this.allUsers();
487 List<Contact> allContacts = this.contactController.allContacts();
490 Iterator<Contact> iterator = allContacts.iterator();
493 while (iterator.hasNext()) {
495 Contact next = iterator.next();
498 Iterator<User> userIterator = allUsers.iterator();
500 // Loop through all users
501 while (userIterator.hasNext()) {
503 User nextUser = userIterator.next();
506 if (Objects.equals(next, nextUser.getUserContact())) {
515 this.selectableContacts = allContacts;
519 public boolean isContactFound (final Contact contact) {
520 // The contact must be valid
521 if (null == contact) {
523 throw new NullPointerException("contact is null"); //NOI18N
524 } else if (contact.getContactId() == null) {
526 throw new NullPointerException("contact.contactId is null"); //NOI18N
527 } else if (contact.getContactId() < 1) {
529 throw new IllegalArgumentException(MessageFormat.format("contact.contactId={0} is not valid", contact.getContactId())); //NOI18N
532 // Default is not found
533 boolean isFound = false;
536 Iterator<User> iterator = this.allUsers().iterator();
538 // Loop through all entries
539 while (iterator.hasNext()) {
541 User next = iterator.next();
543 // Compare both objects
544 if (Objects.equals(contact, next.getUserContact())) {
556 public boolean isRequiredChangePersonalDataSet () {
557 return ((this.getUserProfileMode() != null) &&
558 (this.getUserName() != null) && (!this.getUserName().isEmpty()) &&
559 (this.contactController.isRequiredChangePersonalDataSet()));
563 public boolean isRequiredPersonalDataSet () {
564 return ((this.getUserName() != null) &&
565 (this.getUserProfileMode() != null) &&
566 (this.contactController.isRequiredPersonalDataSet()) &&
567 (this.getUserPassword() != null) &&
568 (this.getUserPasswordRepeat() != null));
572 public boolean isSamePasswordEntered () {
573 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
577 public boolean isUserIdEmpty () {
578 return ((this.getUserId() == null) || (this.getUserId() == 0));
582 public boolean isUserNameRegistered (final User user) {
583 return ((this.userNameList instanceof List) && (this.userNameList.contains(user.getUserName())));
587 public boolean isVisibleUserFound () {
588 return ((this.visibleUserList instanceof List) && (this.visibleUserList.size() > 0));
592 public User lookupUserById (final Long userId) throws UserNotFoundException {
593 // Parameter must be valid
594 if (null == userId) {
596 throw new NullPointerException("userId is null"); //NOI18N
597 } else if (userId < 1) {
599 throw new IllegalArgumentException(MessageFormat.format("userId={0} is not valid.", userId)); //NOI18N
605 // Try to lookup it in visible user list
606 for (final Iterator<User> iterator = this.userList.iterator(); iterator.hasNext();) {
608 User next = iterator.next();
610 // Is the user id found?
611 if (Objects.equals(next.getUserId(), userId)) {
612 // Copy to other variable
620 // Not visible for the current user
621 throw new UserNotFoundException(userId);
629 public List<Contact> selectableContacts () {
630 return Collections.unmodifiableList(this.selectableContacts);
634 * Adds user's name to bean's internal list. It also updates the public user
635 * list if the user has decided to have a public account,
637 * @param user User instance
639 private void addUserName (final User user) {
640 // Make sure the entry is not added yet
641 if (this.userNameList.contains(user.getUserName())) {
643 throw new IllegalArgumentException(MessageFormat.format("User name {0} already added.", user.getUserName())); //NOI18N
644 } else if (this.contactController.isEmailAddressRegistered(user.getUserContact())) {
646 throw new IllegalArgumentException(MessageFormat.format("Email address {0} already added.", user.getUserContact().getContactEmailAddress())); //NOI18N
650 this.userNameList.add(user.getUserName());
656 private void clear () {
659 this.setUserId(null);
660 this.setUserProfileMode(null);
663 this.setUserName(null);
664 this.setUserPassword(null);
665 this.setUserPasswordRepeat(null);
669 * Copies given user into the controller
671 * @param user User instance
673 private void copyUser (final User user) {
676 this.setUserId(user.getUserId());
677 this.setUserProfileMode(user.getUserProfileMode());
679 // Get cellphone, phone and fax instance
680 DialableCellphoneNumber cellphone = user.getUserContact().getContactCellphoneNumber();
681 DialableFaxNumber fax = user.getUserContact().getContactFaxNumber();
682 DialableLandLineNumber phone = user.getUserContact().getContactLandLineNumber();
686 * Updates list with given user instance
688 * @param user User instance
690 private void updateList (final User user) {
691 // The user should be valid
694 throw new NullPointerException("user is null"); //NOI18N
695 } else if (user.getUserId() == null) {
697 throw new NullPointerException("user.userId is null"); //NOI18N
698 } else if (user.getUserId() < 1) {
700 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is invalid", user.getUserId())); //NOI18N
704 Iterator<User> iterator = this.userList.iterator();
707 while (iterator.hasNext()) {
709 User next = iterator.next();
711 // Is the same user id?
712 if (Objects.equals(user.getUserId(), next.getUserId())) {
713 // Found it, so remove it
714 this.userList.remove(next);
720 this.userList.add(user);