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