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