]> git.mxchange.org Git - jjobs-war.git/blob - src/java/org/mxchange/jjobs/beans/user/JobsAdminUserWebRequestBean.java
don't forget to clear helper contact instance. When a user/recruiter has been added...
[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.contact.JobsContactWebSessionController;
34 import org.mxchange.jjobs.beans.helper.JobsAdminWebRequestController;
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
52 /**
53  * A user bean (controller)
54  * <p>
55  * @author Roland Haeder<roland@mxchange.org>
56  */
57 @Named ("adminUserController")
58 @RequestScoped
59 public class JobsAdminUserWebRequestBean implements JobsAdminUserWebRequestController {
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          * Admin helper instance
75          */
76         @Inject
77         private JobsAdminWebRequestController adminHelper;
78
79         /**
80          * Regular contact controller
81          */
82         @Inject
83         private JobsContactWebSessionController 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 JobsUserWebSessionController userController;
102
103         /**
104          * Login bean (controller)
105          */
106         @Inject
107         private JobsUserLoginWebSessionController userLoginController;
108
109         /**
110          * User name
111          */
112         private String userName;
113
114         /**
115          * User password (unencrypted from web form)
116          */
117         private String userPassword;
118
119         /**
120          * User password repeated (unencrypted from web form)
121          */
122         private String userPasswordRepeat;
123
124         /**
125          * Default constructor
126          */
127         public JobsAdminUserWebRequestBean () {
128                 // Try it
129                 try {
130                         // Get initial context
131                         Context context = new InitialContext();
132
133                         // Try to lookup
134                         this.userBean = (UserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
135                 } catch (final NamingException e) {
136                         // Throw again
137                         throw new FaceletException(e);
138                 }
139         }
140
141         @Override
142         public String addUser () {
143                 // As the form cannot validate the data (required="true"), check it here
144                 if (this.getUserName() == null) {
145                         // Throw NPE
146                         throw new NullPointerException("userName is null"); //NOI18N
147                 } else if (this.getUserName().isEmpty()) {
148                         // Is empty
149                         throw new IllegalArgumentException("userName is null"); //NOI18N
150                 } else if (this.adminHelper.getContact() == null) {
151                         // No contact instance set, so test required fields: gender, first name and family name
152                         if (this.contactController.getGender() == null) {
153                                 // Throw NPE again
154                                 throw new NullPointerException("contactController.gender is null"); //NOI18N
155                         } else if (this.contactController.getFirstName() == null) {
156                                 // ... and again
157                                 throw new NullPointerException("contactController.firstName is null"); //NOI18N //NOI18N
158                         } else if (this.contactController.getFirstName().isEmpty()) {
159                                 // ... and again
160                                 throw new IllegalArgumentException("contactController.firstName is empty");
161                         } else if (this.contactController.getFamilyName() == null) {
162                                 // ... and again
163                                 throw new NullPointerException("contactController.familyName is null"); //NOI18N
164                         } else if (this.contactController.getFamilyName().isEmpty()) {
165                                 // ... and again
166                                 throw new IllegalArgumentException("contactController.familyName is empty"); //NOI18N //NOI18N
167                         } else if (this.contactController.getEmailAddress() == null) {
168                                 // ... and again
169                                 throw new NullPointerException("contactController.emailAddress is null");
170                         } else if (this.contactController.getEmailAddress().isEmpty()) {
171                                 // ... and again
172                                 throw new IllegalArgumentException("contactController.emailAddress is empty"); //NOI18N //NOI18N
173                         } else if (this.contactController.getEmailAddressRepeat() == null) {
174                                 // ... and again
175                                 throw new NullPointerException("contactController.emailAddressRepeat is null");
176                         } else if (this.contactController.getEmailAddressRepeat().isEmpty()) {
177                                 // ... and again
178                                 throw new IllegalArgumentException("contactController.emailAddressRepeat is empty"); //NOI18N //NOI18N
179                         } else if (!Objects.equals(this.contactController.getEmailAddress(), this.contactController.getEmailAddressRepeat())) {
180                                 // Is not same email address
181                                 throw new IllegalArgumentException("Both entered email addresses don't match.");
182                         }
183                 }
184
185                 // Create new user instance
186                 User user = new LoginUser();
187
188                 // Set user name, CONFIRMED and INVISIBLE
189                 user.setUserName(this.getUserName());
190                 user.setUserAccountStatus(UserAccountStatus.CONFIRMED);
191                 user.setUserProfileMode(ProfileMode.INVISIBLE);
192
193                 // Create contact instance
194                 Contact contact = this.contactController.createContactInstance();
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(JobsUserWebSessionController.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() >= JobsUserWebSessionController.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                 // Clear helper
246                 this.adminHelper.setContact(null);
247
248                 // Fire event
249                 this.addedUserEvent.fire(new AdminUserAddedEvent(updatedUser));
250
251                 // Return to user list (for now)
252                 return "admin_list_user"; //NOI18N
253         }
254
255         @Override
256         public void afterRegistrationEvent (@Observes final UserRegisteredEvent event) {
257                 // Trace message
258                 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterRegistration: event={0} - CALLED!", event)); //NOI18N
259
260                 // event should not be null
261                 if (null == event) {
262                         // Throw NPE
263                         throw new NullPointerException("event is null"); //NOI18N
264                 } else if (event.getRegisteredUser() == null) {
265                         // Throw NPE again
266                         throw new NullPointerException("event.user is null"); //NOI18N
267                 } else if (event.getRegisteredUser().getUserId() == null) {
268                         // userId is null
269                         throw new NullPointerException("event.user.userId is null"); //NOI18N
270                 } else if (event.getRegisteredUser().getUserId() < 1) {
271                         // Not avalid id
272                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
273                 }
274
275                 // Get user instance
276                 User registeredUser = event.getRegisteredUser();
277
278                 // Debug message
279                 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("UserWebBean:afterRegistration: registeredUser={0}", registeredUser)); //NOI18N
280
281                 // Clear all data
282                 this.clear();
283
284                 // Trace message
285                 //* NOISY-DEBUG: */ System.out.println("UserWebBean:afterRegistration: EXIT!"); //NOI18N
286         }
287
288         @Override
289         public String editUserData () {
290                 // Get user instance
291                 User user = this.adminHelper.getUser();
292
293                 // Null password means not setting it
294                 String encryptedPassword = null;
295
296                 // Check if user instance is in helper and valid
297                 if (null == user) {
298                         // Throw NPE
299                         throw new NullPointerException("adminHelper.user is null"); //NOI18N
300                 } else if (user.getUserId() == null) {
301                         // Throw NPE again
302                         throw new NullPointerException("adminHelper.user.userId is null"); //NOI18N //NOI18N
303                 } else if (user.getUserId() < 1) {
304                         // Invalid id
305                         throw new IllegalStateException(MessageFormat.format("adminHelper.user.userId={0} is invalid", user.getUserId())); //NOI18N
306                 } else if (this.getUserName() == null) {
307                         // Not all required fields are set
308                         throw new NullPointerException("this.userName is null"); //NOI18N
309                 } else if (this.getUserName().isEmpty()) {
310                         // Not all required fields are set
311                         throw new IllegalArgumentException("this.userName is empty"); //NOI18N
312                 } else if (((!this.getUserPassword().isEmpty()) || (!this.getUserPasswordRepeat().isEmpty())) && (!this.isSamePasswordEntered())) {
313                         // Not same password entered
314                         this.setUserPassword(null);
315                         this.setUserPasswordRepeat(null);
316
317                         // Throw exception
318                         throw new FaceletException("Not same password entered"); //NOI18N
319                 } else if (this.userBean.ifUserNameExists(this.getUserName())) {
320                         // User name already exists
321                         throw new FaceletException(new UserNameAlreadyRegisteredException(this.getUserName()));
322                 } else if (this.isSamePasswordEntered()) {
323                         // Same password entered, create container
324                         if (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword()))) {
325                                 // Same password entered
326                                 throw new FaceletException("Same password as stored entered."); //NOI18N
327                         }
328
329                         // Encrypt password
330                         encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
331                 }
332
333                 // Set user name
334                 user.setUserName(this.getUserName());
335
336                 // Is a password set?
337                 if (encryptedPassword != null) {
338                         // Set it as well
339                         user.setUserEncryptedPassword(encryptedPassword);
340                 }
341
342                 // Call EJB for updating user data
343                 User updatedUser = this.userBean.updateUserData(user);
344
345                 // Fire event
346                 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
347
348                 // Return to user list (for now)
349                 return "admin_list_user"; //NOI18N
350         }
351
352         @Override
353         public String getUserName () {
354                 return this.userName;
355         }
356
357         @Override
358         public void setUserName (final String userName) {
359                 this.userName = userName;
360         }
361
362         @Override
363         public String getUserPassword () {
364                 return this.userPassword;
365         }
366
367         @Override
368         public void setUserPassword (final String userPassword) {
369                 this.userPassword = userPassword;
370         }
371
372         @Override
373         public String getUserPasswordRepeat () {
374                 return this.userPasswordRepeat;
375         }
376
377         @Override
378         public void setUserPasswordRepeat (final String userPasswordRepeat) {
379                 this.userPasswordRepeat = userPasswordRepeat;
380         }
381
382         /**
383          * Post-initialization of this class
384          */
385         @PostConstruct
386         public void init () {
387         }
388
389         /**
390          * Clears this bean
391          */
392         private void clear () {
393                 // Clear all data
394                 // - other data
395                 this.setUserName(null);
396                 this.setUserPassword(null);
397                 this.setUserPasswordRepeat(null);
398         }
399
400         /**
401          * Checks if same password is entered and that they are not empty.
402          * <p>
403          * @return Whether the same password was entered
404          */
405         private boolean isSamePasswordEntered () {
406                 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
407         }
408
409 }