]> git.mxchange.org Git - pizzaservice-war.git/blob - src/java/org/mxchange/pizzaapplication/beans/user/PizzaAdminUserWebRequestBean.java
Refactured a lot:
[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.Objects;
21 import javax.annotation.PostConstruct;
22 import javax.enterprise.context.RequestScoped;
23 import javax.enterprise.event.Event;
24 import javax.enterprise.inject.Any;
25 import javax.faces.view.facelets.FaceletException;
26 import javax.inject.Inject;
27 import javax.inject.Named;
28 import javax.naming.Context;
29 import javax.naming.InitialContext;
30 import javax.naming.NamingException;
31 import org.mxchange.jcontacts.contact.Contact;
32 import org.mxchange.jusercore.container.login.UserLoginContainer;
33 import org.mxchange.jusercore.events.user.AdminAddedUserEvent;
34 import org.mxchange.jusercore.events.user.AdminUserAddedEvent;
35 import org.mxchange.jusercore.events.user.update.AdminUpdatedUserDataEvent;
36 import org.mxchange.jusercore.events.user.update.AdminUserDataUpdatedEvent;
37 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
38 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
39 import org.mxchange.jusercore.exceptions.UserPasswordRepeatMismatchException;
40 import org.mxchange.jusercore.model.user.LoginUser;
41 import org.mxchange.jusercore.model.user.User;
42 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
43 import org.mxchange.jusercore.model.user.UserUtils;
44 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
45 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
46 import org.mxchange.pizzaapplication.beans.contact.PizzaContactWebSessionController;
47 import org.mxchange.pizzaapplication.beans.helper.PizzaAdminWebRequestController;
48
49 /**
50  * Administrative user bean (controller)
51  * <p>
52  * @author Roland Haeder<roland@mxchange.org>
53  */
54 @Named ("adminUserController")
55 @RequestScoped
56 public class PizzaAdminUserWebRequestBean implements PizzaAdminUserWebRequestController {
57
58         /**
59          * Serial number
60          */
61         private static final long serialVersionUID = 542_145_347_916L;
62
63         /**
64          * An event fired when the administrator has added a new user
65          */
66         @Inject
67         @Any
68         private Event<AdminAddedUserEvent> addedUserEvent;
69
70         /**
71          * Admin helper instance
72          */
73         @Inject
74         private PizzaAdminWebRequestController adminHelper;
75
76         /**
77          * Regular contact controller
78          */
79         @Inject
80         private PizzaContactWebSessionController contactController;
81
82         /**
83          * An event fired when the administrator has updated a new user
84          */
85         @Inject
86         @Any
87         private Event<AdminUpdatedUserDataEvent> updatedUserDataEvent;
88
89         /**
90          * Remote user bean
91          */
92         private final UserSessionBeanRemote userBean;
93
94         /**
95          * Regular user controller
96          */
97         @Inject
98         private PizzaUserWebSessionController userController;
99
100         /**
101          * User name
102          */
103         private String userName;
104
105         /**
106          * User password (unencrypted from web form)
107          */
108         private String userPassword;
109
110         /**
111          * User password repeated (unencrypted from web form)
112          */
113         private String userPasswordRepeat;
114
115         /**
116          * Default constructor
117          */
118         public PizzaAdminUserWebRequestBean () {
119                 // Try it
120                 try {
121                         // Get initial context
122                         Context context = new InitialContext();
123
124                         // Try to lookup
125                         this.userBean = (UserSessionBeanRemote) context.lookup("java:global/PizzaService-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
126                 } catch (final NamingException e) {
127                         // Throw again
128                         throw new FaceletException(e);
129                 }
130         }
131
132         @Override
133         public String addUser () {
134                 // Create new user instance
135                 User user = new LoginUser();
136
137                 // As the form cannot validate the data (required="true"), check it here
138                 if (this.getUserName() == null) {
139                         // Throw NPE
140                         throw new NullPointerException("userName is null"); //NOI18N
141                 } else if (this.getUserName().isEmpty()) {
142                         // Is empty
143                         throw new IllegalArgumentException("userName is null"); //NOI18N
144                 } else if (this.adminHelper.getContact() == null) {
145                         // No contact instance set, so test required fields: gender, first name and family name
146                         if (this.contactController.getGender() == null) {
147                                 // Throw NPE again
148                                 throw new NullPointerException("contactController.gender is null"); //NOI18N
149                         } else if (this.contactController.getFirstName() == null) {
150                                 // ... and again
151                                 throw new NullPointerException("contactController.firstName is null"); //NOI18N //NOI18N
152                         } else if (this.contactController.getFirstName().isEmpty()) {
153                                 // ... and again
154                                 throw new IllegalArgumentException("contactController.firstName is empty");
155                         } else if (this.contactController.getFamilyName() == null) {
156                                 // ... and again
157                                 throw new NullPointerException("contactController.familyName is null"); //NOI18N
158                         } else if (this.contactController.getFamilyName().isEmpty()) {
159                                 // ... and again
160                                 throw new IllegalArgumentException("contactController.familyName is empty"); //NOI18N //NOI18N
161                         } else if (this.contactController.getEmailAddress() == null) {
162                                 // ... and again
163                                 throw new NullPointerException("contactController.emailAddress is null");
164                         } else if (this.contactController.getEmailAddress().isEmpty()) {
165                                 // ... and again
166                                 throw new IllegalArgumentException("contactController.emailAddress is empty"); //NOI18N //NOI18N
167                         } else if (this.contactController.getEmailAddressRepeat() == null) {
168                                 // ... and again
169                                 throw new NullPointerException("contactController.emailAddressRepeat is null");
170                         } else if (this.contactController.getEmailAddressRepeat().isEmpty()) {
171                                 // ... and again
172                                 throw new IllegalArgumentException("contactController.emailAddressRepeat is empty"); //NOI18N //NOI18N
173                         } else if (!Objects.equals(this.contactController.getEmailAddress(), this.contactController.getEmailAddressRepeat())) {
174                                 // Is not same email address
175                                 throw new IllegalArgumentException("Both entered email addresses don't match.");
176                         }
177                 }
178
179                 // Set user name, CONFIRMED and INVISIBLE
180                 user.setUserName(this.getUserName());
181                 user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
182                 user.setUserProfileMode(ProfileMode.INVISIBLE);
183
184                 // Init instance
185                 Contact contact;
186
187                 // Is a contact instance in helper set?
188                 if (this.adminHelper.getContact() instanceof Contact) {
189                         // Then use it for contact linking
190                         contact = this.adminHelper.getContact();
191                 } else {
192                         // Create contact instance
193                         contact = this.contactController.createContactInstance();
194                 }
195
196                 // Set contact in user
197                 user.setUserContact(contact);
198
199                 // Init variable for password
200                 String password = null;
201
202                 // Is the user name or email address used already?
203                 // @TODO Add password length check
204                 if (this.userController.isUserNameRegistered(user)) {
205                         // User name is already used
206                         throw new FaceletException(new UserNameAlreadyRegisteredException(user));
207                 } else if ((this.adminHelper.getContact() == null) && (this.contactController.isEmailAddressRegistered(user.getUserContact()))) {
208                         // Email address is already used
209                         throw new FaceletException(new EmailAddressAlreadyRegisteredException(user));
210                 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
211                         // Empty password entered, then generate one
212                         password = UserUtils.createRandomPassword(PizzaUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
213                 } else if (!this.isSamePasswordEntered()) {
214                         // Both passwords don't match
215                         throw new FaceletException(new UserPasswordRepeatMismatchException(user));
216                 } else {
217                         // Both match, so get it from this bean
218                         password = this.getUserPassword();
219                 }
220
221                 // The password should not be null and at least 5 characters long
222                 assert (password != null) : "password is null"; //NOI18N
223                 assert (password.length() >= PizzaUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
224
225                 // Encrypt password and set it
226                 user.setUserEncryptedPassword(UserUtils.encryptPassword(password));
227
228                 // Init updated user instance
229                 User updatedUser = null;
230
231                 try {
232                         // Now, that all is set, call EJB
233                         if (this.adminHelper.getContact() instanceof Contact) {
234                                 // Link contact with this user
235                                 updatedUser = this.userBean.linkUser(user);
236                         } else {
237                                 // Add new contact
238                                 updatedUser = this.userBean.addUser(user);
239                         }
240                 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
241                         // Throw again
242                         throw new FaceletException(ex);
243                 }
244
245                 // Fire event
246                 this.addedUserEvent.fire(new AdminUserAddedEvent(updatedUser));
247
248                 // Clear contact instance
249                 this.contactController.clear();
250
251                 // Return to user list (for now)
252                 return "admin_list_user"; //NOI18N
253         }
254
255         @Override
256         public String changeUserData () {
257                 // Get user instance
258                 User user = this.adminHelper.getUser();
259
260                 // Null password means not setting it
261                 String encryptedPassword = null;
262
263                 // Check if user instance is in helper and valid
264                 if (null == user) {
265                         // Throw NPE
266                         throw new NullPointerException("adminHelper.user is null"); //NOI18N
267                 } else if (user.getUserId() == null) {
268                         // Throw NPE again
269                         throw new NullPointerException("adminHelper.user.userId is null"); //NOI18N //NOI18N
270                 } else if (user.getUserId() < 1) {
271                         // Invalid id
272                         throw new IllegalStateException(MessageFormat.format("adminHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N //NOI18N
273                 } else if (this.getUserName() == null) {
274                         // Not all required fields are set
275                         throw new NullPointerException("this.userName is null"); //NOI18N
276                 } else if (this.getUserName().isEmpty()) {
277                         // Not all required fields are set
278                         throw new IllegalArgumentException("this.userName is empty"); //NOI18N
279                 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
280                         // Not same password entered
281                         this.setUserPassword(null);
282                         this.setUserPasswordRepeat(null);
283
284                         // Throw exception
285                         throw new FaceletException("Not same password entered"); //NOI18N
286                 } else if (this.userBean.ifUserNameExists(this.getUserName())) {
287                         // User name already exists
288                         throw new FaceletException(new UserNameAlreadyRegisteredException(this.getUserName()));
289                 } else if (this.isSamePasswordEntered()) {
290                         // Same password entered, create container
291                         if (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword()))) {
292                                 // Same password entered
293                                 throw new FaceletException("Same password as stored entered."); //NOI18N
294                         }
295
296                         // Encrypt password
297                         encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
298                 }
299
300                 // Set user name
301                 user.setUserName(this.getUserName());
302
303                 // Is a password set?
304                 if (encryptedPassword != null) {
305                         // Set it as well
306                         user.setUserEncryptedPassword(encryptedPassword);
307                 }
308
309                 // Call EJB for updating user data
310                 User updatedUser = this.userBean.updateUserData(user);
311
312                 // Update list
313                 this.userController.updateList(updatedUser);
314
315                 // Fire event
316                 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
317
318                 // Return to user list (for now)
319                 return "admin_list_user"; //NOI18N
320         }
321
322         @Override
323         public String getUserName () {
324                 return this.userName;
325         }
326
327         @Override
328         public void setUserName (final String userName) {
329                 this.userName = userName;
330         }
331
332         @Override
333         public String getUserPassword () {
334                 return this.userPassword;
335         }
336
337         @Override
338         public void setUserPassword (final String userPassword) {
339                 this.userPassword = userPassword;
340         }
341
342         @Override
343         public String getUserPasswordRepeat () {
344                 return this.userPasswordRepeat;
345         }
346
347         @Override
348         public void setUserPasswordRepeat (final String userPasswordRepeat) {
349                 this.userPasswordRepeat = userPasswordRepeat;
350         }
351
352         /**
353          * Post-initialization of this class
354          */
355         @PostConstruct
356         public void init () {
357         }
358
359         /**
360          * Checks if same password is entered and that they are not empty.
361          * <p>
362          * @return Whether the same password was entered
363          */
364         private boolean isSamePasswordEntered () {
365                 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
366         }
367
368 }