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.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.jcontacts.contact.Contact;
36 import org.mxchange.jusercore.container.login.UserLoginContainer;
37 import org.mxchange.jusercore.events.user.AdminAddedUserEvent;
38 import org.mxchange.jusercore.events.user.AdminUserAddedEvent;
39 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
40 import org.mxchange.jusercore.events.user.update.AdminUserDataUpdatedEvent;
41 import org.mxchange.jusercore.events.user.update.UpdatedUserPersonalDataEvent;
42 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
43 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
44 import org.mxchange.jusercore.exceptions.UserNotFoundException;
45 import org.mxchange.jusercore.exceptions.UserPasswordRepeatMismatchException;
46 import org.mxchange.jusercore.model.user.LoginUser;
47 import org.mxchange.jusercore.model.user.User;
48 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
49 import org.mxchange.jusercore.model.user.UserUtils;
50 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
51 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
52 import org.mxchange.pizzaapplication.beans.contact.PizzaContactWebSessionController;
53 import org.mxchange.pizzaapplication.beans.helper.PizzaAdminWebRequestController;
56 * Administrative user bean (controller)
58 * @author Roland Haeder<roland@mxchange.org>
60 @Named ("adminUserController")
62 public class PizzaAdminUserWebRequestBean implements PizzaAdminUserWebRequestController {
67 private static final long serialVersionUID = 542_145_347_916L;
70 * An event fired when the administrator has added a new user
74 private Event<AdminAddedUserEvent> addedUserEvent;
77 * Admin helper instance
80 private PizzaAdminWebRequestController adminHelper;
83 * Regular contact controller
86 private PizzaContactWebSessionController contactController;
89 * An event fired when the administrator has updated a new user
93 private Event<AdminUpdatedUserDataEvent> updatedUserDataEvent;
98 private final UserSessionBeanRemote userBean;
101 * Regular user controller
104 private PizzaUserWebSessionController userController;
107 * A list of all user profiles
109 private List<User> userList;
114 private String userName;
117 * User password (unencrypted from web form)
119 private String userPassword;
122 * User password repeated (unencrypted from web form)
124 private String userPasswordRepeat;
127 * Default constructor
129 public PizzaAdminUserWebRequestBean () {
132 // Get initial context
133 Context context = new InitialContext();
136 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/PizzaService-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
137 } catch (final NamingException e) {
139 throw new FaceletException(e);
144 public String addUser () {
145 // Create new user instance
146 User user = new LoginUser();
148 // As the form cannot validate the data (required="true"), check it here
149 if (this.getUserName() == null) {
151 throw new NullPointerException("userName is null"); //NOI18N
152 } else if (this.getUserName().isEmpty()) {
154 throw new IllegalArgumentException("userName is null"); //NOI18N
155 } else if (this.adminHelper.getContact() == null) {
156 // No contact instance set, so test required fields: gender, first name and family name
157 if (this.contactController.getGender() == null) {
159 throw new NullPointerException("contactController.gender is null"); //NOI18N
160 } else if (this.contactController.getFirstName() == null) {
162 throw new NullPointerException("contactController.firstName is null"); //NOI18N //NOI18N
163 } else if (this.contactController.getFirstName().isEmpty()) {
165 throw new IllegalArgumentException("contactController.firstName is empty");
166 } else if (this.contactController.getFamilyName() == null) {
168 throw new NullPointerException("contactController.familyName is null"); //NOI18N
169 } else if (this.contactController.getFamilyName().isEmpty()) {
171 throw new IllegalArgumentException("contactController.familyName is empty"); //NOI18N //NOI18N
172 } else if (this.contactController.getEmailAddress()== null) {
174 throw new NullPointerException("contactController.emailAddress is null");
175 } else if (this.contactController.getEmailAddress().isEmpty()) {
177 throw new IllegalArgumentException("contactController.emailAddress is empty"); //NOI18N //NOI18N
178 } else if (this.contactController.getEmailAddressRepeat()== null) {
180 throw new NullPointerException("contactController.emailAddressRepeat is null");
181 } else if (this.contactController.getEmailAddressRepeat().isEmpty()) {
183 throw new IllegalArgumentException("contactController.emailAddressRepeat is empty"); //NOI18N //NOI18N
184 } else if (!Objects.equals(this.contactController.getEmailAddress(), this.contactController.getEmailAddressRepeat())) {
185 // Is not same email address
186 throw new IllegalArgumentException("Both entered email addresses don't match.");
190 // Set user name, CONFIRMED and INVISIBLE
191 user.setUserName(this.getUserName());
192 user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
193 user.setUserProfileMode(ProfileMode.INVISIBLE);
198 // Is a contact instance in helper set?
199 if (this.adminHelper.getContact() instanceof Contact) {
200 // Then use it for contact linking
201 contact = this.adminHelper.getContact();
203 // Create contact instance
204 contact = this.contactController.createContactInstance();
207 // Set contact in user
208 user.setUserContact(contact);
210 // Init variable for password
211 String password = null;
213 // Is the user name or email address used already?
214 // @TODO Add password length check
215 if (this.userController.isUserNameRegistered(user)) {
216 // User name is already used
217 throw new FaceletException(new UserNameAlreadyRegisteredException(user));
218 } else if ((this.adminHelper.getContact() == null) && (this.contactController.isEmailAddressRegistered(user.getUserContact()))) {
219 // Email address is already used
220 throw new FaceletException(new EmailAddressAlreadyRegisteredException(user));
221 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
222 // Empty password entered, then generate one
223 password = UserUtils.createRandomPassword(PizzaUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
224 } else if (!this.isSamePasswordEntered()) {
225 // Both passwords don't match
226 throw new FaceletException(new UserPasswordRepeatMismatchException(user));
228 // Both match, so get it from this bean
229 password = this.getUserPassword();
232 // The password should not be null and at least 5 characters long
233 assert (password != null) : "password is null"; //NOI18N
234 assert (password.length() >= PizzaUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
236 // Encrypt password and set it
237 user.setUserEncryptedPassword(UserUtils.encryptPassword(password));
239 // Init updated user instance
240 User updatedUser = null;
243 // Now, that all is set, call EJB
244 if (this.adminHelper.getContact() instanceof Contact) {
245 // Link contact with this user
246 updatedUser = this.userBean.linkUser(user);
249 updatedUser = this.userBean.addUser(user);
251 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
253 throw new FaceletException(ex);
257 this.addedUserEvent.fire(new AdminUserAddedEvent(updatedUser));
259 // Add user to local list
260 this.userList.add(updatedUser);
262 // Clear contact instance
263 this.contactController.clear();
265 // Return to user list (for now)
266 return "admin_list_user"; //NOI18N
270 public void afterUserUpdatedPersonalData (@Observes final UpdatedUserPersonalDataEvent event) {
274 throw new NullPointerException("event is null"); //NOI18N
275 } else if (event.getUpdatedUser() == null) {
277 throw new NullPointerException("event.updatedUser is null"); //NOI18N
278 } else if (event.getUpdatedUser().getUserId() == null) {
280 throw new NullPointerException("event.updatedUser.userId is null"); //NOI18N
281 } else if (event.getUpdatedUser().getUserId() < 1) {
283 throw new IllegalArgumentException(MessageFormat.format("event.updatedUser.userId={0} is in valid", event.getUpdatedUser().getUserId())); //NOI18N
286 // All fine, so update list
287 this.updateList(event.getUpdatedUser());
291 public List<User> allUsers () {
293 return Collections.unmodifiableList(this.userList);
297 public String changeUserData () {
299 User user = this.adminHelper.getUser();
301 // Null password means not setting it
302 String encryptedPassword = null;
304 // Check if user instance is in helper and valid
307 throw new NullPointerException("adminHelper.user is null"); //NOI18N
308 } else if (user.getUserId() == null) {
310 throw new NullPointerException("adminHelper.user.userId is null"); //NOI18N //NOI18N
311 } else if (user.getUserId() < 1) {
313 throw new IllegalStateException(MessageFormat.format("adminHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N //NOI18N
314 } else if (this.getUserName() == null) {
315 // Not all required fields are set
316 throw new NullPointerException("this.userName is null"); //NOI18N
317 } else if (this.getUserName().isEmpty()) {
318 // Not all required fields are set
319 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
320 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
321 // Not same password entered
322 this.setUserPassword(null);
323 this.setUserPasswordRepeat(null);
326 throw new FaceletException("Not same password entered"); //NOI18N
327 } else if (this.userBean.ifUserNameExists(this.getUserName())) {
328 // User name already exists
329 throw new FaceletException(new UserNameAlreadyRegisteredException(this.getUserName()));
330 } else if (this.isSamePasswordEntered()) {
331 // Same password entered, create container
332 if (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword()))) {
333 // Same password entered
334 throw new FaceletException("Same password as stored entered."); //NOI18N
338 encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
342 user.setUserName(this.getUserName());
344 // Is a password set?
345 if (encryptedPassword != null) {
347 user.setUserEncryptedPassword(encryptedPassword);
350 // Call EJB for updating user data
351 User updatedUser = this.userBean.updateUserData(user);
354 this.updateList(updatedUser);
357 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
359 // Return to user list (for now)
360 return "admin_list_user"; //NOI18N
364 public String getUserName () {
365 return this.userName;
369 public void setUserName (final String userName) {
370 this.userName = userName;
374 public String getUserPassword () {
375 return this.userPassword;
379 public void setUserPassword (final String userPassword) {
380 this.userPassword = userPassword;
384 public String getUserPasswordRepeat () {
385 return this.userPasswordRepeat;
389 public void setUserPasswordRepeat (final String userPasswordRepeat) {
390 this.userPasswordRepeat = userPasswordRepeat;
394 public boolean hasUsers () {
395 return (!this.allUsers().isEmpty());
399 * Post-initialization of this class
402 public void init () {
403 // Initialize user list
404 this.userList = this.userBean.allUsers();
408 public User lookupUserById (final Long userId) throws UserNotFoundException {
409 // Parameter must be valid
410 if (null == userId) {
412 throw new NullPointerException("userId is null"); //NOI18N
413 } else if (userId < 1) {
415 throw new IllegalArgumentException(MessageFormat.format("userId={0} is not valid.", userId)); //NOI18N
421 // Try to lookup it in visible user list
422 for (final Iterator<User> iterator = this.userList.iterator(); iterator.hasNext();) {
424 User next = iterator.next();
426 // Is the user id found?
427 if (Objects.equals(next.getUserId(), userId)) {
428 // Copy to other variable
436 // Not visible for the current user
437 throw new UserNotFoundException(userId);
445 * Checks if same password is entered and that they are not empty.
447 * @return Whether the same password was entered
449 private boolean isSamePasswordEntered () {
450 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
454 * Updates list with given user instance
456 * @param user User instance
458 private void updateList (final User user) {
459 // The user should be valid
462 throw new NullPointerException("user is null"); //NOI18N
463 } else if (user.getUserId() == null) {
465 throw new NullPointerException("user.userId is null"); //NOI18N
466 } else if (user.getUserId() < 1) {
468 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is invalid", user.getUserId())); //NOI18N
472 Iterator<User> iterator = this.userList.iterator();
475 while (iterator.hasNext()) {
477 User next = iterator.next();
479 // Is the same user id?
480 if (Objects.equals(user.getUserId(), next.getUserId())) {
481 // Found it, so remove it
482 this.userList.remove(next);
488 this.userList.add(user);