]> git.mxchange.org Git - jjobs-war.git/blob - src/java/org/mxchange/jjobs/beans/user/JobsAdminUserWebRequestBean.java
Added redirect outcome + updated jar(s)
[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.isSamePasswordEntered()) {
272                         // Same password entered, create container
273                         if (UserUtils.ifPasswordMatches(new UserLoginContainer(user, this.getUserPassword()))) {
274                                 // Same password entered
275                                 throw new FaceletException("Same password as stored entered."); //NOI18N
276                         }
277
278                         // Encrypt password
279                         encryptedPassword = UserUtils.encryptPassword(this.getUserPassword());
280                 }
281
282                 // Set user name
283                 user.setUserName(this.getUserName());
284
285                 // Is a password set?
286                 if (encryptedPassword != null) {
287                         // Set it as well
288                         user.setUserEncryptedPassword(encryptedPassword);
289                 }
290
291                 // Call EJB for updating user data
292                 User updatedUser = this.userBean.updateUserData(user);
293
294                 // Update list
295                 this.updateList(updatedUser);
296
297                 // Fire event
298                 this.updatedUserDataEvent.fire(new AdminUserDataUpdatedEvent(updatedUser));
299
300                 // Return to user list (for now)
301                 return "admin_list_user"; //NOI18N
302         }
303
304         @Override
305         public String getUserName () {
306                 return this.userName;
307         }
308
309         @Override
310         public void setUserName (final String userName) {
311                 this.userName = userName;
312         }
313
314         @Override
315         public String getUserPassword () {
316                 return this.userPassword;
317         }
318
319         @Override
320         public void setUserPassword (final String userPassword) {
321                 this.userPassword = userPassword;
322         }
323
324         @Override
325         public String getUserPasswordRepeat () {
326                 return this.userPasswordRepeat;
327         }
328
329         @Override
330         public void setUserPasswordRepeat (final String userPasswordRepeat) {
331                 this.userPasswordRepeat = userPasswordRepeat;
332         }
333
334         @Override
335         public boolean hasUsers () {
336                 return (!this.allUsers().isEmpty());
337         }
338
339         /**
340          * Post-initialization of this class
341          */
342         @PostConstruct
343         public void init () {
344                 // Initialize user list
345                 this.userList = this.userBean.allUsers();
346         }
347
348         @Override
349         public User lookupUserById (final Long userId) throws UserNotFoundException {
350                 // Parameter must be valid
351                 if (null == userId) {
352                         // Throw NPE
353                         throw new NullPointerException("userId is null"); //NOI18N
354                 } else if (userId < 1) {
355                         // Not valid
356                         throw new IllegalArgumentException(MessageFormat.format("userId={0} is not valid.", userId)); //NOI18N
357                 }
358
359                 // Init variable
360                 User user = null;
361
362                 // Try to lookup it in visible user list
363                 for (final Iterator<User> iterator = this.userList.iterator(); iterator.hasNext();) {
364                         // Get next user
365                         User next = iterator.next();
366
367                         // Is the user id found?
368                         if (Objects.equals(next.getUserId(), userId)) {
369                                 // Copy to other variable
370                                 user = next;
371                                 break;
372                         }
373                 }
374
375                 // Is it still null?
376                 if (null == user) {
377                         // Not visible for the current user
378                         throw new UserNotFoundException(userId);
379                 }
380
381                 // Return it
382                 return user;
383         }
384
385         /**
386          * Checks if same password is entered and that they are not empty.
387          * <p>
388          * @return Whether the same password was entered
389          */
390         private boolean isSamePasswordEntered () {
391                 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
392         }
393
394         /**
395          * Updates list with given user instance
396          * <p>
397          * @param user User instance
398          */
399         private void updateList (final User user) {
400                 // The user should be valid
401                 if (null == user) {
402                         // Throw NPE
403                         throw new NullPointerException("user is null"); //NOI18N
404                 } else if (user.getUserId() == null) {
405                         // ... again NPE
406                         throw new NullPointerException("user.userId is null"); //NOI18N
407                 } else if (user.getUserId() < 1) {
408                         // Invalid id
409                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is invalid", user.getUserId())); //NOI18N
410                 }
411
412                 // Get iterator
413                 Iterator<User> iterator = this.userList.iterator();
414
415                 // Look whole list
416                 while (iterator.hasNext()) {
417                         // Get next element
418                         User next = iterator.next();
419
420                         // Is the same user id?
421                         if (Objects.equals(user.getUserId(), next.getUserId())) {
422                                 // Found it, so remove it
423                                 this.userList.remove(next);
424                                 break;
425                         }
426                 }
427
428                 // Re-add item
429                 this.userList.add(user);
430         }
431
432 }