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