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