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.jjobs.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.jjobs.beans.contact.JobsContactWebSessionController;
37 import org.mxchange.jjobs.beans.helper.JobsAdminWebRequestController;
38 import org.mxchange.jusercore.container.login.UserLoginContainer;
39 import org.mxchange.jusercore.events.user.add.AdminAddedUserEvent;
40 import org.mxchange.jusercore.events.user.add.AdminUserAddedEvent;
41 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
42 import org.mxchange.jusercore.events.user.update.AdminUserDataUpdatedEvent;
43 import org.mxchange.jusercore.events.user.update.UpdatedUserPersonalDataEvent;
44 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
45 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
46 import org.mxchange.jusercore.exceptions.UserNotFoundException;
47 import org.mxchange.jusercore.exceptions.UserPasswordRepeatMismatchException;
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.UserUtils;
52 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
53 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
56 * A user bean (controller)
58 * @author Roland Haeder<roland@mxchange.org>
60 @Named ("adminUserController")
62 public class JobsAdminUserWebRequestBean implements JobsAdminUserWebRequestController {
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 JobsAdminWebRequestController adminHelper;
83 * Regular contact controller
86 private JobsContactWebSessionController 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 JobsUserWebSessionController 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 JobsAdminUserWebRequestBean () {
132 // Get initial context
133 Context context = new InitialContext();
136 this.userBean = (UserSessionBeanRemote) context.lookup("java:global/jjobs-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);
195 // Create contact instance
196 Contact contact = this.contactController.createContactInstance();
198 // Set contact in user
199 user.setUserContact(contact);
201 // Init variable for password
202 String password = null;
204 // Is the user name or email address used already?
205 // @TODO Add password length check
206 if (this.userController.isUserNameRegistered(user)) {
207 // User name is already used
208 throw new FaceletException(new UserNameAlreadyRegisteredException(user));
209 } else if ((this.adminHelper.getContact() == null) && (this.contactController.isEmailAddressRegistered(user.getUserContact()))) {
210 // Email address is already used
211 throw new FaceletException(new EmailAddressAlreadyRegisteredException(user));
212 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
213 // Empty password entered, then generate one
214 password = UserUtils.createRandomPassword(JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
215 } else if (!this.isSamePasswordEntered()) {
216 // Both passwords don't match
217 throw new FaceletException(new UserPasswordRepeatMismatchException(user));
219 // Both match, so get it from this bean
220 password = this.getUserPassword();
223 // The password should not be null and at least 5 characters long
224 assert (password != null) : "password is null"; //NOI18N
225 assert (password.length() >= JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
227 // Encrypt password and set it
228 user.setUserEncryptedPassword(UserUtils.encryptPassword(password));
230 // Init updated user instance
231 User updatedUser = null;
234 // Now, that all is set, call EJB
235 if (this.adminHelper.getContact() instanceof Contact) {
236 // Link contact with this user
237 updatedUser = this.userBean.linkUser(user);
240 updatedUser = this.userBean.addUser(user);
242 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
244 throw new FaceletException(ex);
248 this.addedUserEvent.fire(new AdminUserAddedEvent(updatedUser));
250 // Add user to local list
251 this.userList.add(updatedUser);
253 // Clear contact instance
254 this.contactController.clear();
256 // Return to user list (for now)
257 return "admin_list_user"; //NOI18N
261 public void afterUserUpdatedPersonalData (@Observes final UpdatedUserPersonalDataEvent event) {
265 throw new NullPointerException("event is null"); //NOI18N
266 } else if (event.getUpdatedUser() == null) {
268 throw new NullPointerException("event.updatedUser is null"); //NOI18N
269 } else if (event.getUpdatedUser().getUserId() == null) {
271 throw new NullPointerException("event.updatedUser.userId is null"); //NOI18N
272 } else if (event.getUpdatedUser().getUserId() < 1) {
274 throw new IllegalArgumentException(MessageFormat.format("event.updatedUser.userId={0} is in valid", event.getUpdatedUser().getUserId())); //NOI18N
277 // All fine, so update list
278 this.updateList(event.getUpdatedUser());
282 public List<User> allUsers () {
284 return Collections.unmodifiableList(this.userList);
288 public String editUserData () {
290 User user = this.adminHelper.getUser();
292 // Null password means not setting it
293 String encryptedPassword = null;
295 // Check if user instance is in helper and valid
298 throw new NullPointerException("adminHelper.user is null"); //NOI18N
299 } else if (user.getUserId() == null) {
301 throw new NullPointerException("adminHelper.user.userId is null"); //NOI18N //NOI18N
302 } else if (user.getUserId() < 1) {
304 throw new IllegalStateException(MessageFormat.format("adminHelper.user.userId={0} is invalid", user.getUserId()));
305 } else if (this.getUserName() == null) {
306 // Not all required fields are set
307 throw new NullPointerException("this.userName is null"); //NOI18N
308 } else if (this.getUserName().isEmpty()) {
309 // Not all required fields are set
310 throw new IllegalArgumentException("this.userName is empty"); //NOI18N
311 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
312 // Not same password entered
313 this.setUserPassword(null);
314 this.setUserPasswordRepeat(null);
317 throw new FaceletException("Not same password entered"); //NOI18N
318 } else if (this.userBean.ifUserNameExists(this.getUserName())) {
319 // User name already exists
320 throw new FaceletException(new UserNameAlreadyRegisteredException(this.getUserName()));
321 } else if (this.isSamePasswordEntered()) {
322 // Same password entered, create container
323 if (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword()))) {
324 // Same password entered
325 throw new FaceletException("Same password as stored entered."); //NOI18N
329 encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
333 user.setUserName(this.getUserName());
335 // Is a password set?
336 if (encryptedPassword != null) {
338 user.setUserEncryptedPassword(encryptedPassword);
341 // Call EJB for updating user data
342 User updatedUser = this.userBean.updateUserData(user);
345 this.updateList(updatedUser);
348 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
350 // Return to user list (for now)
351 return "admin_list_user"; //NOI18N
355 public String getUserName () {
356 return this.userName;
360 public void setUserName (final String userName) {
361 this.userName = userName;
365 public String getUserPassword () {
366 return this.userPassword;
370 public void setUserPassword (final String userPassword) {
371 this.userPassword = userPassword;
375 public String getUserPasswordRepeat () {
376 return this.userPasswordRepeat;
380 public void setUserPasswordRepeat (final String userPasswordRepeat) {
381 this.userPasswordRepeat = userPasswordRepeat;
385 public boolean hasUsers () {
386 return (!this.allUsers().isEmpty());
390 * Post-initialization of this class
393 public void init () {
394 // Initialize user list
395 this.userList = this.userBean.allUsers();
399 public boolean isContactFound (final Contact contact) {
400 // The contact must be valid
401 if (null == contact) {
403 throw new NullPointerException("contact is null"); //NOI18N
404 } else if (contact.getContactId() == null) {
406 throw new NullPointerException("contact.contactId is null"); //NOI18N
407 } else if (contact.getContactId() < 1) {
409 throw new IllegalArgumentException(MessageFormat.format("contact.contactId={0} is not valid", contact.getContactId())); //NOI18N
412 // Default is not found
413 boolean isFound = false;
416 Iterator<User> iterator = this.allUsers().iterator();
418 // Loop through all entries
419 while (iterator.hasNext()) {
421 User next = iterator.next();
423 // Compare both objects
424 if (Objects.equals(contact, next.getUserContact())) {
436 public User lookupUserById (final Long userId) throws UserNotFoundException {
437 // Parameter must be valid
438 if (null == userId) {
440 throw new NullPointerException("userId is null"); //NOI18N
441 } else if (userId < 1) {
443 throw new IllegalArgumentException(MessageFormat.format("userId={0} is not valid.", userId)); //NOI18N
449 // Try to lookup it in visible user list
450 for (final Iterator<User> iterator = this.userList.iterator(); iterator.hasNext();) {
452 User next = iterator.next();
454 // Is the user id found?
455 if (Objects.equals(next.getUserId(), userId)) {
456 // Copy to other variable
464 // Not visible for the current user
465 throw new UserNotFoundException(userId);
473 * Checks if same password is entered and that they are not empty.
475 * @return Whether the same password was entered
477 private boolean isSamePasswordEntered () {
478 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
482 * Updates list with given user instance
484 * @param user User instance
486 private void updateList (final User user) {
487 // The user should be valid
490 throw new NullPointerException("user is null"); //NOI18N
491 } else if (user.getUserId() == null) {
493 throw new NullPointerException("user.userId is null"); //NOI18N
494 } else if (user.getUserId() < 1) {
496 throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is invalid", user.getUserId())); //NOI18N
500 Iterator<User> iterator = this.userList.iterator();
503 while (iterator.hasNext()) {
505 User next = iterator.next();
507 // Is the same user id?
508 if (Objects.equals(user.getUserId(), next.getUserId())) {
509 // Found it, so remove it
510 this.userList.remove(next);
516 this.userList.add(user);