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.RequestScoped;
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.helper.AddressbookAdminWebRequestController;
37 import org.mxchange.addressbook.beans.login.AddressbookUserLoginWebSessionController;
38 import org.mxchange.jcontacts.contact.Contact;
39 import org.mxchange.jcontacts.contact.ContactSessionBeanRemote;
40 import org.mxchange.jusercore.container.login.UserLoginContainer;
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.add.AdminUserAddedEvent;
45 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
46 import org.mxchange.jusercore.events.user.update.AdminUserDataUpdatedEvent;
47 import org.mxchange.jusercore.events.user.update.UpdatedUserPersonalDataEvent;
48 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
49 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
50 import org.mxchange.jusercore.exceptions.UserNotFoundException;
51 import org.mxchange.jusercore.exceptions.UserPasswordRepeatMismatchException;
52 import org.mxchange.jusercore.model.user.LoginUser;
53 import org.mxchange.jusercore.model.user.User;
54 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
55 import org.mxchange.jusercore.model.user.UserUtils;
56 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
57 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
60 * A user bean (controller)
62 * @author Roland Haeder<roland@mxchange.org>
64 @Named ("adminUserController")
66 public class AddressbookAdminUserWebRequestBean implements AddressbookAdminUserWebRequestController {
71 private static final long serialVersionUID = 542_145_347_916L;
74 * An event fired when the administrator has added a new user
78 private Event<AdminAddedUserEvent> addedUserEvent;
81 * Admin helper instance
84 private AddressbookAdminWebRequestController adminHelper;
89 private final ContactSessionBeanRemote contactBean;
92 * Regular contact controller
95 private AddressbookContactWebSessionController contactController;
98 * A list of all selectable contacts
100 private List<Contact> selectableContacts;
103 * An event fired when the administrator has updated a new user
107 private Event<AdminUpdatedUserDataEvent> updatedUserDataEvent;
112 private final UserSessionBeanRemote userBean;
115 * Regular user controller
118 private AddressbookUserWebSessionController userController;
121 * A list of all user profiles
123 private List<User> userList;
126 * Login bean (controller)
129 private AddressbookUserLoginWebSessionController userLoginController;
134 private String userName;
139 private List<String> userNameList;
142 * User password (unencrypted from web form)
144 private String userPassword;
147 * User password repeated (unencrypted from web form)
149 private String userPasswordRepeat;
152 * A list of all public user profiles
154 private List<User> visibleUserList;
157 * Default constructor
159 public AddressbookAdminUserWebRequestBean () {
162 // Get initial context
163 Context context = new InitialContext();
166 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/addressbook-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
169 this.contactBean = (ContactSessionBeanRemote) context.lookup("java:global/addressbook-ejb/contact!org.mxchange.jcontacts.contact.ContactSessionBeanRemote"); //NOI18N
170 } catch (final NamingException e) {
172 throw new FaceletException(e);
177 public String addUser () {
178 // Create new user instance
179 User user = new LoginUser();
181 // As the form cannot validate the data (required="true"), check it here
182 if (this.getUserName() == null) {
184 throw new NullPointerException("userName is null"); //NOI18N
185 } else if (this.getUserName().isEmpty()) {
187 throw new IllegalArgumentException("userName is null"); //NOI18N
188 } else if (this.adminHelper.getContact() == null) {
189 // No contact instance set, so test required fields: gender, first name and family name
190 if (this.contactController.getGender() == null) {
192 throw new NullPointerException("contactController.gender is null"); //NOI18N
193 } else if (this.contactController.getFirstName() == null) {
195 throw new NullPointerException("contactController.firstName is null"); //NOI18N //NOI18N
196 } else if (this.contactController.getFirstName().isEmpty()) {
198 throw new IllegalArgumentException("contactController.firstName is empty");
199 } else if (this.contactController.getFamilyName() == null) {
201 throw new NullPointerException("contactController.familyName is null"); //NOI18N
202 } else if (this.contactController.getFamilyName().isEmpty()) {
204 throw new IllegalArgumentException("contactController.familyName is empty"); //NOI18N //NOI18N
205 } else if (this.contactController.getEmailAddress() == null) {
207 throw new NullPointerException("contactController.emailAddress is null");
208 } else if (this.contactController.getEmailAddress().isEmpty()) {
210 throw new IllegalArgumentException("contactController.emailAddress is empty"); //NOI18N //NOI18N
211 } else if (this.contactController.getEmailAddressRepeat() == null) {
213 throw new NullPointerException("contactController.emailAddressRepeat is null");
214 } else if (this.contactController.getEmailAddressRepeat().isEmpty()) {
216 throw new IllegalArgumentException("contactController.emailAddressRepeat is empty"); //NOI18N //NOI18N
217 } else if (!Objects.equals(this.contactController.getEmailAddress(), this.contactController.getEmailAddressRepeat())) {
218 // Is not same email address
219 throw new IllegalArgumentException("Both entered email addresses don't match.");
223 // Set user name, CONFIRMED and INVISIBLE
224 user.setUserName(this.getUserName());
225 user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
226 user.setUserProfileMode(ProfileMode.INVISIBLE);
231 // Is a contact instance in helper set?
232 if (this.adminHelper.getContact() instanceof Contact) {
233 // Then use it for contact linking
234 contact = this.adminHelper.getContact();
236 // Create contact instance
237 contact = this.contactController.createContactInstance();
240 // Set contact in user
241 user.setUserContact(contact);
243 // Init variable for password
244 String password = null;
246 // Is the user name or email address used already?
247 // @TODO Add password length check
248 if (this.isUserNameRegistered(user)) {
249 // User name is already used
250 throw new FaceletException(new UserNameAlreadyRegisteredException(user));
251 } else if ((this.adminHelper.getContact() == null) && (this.contactController.isEmailAddressRegistered(user.getUserContact()))) {
252 // Email address is already used
253 throw new FaceletException(new EmailAddressAlreadyRegisteredException(user));
254 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
255 // Empty password entered, then generate one
256 password = UserUtils.createRandomPassword(AddressbookUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
257 } else if (!this.isSamePasswordEntered()) {
258 // Both passwords don't match
259 throw new FaceletException(new UserPasswordRepeatMismatchException(user));
261 // Both match, so get it from this bean
262 password = this.getUserPassword();
265 // The password should not be null and at least 5 characters long
266 assert (password != null) : "password is null"; //NOI18N
267 assert (password.length() >= AddressbookUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
269 // Encrypt password and set it
270 user.setUserEncryptedPassword(UserUtils.encryptPassword(password));
272 // Init updated user instance
273 User updatedUser = null;
276 // Now, that all is set, call EJB
277 if (this.adminHelper.getContact() instanceof Contact) {
278 // Link contact with this user
279 updatedUser = this.userBean.linkUser(user);
281 // Remove contact instance
282 this.adminHelper.setContact(null);
285 updatedUser = this.userBean.addUser(user);
287 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
289 throw new FaceletException(ex);
293 this.addedUserEvent.fire(new AdminUserAddedEvent(updatedUser));
298 // Return to user list (for now)
299 return "admin_list_user"; //NOI18N
303 public void afterRegistrationEvent (final @Observes UserRegisteredEvent event) {
305 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("AdminUserWebBean:afterRegistration: event={0} - CALLED!", event)); //NOI18N
307 // event should not be null
310 throw new NullPointerException("event is null"); //NOI18N
311 } else if (event.getRegisteredUser() == null) {
313 throw new NullPointerException("event.user is null"); //NOI18N
314 } else if (event.getRegisteredUser().getUserId() == null) {
316 throw new NullPointerException("event.user.userId is null"); //NOI18N
317 } else if (event.getRegisteredUser().getUserId() < 1) {
319 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
323 User registeredUser = event.getRegisteredUser();
326 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("AdminUserWebBean:afterRegistration: registeredUser={0}", registeredUser)); //NOI18N
327 // Add user to local list
328 this.userList.add(registeredUser);
330 // Is the account public?
331 if (Objects.equals(registeredUser.getUserProfileMode(), ProfileMode.PUBLIC)) {
332 // Also add it to this list
333 this.visibleUserList.add(registeredUser);
336 // Add user name and email address
337 this.addUserNameEmailAddress(registeredUser);
343 //* NOISY-DEBUG: */ System.out.println("AdminUserWebBean:afterRegistration: EXIT!"); //NOI18N
347 public void afterUserLogin (final @Observes UserLoggedInEvent event) {
349 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("AdminUserWebBean:afterUserLogin: event={0} - CALLED!", event)); //NOI18N
351 // event should not be null
354 throw new NullPointerException("event is null"); //NOI18N
355 } else if (event.getLoggedInUser() == null) {
357 throw new NullPointerException("event.user is null"); //NOI18N
358 } else if (event.getLoggedInUser().getUserId() == null) {
360 throw new NullPointerException("event.user.userId is null"); //NOI18N
361 } else if (event.getLoggedInUser().getUserId() < 1) {
363 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getLoggedInUser(), event.getLoggedInUser().getUserId())); //NOI18N
366 // Re-initialize list
367 this.visibleUserList = this.userBean.allMemberPublicVisibleUsers();
370 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("AdminUserWebBean:afterUserLogin: this.visibleUserList.size()={0} - EXIT!", this.visibleUserList.size())); //NOI18N
374 public void afterUserUpdatedPersonalData (@Observes final UpdatedUserPersonalDataEvent event) {
378 throw new NullPointerException("event is null"); //NOI18N
379 } else if (event.getUpdatedUser() == null) {
381 throw new NullPointerException("event.updatedUser is null"); //NOI18N
382 } else if (event.getUpdatedUser().getUserId() == null) {
384 throw new NullPointerException("event.updatedUser.userId is null"); //NOI18N
385 } else if (event.getUpdatedUser().getUserId() < 1) {
387 throw new IllegalArgumentException(MessageFormat.format("event.updatedUser.userId={0} is in valid", event.getUpdatedUser().getUserId())); //NOI18N
390 // All fine, so update list
391 this.updateList(event.getUpdatedUser());
395 public List<User> allUsers () {
397 return Collections.unmodifiableList(this.userList);
401 public List<User> allVisibleUsers () {
403 return Collections.unmodifiableList(this.visibleUserList);
407 public String editUserData () {
409 User user = this.adminHelper.getUser();
411 // Null password means not setting it
412 String encryptedPassword = null;
414 // Check if user instance is in helper and valid
417 throw new NullPointerException("adminHelper.user is null"); //NOI18N
418 } else if (user.getUserId() == null) {
420 throw new NullPointerException("adminHelper.user.userId is null"); //NOI18N //NOI18N
421 } else if (user.getUserId() < 1) {
423 throw new IllegalStateException(MessageFormat.format("adminHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N //NOI18N
424 } else if (this.getUserName() == null) {
425 // Not all required fields are set
426 throw new NullPointerException("this.userName is null"); //NOI18N
427 } else if (this.getUserName().isEmpty()) {
428 // Not all required fields are set
429 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
430 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
431 // Not same password entered
432 this.setUserPassword(null);
433 this.setUserPasswordRepeat(null);
436 throw new FaceletException("Not same password entered"); //NOI18N
437 } else if (this.userBean.ifUserNameExists(this.getUserName())) {
438 // User name already exists
439 throw new FaceletException(new UserNameAlreadyRegisteredException(this.getUserName()));
440 } else if (this.isSamePasswordEntered()) {
441 // Same password entered, create container
442 if (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword()))) {
443 // Same password entered
444 throw new FaceletException("Same password as stored entered."); //NOI18N
448 encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
452 user.setUserName(this.getUserName());
454 // Is a password set?
455 if (encryptedPassword != null) {
457 user.setUserEncryptedPassword(encryptedPassword);
460 // Call EJB for updating user data
461 User updatedUser = this.userBean.updateUserData(user);
464 this.updateList(updatedUser);
467 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
469 // Return to user list (for now)
470 return "admin_list_user"; //NOI18N
474 public String getUserName () {
475 return this.userName;
479 public void setUserName (final String userName) {
480 this.userName = userName;
484 public String getUserPassword () {
485 return this.userPassword;
489 public void setUserPassword (final String userPassword) {
490 this.userPassword = userPassword;
494 public String getUserPasswordRepeat () {
495 return this.userPasswordRepeat;
499 public void setUserPasswordRepeat (final String userPasswordRepeat) {
500 this.userPasswordRepeat = userPasswordRepeat;
504 public boolean hasUsers () {
505 return (!this.allUsers().isEmpty());
509 * Post-initialization of this class
512 public void init () {
513 // Get full user name list for reducing EJB calls
514 this.userNameList = this.userBean.getUserNameList();
516 // Is the user logged-in?
517 if (this.userLoginController.isUserLoggedIn()) {
518 // Is logged-in, so load also users visible to memebers
519 this.visibleUserList = this.userBean.allMemberPublicVisibleUsers();
521 // Initialize user list
522 this.visibleUserList = this.userBean.allPublicUsers();
525 // Initialize user list
526 this.userList = this.userBean.allUsers();
528 // Get full user name list for reducing EJB calls
529 this.userNameList = this.userBean.getUserNameList();
531 // Is the user logged-in?
532 if (this.userLoginController.isUserLoggedIn()) {
533 // Is logged-in, so load also users visible to memebers
534 this.visibleUserList = this.userBean.allMemberPublicVisibleUsers();
536 // Initialize user list
537 this.visibleUserList = this.userBean.allPublicUsers();
541 List<Contact> allContacts = this.contactController.allContacts();
544 Iterator<Contact> iterator = allContacts.iterator();
547 while (iterator.hasNext()) {
549 Contact next = iterator.next();
552 Iterator<User> userIterator = this.userList.iterator();
554 // Loop through all users
555 while (userIterator.hasNext()) {
557 User nextUser = userIterator.next();
560 if (Objects.equals(next, nextUser.getUserContact())) {
569 this.selectableContacts = allContacts;
573 public boolean isContactFound (final Contact contact) {
574 // The contact must be valid
575 if (null == contact) {
577 throw new NullPointerException("contact is null"); //NOI18N
578 } else if (contact.getContactId() == null) {
580 throw new NullPointerException("contact.contactId is null"); //NOI18N
581 } else if (contact.getContactId() < 1) {
583 throw new IllegalArgumentException(MessageFormat.format("contact.contactId={0} is not valid", contact.getContactId())); //NOI18N
586 // Default is not found
587 boolean isFound = false;
590 Iterator<User> iterator = this.allUsers().iterator();
592 // Loop through all entries
593 while (iterator.hasNext()) {
595 User next = iterator.next();
597 // Compare both objects
598 if (Objects.equals(contact, next.getUserContact())) {
610 public boolean isUserNameRegistered (final User user) {
611 return ((this.userNameList instanceof List) && (this.userNameList.contains(user.getUserName())));
615 public boolean isVisibleUserFound () {
616 return ((this.visibleUserList instanceof List) && (this.visibleUserList.size() > 0));
620 public User lookupUserById (final Long userId) throws UserNotFoundException {
621 // Parameter must be valid
622 if (null == userId) {
624 throw new NullPointerException("userId is null"); //NOI18N
625 } else if (userId < 1) {
627 throw new IllegalArgumentException(MessageFormat.format("userId={0} is not valid.", userId)); //NOI18N
633 // Try to lookup it in visible user list
634 for (final Iterator<User> iterator = this.userList.iterator(); iterator.hasNext();) {
636 User next = iterator.next();
638 // Is the user id found?
639 if (Objects.equals(next.getUserId(), userId)) {
640 // Copy to other variable
648 // Not visible for the current user
649 throw new UserNotFoundException(userId);
657 public List<Contact> selectableContacts () {
658 return Collections.unmodifiableList(this.selectableContacts);
662 * Updates list with given user instance
664 * @param user User instance
667 public void updateList (final User user) {
668 // The user should be valid
671 throw new NullPointerException("user is null"); //NOI18N
672 } else if (user.getUserId() == null) {
674 throw new NullPointerException("user.userId is null"); //NOI18N
675 } else if (user.getUserId() < 1) {
677 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is invalid", user.getUserId())); //NOI18N
681 Iterator<User> iterator = this.userList.iterator();
684 while (iterator.hasNext()) {
686 User next = iterator.next();
688 // Is the same user id?
689 if (Objects.equals(user.getUserId(), next.getUserId())) {
690 // Found it, so remove it
691 this.userList.remove(next);
697 this.userList.add(user);
701 * Adds user's name and email address to bean's internal list. It also
702 * updates the public user list if the user has decided to ha }
704 * @param user User instance
706 private void addUserNameEmailAddress (final User user) {
707 // Make sure the entry is not added yet
708 if (this.userNameList.contains(user.getUserName())) {
710 throw new IllegalArgumentException(MessageFormat.format("User name {0} already added.", user.getUserName())); //NOI18N
711 } else if (this.contactController.isEmailAddressRegistered(user.getUserContact())) {
713 throw new IllegalArgumentException(MessageFormat.format("Email address {0} already added.", user.getUserContact().getContactEmailAddress())); //NOI18N
717 this.userNameList.add(user.getUserName());
720 this.contactController.addEmailAddress(user.getUserContact().getContactEmailAddress());
726 private void clear () {
729 this.setUserName(null);
730 this.setUserPassword(null);
731 this.setUserPasswordRepeat(null);
735 * Checks if same password is entered and that they are not empty.
737 * @return Whether the same password was entered
739 private boolean isSamePasswordEntered () {
740 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));