]> git.mxchange.org Git - pizzaservice-war.git/blob - src/java/org/mxchange/pizzaapplication/beans/user/PizzaAdminUserWebRequestBean.java
6000c201b65293f86e47a0b7b422109f06a6076e
[pizzaservice-war.git] / src / java / org / mxchange / pizzaapplication / beans / user / PizzaAdminUserWebRequestBean.java
1 /*
2  * Copyright (C) 2016 Roland Haeder
3  *
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.
8  *
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.
13  *
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/>.
16  */
17 package org.mxchange.pizzaapplication.beans.user;
18
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;
54
55 /**
56  * Administrative user bean (controller)
57  * <p>
58  * @author Roland Haeder<roland@mxchange.org>
59  */
60 @Named ("adminUserController")
61 @RequestScoped
62 public class PizzaAdminUserWebRequestBean implements PizzaAdminUserWebRequestController {
63
64         /**
65          * Serial number
66          */
67         private static final long serialVersionUID = 542_145_347_916L;
68
69         /**
70          * An event fired when the administrator has added a new user
71          */
72         @Inject
73         @Any
74         private Event<AdminAddedUserEvent> addedUserEvent;
75
76         /**
77          * Admin helper instance
78          */
79         @Inject
80         private PizzaAdminWebRequestController adminHelper;
81
82         /**
83          * Regular contact controller
84          */
85         @Inject
86         private PizzaContactWebSessionController contactController;
87
88         /**
89          * An event fired when the administrator has updated a new user
90          */
91         @Inject
92         @Any
93         private Event<AdminUpdatedUserDataEvent> updatedUserDataEvent;
94
95         /**
96          * Remote user bean
97          */
98         private final UserSessionBeanRemote userBean;
99
100         /**
101          * Regular user controller
102          */
103         @Inject
104         private PizzaUserWebSessionController userController;
105
106         /**
107          * A list of all user profiles
108          */
109         private List<User> userList;
110
111         /**
112          * User name
113          */
114         private String userName;
115
116         /**
117          * User password (unencrypted from web form)
118          */
119         private String userPassword;
120
121         /**
122          * User password repeated (unencrypted from web form)
123          */
124         private String userPasswordRepeat;
125
126         /**
127          * Default constructor
128          */
129         public PizzaAdminUserWebRequestBean () {
130                 // Try it
131                 try {
132                         // Get initial context
133                         Context context = new InitialContext();
134
135                         // Try to lookup
136                         this.userBean = (UserSessionBeanRemote) context.lookup("java:global/PizzaService-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
137                 } catch (final NamingException e) {
138                         // Throw again
139                         throw new FaceletException(e);
140                 }
141         }
142
143         @Override
144         public String addUser () {
145                 // Create new user instance
146                 User user = new LoginUser();
147
148                 // As the form cannot validate the data (required="true"), check it here
149                 if (this.getUserName() == null) {
150                         // Throw NPE
151                         throw new NullPointerException("userName is null"); //NOI18N
152                 } else if (this.getUserName().isEmpty()) {
153                         // Is empty
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) {
158                                 // Throw NPE again
159                                 throw new NullPointerException("contactController.gender is null"); //NOI18N
160                         } else if (this.contactController.getFirstName() == null) {
161                                 // ... and again
162                                 throw new NullPointerException("contactController.firstName is null"); //NOI18N //NOI18N
163                         } else if (this.contactController.getFirstName().isEmpty()) {
164                                 // ... and again
165                                 throw new IllegalArgumentException("contactController.firstName is empty");
166                         } else if (this.contactController.getFamilyName() == null) {
167                                 // ... and again
168                                 throw new NullPointerException("contactController.familyName is null"); //NOI18N
169                         } else if (this.contactController.getFamilyName().isEmpty()) {
170                                 // ... and again
171                                 throw new IllegalArgumentException("contactController.familyName is empty"); //NOI18N //NOI18N
172                         } else if (this.contactController.getEmailAddress()== null) {
173                                 // ... and again
174                                 throw new NullPointerException("contactController.emailAddress is null");
175                         } else if (this.contactController.getEmailAddress().isEmpty()) {
176                                 // ... and again
177                                 throw new IllegalArgumentException("contactController.emailAddress is empty"); //NOI18N //NOI18N
178                         } else if (this.contactController.getEmailAddressRepeat()== null) {
179                                 // ... and again
180                                 throw new NullPointerException("contactController.emailAddressRepeat is null");
181                         } else if (this.contactController.getEmailAddressRepeat().isEmpty()) {
182                                 // ... and again
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.");
187                         }
188                 }
189
190                 // Set user name, CONFIRMED and INVISIBLE
191                 user.setUserName(this.getUserName());
192                 user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
193                 user.setUserProfileMode(ProfileMode.INVISIBLE);
194
195                 // Init instance
196                 Contact contact;
197
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();
202                 } else {
203                         // Create contact instance
204                         contact = this.contactController.createContactInstance();
205                 }
206
207                 // Set contact in user
208                 user.setUserContact(contact);
209
210                 // Init variable for password
211                 String password = null;
212
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));
227                 } else {
228                         // Both match, so get it from this bean
229                         password = this.getUserPassword();
230                 }
231
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
235
236                 // Encrypt password and set it
237                 user.setUserEncryptedPassword(UserUtils.encryptPassword(password));
238
239                 // Init updated user instance
240                 User updatedUser = null;
241
242                 try {
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);
247                         } else {
248                                 // Add new contact
249                                 updatedUser = this.userBean.addUser(user);
250                         }
251                         } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
252                         // Throw again
253                         throw new FaceletException(ex);
254                 }
255
256                 // Fire event
257                 this.addedUserEvent.fire(new AdminUserAddedEvent(updatedUser));
258
259                 // Add user to local list
260                 this.userList.add(updatedUser);
261
262                 // Clear contact instance
263                 this.contactController.clear();
264
265                 // Return to user list (for now)
266                 return "admin_list_user"; //NOI18N
267         }
268
269         @Override
270         public void afterUserUpdatedPersonalData (@Observes final UpdatedUserPersonalDataEvent event) {
271                 // Check parameter
272                 if (null == event) {
273                         // Throw NPE
274                         throw new NullPointerException("event is null"); //NOI18N
275                 } else if (event.getUpdatedUser() == null) {
276                         // Throw NPE again
277                         throw new NullPointerException("event.updatedUser is null"); //NOI18N
278                 } else if (event.getUpdatedUser().getUserId() == null) {
279                         // ... and again
280                         throw new NullPointerException("event.updatedUser.userId is null"); //NOI18N
281                 } else if (event.getUpdatedUser().getUserId() < 1) {
282                         // Invalid value
283                         throw new IllegalArgumentException(MessageFormat.format("event.updatedUser.userId={0} is in valid", event.getUpdatedUser().getUserId())); //NOI18N
284                 }
285
286                 // All fine, so update list
287                 this.updateList(event.getUpdatedUser());
288         }
289
290         @Override
291         public List<User> allUsers () {
292                 // Return it
293                 return Collections.unmodifiableList(this.userList);
294         }
295
296         @Override
297         public String changeUserData () {
298                 // Get user instance
299                 User user = this.adminHelper.getUser();
300
301                 // Null password means not setting it
302                 String encryptedPassword = null;
303
304                 // Check if user instance is in helper and valid
305                 if (null == user) {
306                         // Throw NPE
307                         throw new NullPointerException("adminHelper.user is null"); //NOI18N
308                 } else if (user.getUserId() == null) {
309                         // Throw NPE again
310                         throw new NullPointerException("adminHelper.user.userId is null"); //NOI18N //NOI18N
311                 } else if (user.getUserId() < 1) {
312                         // Invalid id
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);
324
325                         // Throw exception
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
335                         }
336
337                         // Encrypt password
338                         encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
339                 }
340
341                 // Set user name
342                 user.setUserName(this.getUserName());
343
344                 // Is a password set?
345                 if (encryptedPassword != null) {
346                         // Set it as well
347                         user.setUserEncryptedPassword(encryptedPassword);
348                 }
349
350                 // Call EJB for updating user data
351                 User updatedUser = this.userBean.updateUserData(user);
352
353                 // Update list
354                 this.updateList(updatedUser);
355
356                 // Fire event
357                 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
358
359                 // Return to user list (for now)
360                 return "admin_list_user"; //NOI18N
361         }
362
363         @Override
364         public String getUserName () {
365                 return this.userName;
366         }
367
368         @Override
369         public void setUserName (final String userName) {
370                 this.userName = userName;
371         }
372
373         @Override
374         public String getUserPassword () {
375                 return this.userPassword;
376         }
377
378         @Override
379         public void setUserPassword (final String userPassword) {
380                 this.userPassword = userPassword;
381         }
382
383         @Override
384         public String getUserPasswordRepeat () {
385                 return this.userPasswordRepeat;
386         }
387
388         @Override
389         public void setUserPasswordRepeat (final String userPasswordRepeat) {
390                 this.userPasswordRepeat = userPasswordRepeat;
391         }
392
393         @Override
394         public boolean hasUsers () {
395                 return (!this.allUsers().isEmpty());
396         }
397
398         /**
399          * Post-initialization of this class
400          */
401         @PostConstruct
402         public void init () {
403                 // Initialize user list
404                 this.userList = this.userBean.allUsers();
405         }
406
407         @Override
408         public User lookupUserById (final Long userId) throws UserNotFoundException {
409                 // Parameter must be valid
410                 if (null == userId) {
411                         // Throw NPE
412                         throw new NullPointerException("userId is null"); //NOI18N
413                 } else if (userId < 1) {
414                         // Not valid
415                         throw new IllegalArgumentException(MessageFormat.format("userId={0} is not valid.", userId)); //NOI18N
416                 }
417
418                 // Init variable
419                 User user = null;
420
421                 // Try to lookup it in visible user list
422                 for (final Iterator<User> iterator = this.userList.iterator(); iterator.hasNext();) {
423                         // Get next user
424                         User next = iterator.next();
425
426                         // Is the user id found?
427                         if (Objects.equals(next.getUserId(), userId)) {
428                                 // Copy to other variable
429                                 user = next;
430                                 break;
431                         }
432                 }
433
434                 // Is it still null?
435                 if (null == user) {
436                         // Not visible for the current user
437                         throw new UserNotFoundException(userId);
438                 }
439
440                 // Return it
441                 return user;
442         }
443
444         /**
445          * Checks if same password is entered and that they are not empty.
446          * <p>
447          * @return Whether the same password was entered
448          */
449         private boolean isSamePasswordEntered () {
450                 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
451         }
452
453         /**
454          * Updates list with given user instance
455          * <p>
456          * @param user User instance
457          */
458         private void updateList (final User user) {
459                 // The user should be valid
460                 if (null == user) {
461                         // Throw NPE
462                         throw new NullPointerException("user is null"); //NOI18N
463                 } else if (user.getUserId() == null) {
464                         // ... again NPE
465                         throw new NullPointerException("user.userId is null"); //NOI18N
466                 } else if (user.getUserId() < 1) {
467                         // Invalid id
468                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is invalid", user.getUserId())); //NOI18N
469                 }
470
471                 // Get iterator
472                 Iterator<User> iterator = this.userList.iterator();
473
474                 // Look whole list
475                 while (iterator.hasNext()) {
476                         // Get next element
477                         User next = iterator.next();
478
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);
483                                 break;
484                         }
485                 }
486
487                 // Re-add item
488                 this.userList.add(user);
489         }
490
491 }