]> git.mxchange.org Git - pizzaservice-war.git/blob - src/java/org/mxchange/pizzaapplication/beans/user/PizzaAdminUserWebRequestBean.java
Continued:
[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.inject.Any;
28 import javax.faces.view.facelets.FaceletException;
29 import javax.inject.Inject;
30 import javax.inject.Named;
31 import javax.naming.Context;
32 import javax.naming.InitialContext;
33 import javax.naming.NamingException;
34 import org.mxchange.jcontacts.contact.Contact;
35 import org.mxchange.pizzaapplication.beans.contact.PizzaContactWebSessionController;
36 import org.mxchange.jusercore.events.user.AdminAddedUserEvent;
37 import org.mxchange.jusercore.events.user.AdminUserAddedEvent;
38 import org.mxchange.jusercore.exceptions.EmailAddressAlreadyRegisteredException;
39 import org.mxchange.jusercore.exceptions.UserNameAlreadyRegisteredException;
40 import org.mxchange.jusercore.exceptions.UserNotFoundException;
41 import org.mxchange.jusercore.exceptions.UserPasswordRepeatMismatchException;
42 import org.mxchange.jusercore.model.user.LoginUser;
43 import org.mxchange.jusercore.model.user.User;
44 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
45 import org.mxchange.jusercore.model.user.UserUtils;
46 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
47 import org.mxchange.jusercore.model.user.status.UserAccountStatus;
48
49 /**
50  * A user bean (controller)
51  * <p>
52  * @author Roland Haeder<roland@mxchange.org>
53  */
54 @Named ("adminUserController")
55 @RequestScoped
56 public class PizzaAdminUserWebRequestBean implements PizzaAdminUserWebRequestController {
57
58         /**
59          * Serial number
60          */
61         private static final long serialVersionUID = 542_145_347_916L;
62
63         /**
64          * An event fired when the administrator has added a new user
65          */
66         @Inject
67         @Any
68         private Event<AdminAddedUserEvent> addedUserEvent;
69
70         /**
71          * Regular contact controller
72          */
73         @Inject
74         private PizzaContactWebSessionController contactController;
75
76         /**
77          * Remote user bean
78          */
79         private final UserSessionBeanRemote userBean;
80
81         /**
82          * Regular user controller
83          */
84         @Inject
85         private PizzaUserWebSessionController userController;
86
87         /**
88          * A list of all user profiles
89          */
90         private List<User> userList;
91
92         /**
93          * User name
94          */
95         private String userName;
96
97         /**
98          * User password (unencrypted from web form)
99          */
100         private String userPassword;
101
102         /**
103          * User password repeated (unencrypted from web form)
104          */
105         private String userPasswordRepeat;
106
107         /**
108          * Default constructor
109          */
110         public PizzaAdminUserWebRequestBean () {
111                 // Try it
112                 try {
113                         // Get initial context
114                         Context context = new InitialContext();
115
116                         // Try to lookup
117                         this.userBean = (UserSessionBeanRemote) context.lookup("java:global/PizzaService-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
118                 } catch (final NamingException e) {
119                         // Throw again
120                         throw new FaceletException(e);
121                 }
122         }
123
124         @Override
125         public void addUser () {
126                 // Create new user instance
127                 User localUser = new LoginUser();
128
129                 // Set user name, CONFIRMED and INVISIBLE
130                 localUser.setUserName(this.getUserName());
131                 localUser.setUserAccountStatus(UserAccountStatus.CONFIRMED);
132                 localUser.setUserProfileMode(ProfileMode.INVISIBLE);
133
134                 // Create contact instance
135                 Contact contact = this.contactController.createContactInstance();
136
137                 // Set contact in user
138                 localUser.setUserContact(contact);
139
140                 // Init variable for password
141                 String password = null;
142
143                 // Is the user name or email address used already?
144                 // @TODO Add password length check
145                 if (this.userController.isUserNameRegistered(localUser)) {
146                         // User name is already used
147                         throw new FaceletException(new UserNameAlreadyRegisteredException(localUser));
148                 } else if (this.contactController.isEmailAddressRegistered(localUser.getUserContact())) {
149                         // Email address is already used
150                         throw new FaceletException(new EmailAddressAlreadyRegisteredException(localUser));
151                 } else if ((this.getUserPassword() == null && (this.getUserPasswordRepeat() == null)) || ((this.getUserPassword().isEmpty()) && (this.getUserPasswordRepeat().isEmpty()))) {
152                         // Empty password entered, then generate one
153                         password = UserUtils.createRandomPassword(PizzaUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
154                 } else if (!this.isSamePasswordEntered()) {
155                         // Both passwords don't match
156                         throw new FaceletException(new UserPasswordRepeatMismatchException(localUser));
157                 } else {
158                         // Both match, so get it from this bean
159                         password = this.getUserPassword();
160                 }
161
162                 // The password should not be null and at least 5 characters long
163                 assert (password != null) : "password is null"; //NOI18N
164                 assert (password.length() >= PizzaUserWebSessionController.MINIMUM_PASSWORD_LENGTH) : "Password is not long enough."; //NOI18N
165
166                 // Encrypt password and set it
167                 localUser.setUserEncryptedPassword(UserUtils.encryptPassword(password));
168
169                 // Init updated user instance
170                 User updatedUser = null;
171
172                 try {
173                         // Now, that all is set, call EJB
174                         updatedUser = this.userBean.addUser(localUser);
175                 } catch (final UserNameAlreadyRegisteredException | EmailAddressAlreadyRegisteredException ex) {
176                         // Throw again
177                         throw new FaceletException(ex);
178                 }
179
180                 // Fire event
181                 this.addedUserEvent.fire(new AdminUserAddedEvent(updatedUser));
182
183                 // Add user to local list
184                 this.userList.add(updatedUser);
185
186                 // Clear all
187                 this.clear();
188
189                 // Clear contact instance
190                 this.contactController.clear();
191         }
192
193         @Override
194         public List<User> allUsers () {
195                 // Return it
196                 return Collections.unmodifiableList(this.userList);
197         }
198
199         @Override
200         public void editUserData () {
201                 throw new UnsupportedOperationException("Not supported yet."); //NOI18N
202         }
203
204         @Override
205         public String getUserName () {
206                 return this.userName;
207         }
208
209         @Override
210         public void setUserName (final String userName) {
211                 this.userName = userName;
212         }
213
214         @Override
215         public String getUserPassword () {
216                 return this.userPassword;
217         }
218
219         @Override
220         public void setUserPassword (final String userPassword) {
221                 this.userPassword = userPassword;
222         }
223
224         @Override
225         public String getUserPasswordRepeat () {
226                 return this.userPasswordRepeat;
227         }
228
229         @Override
230         public void setUserPasswordRepeat (final String userPasswordRepeat) {
231                 this.userPasswordRepeat = userPasswordRepeat;
232         }
233
234         @Override
235         public boolean hasUsers () {
236                 return (!this.allUsers().isEmpty());
237         }
238
239         /**
240          * Post-initialization of this class
241          */
242         @PostConstruct
243         public void init () {
244                 // Initialize user list
245                 this.userList = this.userBean.allUsers();
246         }
247
248         @Override
249         public User lookupUserById (final Long userId) throws UserNotFoundException {
250                 // Parameter must be valid
251                 if (null == userId) {
252                         // Throw NPE
253                         throw new NullPointerException("userId is null"); //NOI18N
254                 } else if (userId < 1) {
255                         // Not valid
256                         throw new IllegalArgumentException(MessageFormat.format("userId={0} is not valid.", userId)); //NOI18N
257                 }
258
259                 // Init variable
260                 User user = null;
261
262                 // Try to lookup it in visible user list
263                 for (final Iterator<User> iterator = this.userList.iterator(); iterator.hasNext();) {
264                         // Get next user
265                         User next = iterator.next();
266
267                         // Is the user id found?
268                         if (Objects.equals(next.getUserId(), userId)) {
269                                 // Copy to other variable
270                                 user = next;
271                                 break;
272                         }
273                 }
274
275                 // Is it still null?
276                 if (null == user) {
277                         // Not visible for the current user
278                         throw new UserNotFoundException(userId);
279                 }
280
281                 // Return it
282                 return user;
283         }
284
285         /**
286          * Clears this bean
287          */
288         private void clear () {
289                 // Clear all
290                 this.setUserName(null);
291                 this.setUserPassword(null);
292                 this.setUserPasswordRepeat(null);
293         }
294
295         /**
296          * Checks if same password is entered and that they are not empty.
297          * <p>
298          * @return Whether the same password was entered
299          */
300         private boolean isSamePasswordEntered () {
301                 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
302         }
303
304 }