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