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