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