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