]> git.mxchange.org Git - jjobs-war.git/blob - src/java/org/mxchange/jjobs/beans/user/JobsAdminUserWebRequestBean.java
Continued 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.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 @RequestScoped
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          * Regular user controller
83          */
84         @Inject
85         private JobsUserWebSessionController 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 JobsAdminUserWebRequestBean () {
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/jjobs-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(JobsUserWebSessionController.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() >= JobsUserWebSessionController.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 String getUserName () {
201                 return this.userName;
202         }
203
204         @Override
205         public void setUserName (final String userName) {
206                 this.userName = userName;
207         }
208
209         @Override
210         public String getUserPassword () {
211                 return this.userPassword;
212         }
213
214         @Override
215         public void setUserPassword (final String userPassword) {
216                 this.userPassword = userPassword;
217         }
218
219         @Override
220         public String getUserPasswordRepeat () {
221                 return this.userPasswordRepeat;
222         }
223
224         @Override
225         public void setUserPasswordRepeat (final String userPasswordRepeat) {
226                 this.userPasswordRepeat = userPasswordRepeat;
227         }
228
229         @Override
230         public boolean hasUsers () {
231                 return (!this.allUsers().isEmpty());
232         }
233
234         /**
235          * Post-initialization of this class
236          */
237         @PostConstruct
238         public void init () {
239                 // Initialize user list
240                 this.userList = this.userBean.allUsers();
241         }
242
243         @Override
244         public User lookupUserById (final Long userId) throws UserNotFoundException {
245                 // Parameter must be valid
246                 if (null == userId) {
247                         // Throw NPE
248                         throw new NullPointerException("userId is null"); //NOI18N
249                 } else if (userId < 1) {
250                         // Not valid
251                         throw new IllegalArgumentException(MessageFormat.format("userId={0} is not valid.", userId)); //NOI18N
252                 }
253
254                 // Init variable
255                 User user = null;
256
257                 // Try to lookup it in visible user list
258                 for (final Iterator<User> iterator = this.userList.iterator(); iterator.hasNext();) {
259                         // Get next user
260                         User next = iterator.next();
261
262                         // Is the user id found?
263                         if (Objects.equals(next.getUserId(), userId)) {
264                                 // Copy to other variable
265                                 user = next;
266                                 break;
267                         }
268                 }
269
270                 // Is it still null?
271                 if (null == user) {
272                         // Not visible for the current user
273                         throw new UserNotFoundException(userId);
274                 }
275
276                 // Return it
277                 return user;
278         }
279
280         /**
281          * Clears this bean
282          */
283         private void clear () {
284                 // Clear all
285                 this.setUserName(null);
286                 this.setUserPassword(null);
287                 this.setUserPasswordRepeat(null);
288         }
289
290         /**
291          * Checks if same password is entered and that they are not empty.
292          * <p>
293          * @return Whether the same password was entered
294          */
295         private boolean isSamePasswordEntered () {
296                 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
297         }
298
299 }