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