]> git.mxchange.org Git - jjobs-war.git/blob - src/java/org/mxchange/jjobs/beans/user/JobsUserWebSessionBean.java
Please cherry-pick:
[jjobs-war.git] / src / java / org / mxchange / jjobs / beans / user / JobsUserWebSessionBean.java
1 /*
2  * Copyright (C) 2016, 2017 Roland Häder
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.Iterator;
21 import java.util.List;
22 import java.util.Objects;
23 import javax.annotation.PostConstruct;
24 import javax.enterprise.context.SessionScoped;
25 import javax.enterprise.event.Event;
26 import javax.enterprise.event.Observes;
27 import javax.enterprise.inject.Any;
28 import javax.faces.context.FacesContext;
29 import javax.faces.view.facelets.FaceletException;
30 import javax.inject.Inject;
31 import javax.inject.Named;
32 import javax.naming.Context;
33 import javax.naming.InitialContext;
34 import javax.naming.NamingException;
35 import org.mxchange.jcontacts.contact.Contact;
36 import org.mxchange.jjobs.beans.BaseJobsController;
37 import org.mxchange.jjobs.beans.contact.JobsContactWebSessionController;
38 import org.mxchange.jjobs.beans.features.JobsFeaturesWebApplicationController;
39 import org.mxchange.jjobs.beans.localization.JobsLocalizationSessionController;
40 import org.mxchange.jjobs.beans.login.user.JobsUserLoginWebSessionController;
41 import org.mxchange.jusercore.events.confirmation.ObservableUserConfirmedAccountEvent;
42 import org.mxchange.jusercore.events.login.ObservableUserLoggedInEvent;
43 import org.mxchange.jusercore.events.registration.ObservableUserRegisteredEvent;
44 import org.mxchange.jusercore.events.user.add.ObservableAdminAddedUserEvent;
45 import org.mxchange.jusercore.events.user.delete.ObservableAdminDeletedUserEvent;
46 import org.mxchange.jusercore.events.user.linked.ObservableAdminLinkedUserEvent;
47 import org.mxchange.jusercore.events.user.locked.ObservableAdminLockedUserEvent;
48 import org.mxchange.jusercore.events.user.password_change.ObservableUpdatedUserPasswordEvent;
49 import org.mxchange.jusercore.events.user.unlocked.ObservableAdminUnlockedUserEvent;
50 import org.mxchange.jusercore.events.user.update.ObservableAdminUpdatedUserDataEvent;
51 import org.mxchange.jusercore.events.user.update.ObservableUpdatedUserPersonalDataEvent;
52 import org.mxchange.jusercore.events.user.update.UpdatedUserPersonalDataEvent;
53 import org.mxchange.jusercore.exceptions.UserEmailAddressNotFoundException;
54 import org.mxchange.jusercore.exceptions.UserNotFoundException;
55 import org.mxchange.jusercore.exceptions.UserPasswordMismatchException;
56 import org.mxchange.jusercore.model.user.LoginUser;
57 import org.mxchange.jusercore.model.user.User;
58 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
59 import org.mxchange.jusercore.model.user.UserUtils;
60 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
61
62 /**
63  * A user controller (bean)
64  * <p>
65  * @author Roland Häder<roland@mxchange.org>
66  */
67 @Named ("userController")
68 @SessionScoped
69 public class JobsUserWebSessionBean extends BaseJobsController implements JobsUserWebSessionController {
70
71         /**
72          * Serial number
73          */
74         private static final long serialVersionUID = 542_145_347_916L;
75
76         /**
77          * General contact controller
78          */
79         @Inject
80         private JobsContactWebSessionController contactController;
81
82         /**
83          * Features controller
84          */
85         @Inject
86         private JobsFeaturesWebApplicationController featureController;
87
88         /**
89          * Localization controller
90          */
91         @Inject
92         private JobsLocalizationSessionController localizationController;
93
94         /**
95          * Event being fired when user updated personal data
96          */
97         @Inject
98         @Any
99         private Event<ObservableUpdatedUserPersonalDataEvent> updatedPersonalDataEvent;
100
101         /**
102          * Remote user bean
103          */
104         private UserSessionBeanRemote userBean;
105
106         /**
107          * User id
108          */
109         private Long userId;
110
111         /**
112          * A list of all user profiles
113          */
114         private List<User> userList;
115
116         /**
117          * Login controller (bean)
118          */
119         @Inject
120         private JobsUserLoginWebSessionController userLoginController;
121
122         /**
123          * User name
124          */
125         private String userName;
126
127         /**
128          * User name list
129          */
130         private List<String> userNameList;
131
132         /**
133          * User password (clear-text from web form)
134          */
135         private String userPassword;
136
137         /**
138          * User password repeated (clear-text from web form)
139          */
140         private String userPasswordRepeat;
141
142         /**
143          * Whether the user wants a public profile
144          */
145         private ProfileMode userProfileMode;
146
147         /**
148          * A list of all public user profiles
149          * <p>
150          * @TODO Hmm, makes that sense? Having visible user list in current
151          * (session-scoped) user's visible user list?
152          */
153         private List<User> visibleUserList;
154
155         /**
156          * Default constructor
157          */
158         public JobsUserWebSessionBean () {
159                 // Call super constructor
160                 super();
161         }
162
163         /**
164          * Event observer for newly added users by administrator
165          * <p>
166          * @param event Event being fired
167          */
168         public void afterAdminAddedUserEvent (@Observes final ObservableAdminAddedUserEvent event) {
169                 // event should not be null
170                 if (null == event) {
171                         // Throw NPE
172                         throw new NullPointerException("event is null"); //NOI18N
173                 } else if (event.getAddedUser() == null) {
174                         // Throw NPE again
175                         throw new NullPointerException("event.addedUser is null"); //NOI18N
176                 } else if (event.getAddedUser().getUserId() == null) {
177                         // userId is null
178                         throw new NullPointerException("event.addedUser.userId is null"); //NOI18N
179                 } else if (event.getAddedUser().getUserId() < 1) {
180                         // Not avalid id
181                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getAddedUser(), event.getAddedUser().getUserId())); //NOI18N
182                 }
183
184                 // Update user list
185                 this.updateList(event.getAddedUser());
186
187                 // Clear all data
188                 this.clear();
189
190                 // Set user id again
191                 this.setUserId(event.getAddedUser().getUserId());
192         }
193
194         /**
195          * Event observer for deleted user accounts (by administrator)
196          * <p>
197          * @param event Event being fired
198          */
199         public void afterAdminDeletedUserEvent (final ObservableAdminDeletedUserEvent event) {
200                 // event should not be null
201                 if (null == event) {
202                         // Throw NPE
203                         throw new NullPointerException("event is null"); //NOI18N
204                 } else if (event.getDeletedUser() == null) {
205                         // Throw NPE again
206                         throw new NullPointerException("event.deletedUser is null"); //NOI18N
207                 } else if (event.getDeletedUser().getUserId() == null) {
208                         // userId is null
209                         throw new NullPointerException("event.deletedUser.userId is null"); //NOI18N
210                 } else if (event.getDeletedUser().getUserId() < 1) {
211                         // Not avalid id
212                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getDeletedUser(), event.getDeletedUser().getUserId())); //NOI18N
213                 }
214
215                 // Update user list
216                 this.removeFromList(event.getDeletedUser());
217
218                 // Clear all data
219                 this.clear();
220         }
221
222         /**
223          * Event observer for linked users with existing contact data
224          * <p>
225          * @param event Event being fired
226          */
227         public void afterAdminLinkedUserEvent (@Observes final ObservableAdminLinkedUserEvent event) {
228                 // event should not be null
229                 if (null == event) {
230                         // Throw NPE
231                         throw new NullPointerException("event is null"); //NOI18N
232                 } else if (event.getLinkedUser() == null) {
233                         // Throw NPE again
234                         throw new NullPointerException("event.linkedUser is null"); //NOI18N
235                 } else if (event.getLinkedUser().getUserId() == null) {
236                         // userId is null
237                         throw new NullPointerException("event.linkedUser.userId is null"); //NOI18N
238                 } else if (event.getLinkedUser().getUserId() < 1) {
239                         // Not avalid id
240                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getLinkedUser(), event.getLinkedUser().getUserId())); //NOI18N
241                 }
242
243                 // Update user list
244                 this.updateList(event.getLinkedUser());
245
246                 // Clear all data
247                 this.clear();
248
249                 // Set user id again
250                 this.setUserId(event.getLinkedUser().getUserId());
251         }
252
253         /**
254          * Event observer for locked users
255          * <p>
256          * @param event Event being fired
257          */
258         public void afterAdminLockedUserEvent (@Observes final ObservableAdminLockedUserEvent event) {
259                 // event should not be null
260                 if (null == event) {
261                         // Throw NPE
262                         throw new NullPointerException("event is null"); //NOI18N
263                 } else if (event.getLockedUser() == null) {
264                         // Throw NPE again
265                         throw new NullPointerException("event.lockedUser is null"); //NOI18N
266                 } else if (event.getLockedUser().getUserId() == null) {
267                         // userId is null
268                         throw new NullPointerException("event.lockedUser.userId is null"); //NOI18N
269                 } else if (event.getLockedUser().getUserId() < 1) {
270                         // Not avalid id
271                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getLockedUser(), event.getLockedUser().getUserId())); //NOI18N
272                 }
273
274                 // Update user list
275                 this.updateList(event.getLockedUser());
276         }
277
278         /**
279          * Event observer for unlocked users
280          * <p>
281          * @param event Event being fired
282          */
283         public void afterAdminUnlockedUserEvent (@Observes final ObservableAdminUnlockedUserEvent event) {
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.getUnlockedUser() == null) {
289                         // Throw NPE again
290                         throw new NullPointerException("event.unlockedUser is null"); //NOI18N
291                 } else if (event.getUnlockedUser().getUserId() == null) {
292                         // userId is null
293                         throw new NullPointerException("event.unlockedUser.userId is null"); //NOI18N
294                 } else if (event.getUnlockedUser().getUserId() < 1) {
295                         // Not avalid id
296                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getUnlockedUser(), event.getUnlockedUser().getUserId())); //NOI18N
297                 }
298
299                 // Update user list
300                 this.updateList(event.getUnlockedUser());
301         }
302
303         /**
304          * Event observer for updated user data by administrator
305          * <p>
306          * @param event Event being updated
307          */
308         public void afterAdminUpdatedUserDataEvent (@Observes final ObservableAdminUpdatedUserDataEvent event) {
309                 // event should not be null
310                 if (null == event) {
311                         // Throw NPE
312                         throw new NullPointerException("event is null"); //NOI18N
313                 } else if (event.getUpdatedUser() == null) {
314                         // Throw NPE again
315                         throw new NullPointerException("event.updatedUser is null"); //NOI18N
316                 } else if (event.getUpdatedUser().getUserId() == null) {
317                         // userId is null
318                         throw new NullPointerException("event.updatedUser.userId is null"); //NOI18N
319                 } else if (event.getUpdatedUser().getUserId() < 1) {
320                         // Not avalid id
321                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getUpdatedUser(), event.getUpdatedUser().getUserId())); //NOI18N
322                 }
323
324                 // Update user list
325                 this.updateList(event.getUpdatedUser());
326
327                 // Clear all data
328                 this.clear();
329         }
330
331         /**
332          * Event observer when user confirmed account.
333          * <p>
334          * @param event Event being fired
335          */
336         public void afterUserConfirmedAccountEvent (@Observes final ObservableUserConfirmedAccountEvent event) {
337                 // event should not be null
338                 if (null == event) {
339                         // Throw NPE
340                         throw new NullPointerException("event is null"); //NOI18N
341                 } else if (event.getConfirmedUser() == null) {
342                         // Throw NPE again
343                         throw new NullPointerException("event.confirmedUser is null"); //NOI18N
344                 } else if (event.getConfirmedUser().getUserId() == null) {
345                         // userId is null
346                         throw new NullPointerException("event.confirmedUser.userId is null"); //NOI18N
347                 } else if (event.getConfirmedUser().getUserId() < 1) {
348                         // Not avalid id
349                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getConfirmedUser(), event.getConfirmedUser().getUserId())); //NOI18N
350                 }
351
352                 // Update user list
353                 this.updateList(event.getConfirmedUser());
354         }
355
356         /**
357          * Event observer for logged-in user
358          * <p>
359          * @param event Event instance
360          */
361         public void afterUserLoginEvent (@Observes final ObservableUserLoggedInEvent event) {
362                 // event should not be null
363                 if (null == event) {
364                         // Throw NPE
365                         throw new NullPointerException("event is null"); //NOI18N
366                 } else if (event.getLoggedInUser() == null) {
367                         // Throw NPE again
368                         throw new NullPointerException("event.registeredUser is null"); //NOI18N
369                 } else if (event.getLoggedInUser().getUserId() == null) {
370                         // userId is null
371                         throw new NullPointerException("event.registeredUser.userId is null"); //NOI18N
372                 } else if (event.getLoggedInUser().getUserId() < 1) {
373                         // Not avalid id
374                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getLoggedInUser(), event.getLoggedInUser().getUserId())); //NOI18N
375                 }
376
377                 // "Cache" user instance
378                 User loggedInUser = event.getLoggedInUser();
379
380                 // Copy all data to this bean
381                 this.copyUser(loggedInUser);
382
383                 // Is the user visible?
384                 if (Objects.equals(loggedInUser.getUserProfileMode(), ProfileMode.PUBLIC)) {
385                         // Yes, then add user
386                         this.visibleUserList.add(loggedInUser);
387                 }
388         }
389
390         /**
391          * Event observer for new user registrations
392          * <p>
393          * @param event User registration event
394          */
395         public void afterUserRegistrationEvent (@Observes final ObservableUserRegisteredEvent event) {
396                 // event should not be null
397                 if (null == event) {
398                         // Throw NPE
399                         throw new NullPointerException("event is null"); //NOI18N
400                 } else if (event.getRegisteredUser() == null) {
401                         // Throw NPE again
402                         throw new NullPointerException("event.registeredUser is null"); //NOI18N
403                 } else if (event.getRegisteredUser().getUserId() == null) {
404                         // userId is null
405                         throw new NullPointerException("event.registeredUser.userId is null"); //NOI18N
406                 } else if (event.getRegisteredUser().getUserId() < 1) {
407                         // Not avalid id
408                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
409                 }
410
411                 // Get user instance
412                 User registeredUser = event.getRegisteredUser();
413
414                 // Copy all data from registered->user
415                 this.copyUser(registeredUser);
416
417                 // Clear all data
418                 this.clear();
419
420                 // Update user list
421                 this.updateList(registeredUser);
422
423                 // Add user name
424                 this.addUserName(registeredUser);
425
426                 // Is the account public?
427                 if (Objects.equals(registeredUser.getUserProfileMode(), ProfileMode.PUBLIC)) {
428                         // Also add it to this list
429                         this.visibleUserList.add(registeredUser);
430                 }
431
432                 // Set user id again
433                 this.setUserId(registeredUser.getUserId());
434         }
435
436         /**
437          * Method being call after user's password has been updated (and history
438          * entry has been created).
439          * <p>
440          * @param event Event being observed
441          */
442         public void afterUserUpdatedPasswordEvent (@Observes final ObservableUpdatedUserPasswordEvent event) {
443                 // Check parameter
444                 if (null == event) {
445                         // Throw NPE
446                         throw new NullPointerException("event is null"); //NOI18N
447                 } else if (event.getPasswordHistory() == null) {
448                         // Throw NPE again
449                         throw new NullPointerException("event.passwordHistory is null"); //NOI18N
450                 } else if (event.getPasswordHistory().getUserPasswordHistoryId() == null) {
451                         // ... and again
452                         throw new NullPointerException("event.passwordHistory.userPasswordHistoryId is null"); //NOI18N
453                 } else if (event.getPasswordHistory().getUserPasswordHistoryId() < 1) {
454                         // Invalid value
455                         throw new IllegalArgumentException(MessageFormat.format("event.passwordHistory.userPasswordHistoryId={0} is in valid", event.getPasswordHistory().getUserPasswordHistoryId())); //NOI18N
456                 }
457
458                 // Update user list
459                 this.updateList(event.getPasswordHistory().getUserPasswordHistoryUser());
460         }
461
462         /**
463          * Listens to fired event when user updated personal data
464          * <p>
465          * @param event Event being fired
466          */
467         public void afterUserUpdatedPersonalDataEvent (@Observes final ObservableUpdatedUserPersonalDataEvent event) {
468                 // Check parameter
469                 if (null == event) {
470                         // Throw NPE
471                         throw new NullPointerException("event is null"); //NOI18N
472                 } else if (event.getUpdatedUser() == null) {
473                         // Throw NPE again
474                         throw new NullPointerException("event.updatedUser is null"); //NOI18N
475                 } else if (event.getUpdatedUser().getUserId() == null) {
476                         // ... and again
477                         throw new NullPointerException("event.updatedUser.userId is null"); //NOI18N
478                 } else if (event.getUpdatedUser().getUserId() < 1) {
479                         // Invalid value
480                         throw new IllegalArgumentException(MessageFormat.format("event.updatedUser.userId={0} is in valid", event.getUpdatedUser().getUserId())); //NOI18N
481                 }
482
483                 // Update user list
484                 this.updateList(event.getUpdatedUser());
485         }
486
487         @Override
488         @SuppressWarnings ("ReturnOfCollectionOrArrayField")
489         public List<User> allUsers () {
490                 // Return it
491                 return this.userList;
492         }
493
494         @Override
495         @SuppressWarnings ("ReturnOfCollectionOrArrayField")
496         public List<User> allVisibleUsers () {
497                 // Return it
498                 return this.visibleUserList;
499         }
500
501         @Override
502         public User createUserInstance (final boolean createContactData) {
503                 // Trace message
504                 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("{0}.createUserInstance: CALLED!", this.getClass().getSimpleName()));
505
506                 // Required personal data must be set
507                 assert (this.isRequiredPersonalDataSet()) : "not all personal data is set"; //NOI18N
508
509                 // Create new user instance
510                 User user = new LoginUser();
511
512                 // Is user name required?
513                 if (!this.isUserNameRequired()) {
514                         // Generate pseudo-random user name
515                         String randomName = this.userBean.generateRandomUserName();
516
517                         // Set it and inivisible profile
518                         this.setUserName(randomName);
519                         this.setUserProfileMode(ProfileMode.INVISIBLE);
520
521                         // Generate random password
522                         String randomPassword = UserUtils.createRandomPassword(JobsUserWebSessionController.MINIMUM_PASSWORD_LENGTH);
523
524                         // Set random password
525                         this.setUserPassword(randomPassword);
526                         this.setUserPasswordRepeat(randomPassword);
527                 }
528
529                 // Set user name profile mode and locale
530                 user.setUserName(this.getUserName());
531                 user.setUserProfileMode(this.getUserProfileMode());
532                 user.setUserLocale(this.localizationController.getLocale());
533
534                 // Is multiple registration page
535                 if ((createContactData) || (!this.featureController.isFeatureEnabled("user_register_multiple_page"))) { //NOI18N
536                         // Create contact instance
537                         Contact contact = this.contactController.createContactInstance();
538
539                         // Debug message
540                         //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("{0}.createUserInstance: contact={1}", this.getClass().getSimpleName(), contact));
541                         // Set contact in user
542                         user.setUserContact(contact);
543                 }
544
545                 // Trace message
546                 //* NOISY-DEBUG: */ System.out.println(MessageFormat.format("{0}.createUserInstance: user={1} - EXIT!", this.getClass().getSimpleName(), user));
547                 // Return it
548                 return user;
549         }
550
551         @Override
552         public User createUserLogin () {
553                 // Trace message
554                 //* NOISY-DEBUG */ System.out.println(MessageFormat.format("{0}.createUserLogin: CALLED!", this.getClass().getSimpleName()));
555
556                 // Is all data set?
557                 if (this.getUserName() == null) {
558                         // Throw NPE
559                         throw new NullPointerException("userName is null"); //NOI18N
560                 } else if (this.getUserName().isEmpty()) {
561                         // Is empty
562                         throw new IllegalStateException("userName is empty."); //NOI18N
563                 }
564
565                 // Create new user instance
566                 User user = new LoginUser();
567
568                 // Update all data ...
569                 user.setUserName(this.getUserName());
570
571                 // Trace message
572                 //* NOISY-DEBUG */ System.out.println(MessageFormat.format("{0}.createUserLogin: user={1} - EXIT!", this.getClass().getSimpleName(), user));
573                 // Return the new instance
574                 return user;
575         }
576
577         @Override
578         public String doChangePersonalData () {
579                 // This method shall only be called if the user is logged-in
580                 if (!this.userLoginController.isUserLoggedIn()) {
581                         // Not logged-in
582                         throw new IllegalStateException("User is not logged-in"); //NOI18N
583                 } else if (!this.isRequiredChangePersonalDataSet()) {
584                         // Not all required fields are set
585                         throw new FaceletException("Not all required fields are set."); //NOI18N
586                 } else if (!this.userLoginController.ifCurrentPasswordMatches()) {
587                         // Password not matching
588                         throw new FaceletException(new UserPasswordMismatchException(this.userLoginController.getLoggedInUser()));
589                 } else if (!this.featureController.isFeatureEnabled("change_user_personal_data")) {
590                         // Editing is not allowed
591                         throw new IllegalStateException("User tried to edit personal data."); //NOI18N
592                 }
593
594                 // Get user instance
595                 User user = this.userLoginController.getLoggedInUser();
596
597                 // Copy contact data to contact instance
598                 this.contactController.updateContactDataFromController(user.getUserContact());
599
600                 // It should be there, so run some tests on it
601                 assert (user instanceof User) : "Instance userLoginController.loggedInUser is null"; //NOI18N
602                 assert (user.getUserId() instanceof Long) : "Instance userLoginController.loggedInUser.userId is null"; //NOI18N
603                 assert (user.getUserId() > 0) : MessageFormat.format("userLoginController.loggedInUser.userId={0} is invalid", user.getUserId()); //NOI18N
604                 assert (user.getUserContact() instanceof Contact) : "Instance userLoginController.loggedInUser.userContact is null"; //NOI18N
605                 assert (user.getUserContact().getContactId() instanceof Long) : "Instance userLoginController.userContact.contactId is null"; //NOI18N
606                 assert (user.getUserContact().getContactId() > 0) : MessageFormat.format("Instance userLoginController.userContact.contactId={0} is invalid", user.getUserContact().getContactId()); //NOI18N
607
608                 // Update all fields
609                 user.setUserProfileMode(this.getUserProfileMode());
610
611                 // Send it to the EJB
612                 User updatedUser = this.userBean.updateUserPersonalData(user);
613
614                 // Fire event
615                 this.updatedPersonalDataEvent.fire(new UpdatedUserPersonalDataEvent(updatedUser));
616
617                 // All fine
618                 return "user_contact_data_saved"; //NOI18N
619         }
620
621         @Override
622         public Long getUserId () {
623                 return this.userId;
624         }
625
626         @Override
627         public void setUserId (final Long userId) {
628                 this.userId = userId;
629         }
630
631         @Override
632         public String getUserName () {
633                 return this.userName;
634         }
635
636         @Override
637         public void setUserName (final String userName) {
638                 this.userName = userName;
639         }
640
641         @Override
642         public String getUserPassword () {
643                 return this.userPassword;
644         }
645
646         @Override
647         public void setUserPassword (final String userPassword) {
648                 this.userPassword = userPassword;
649         }
650
651         @Override
652         public String getUserPasswordRepeat () {
653                 return this.userPasswordRepeat;
654         }
655
656         @Override
657         public void setUserPasswordRepeat (final String userPasswordRepeat) {
658                 this.userPasswordRepeat = userPasswordRepeat;
659         }
660
661         @Override
662         public ProfileMode getUserProfileMode () {
663                 return this.userProfileMode;
664         }
665
666         @Override
667         public void setUserProfileMode (final ProfileMode userProfileMode) {
668                 this.userProfileMode = userProfileMode;
669         }
670
671         @Override
672         public boolean ifBothPasswordsEmptyAllowed () {
673                 // Check feature first
674                 return ((this.featureController.isFeatureEnabled("allow_user_registration_empty_password")) &&
675                                 ((this.getUserPassword() == null) || (this.getUserPassword().isEmpty())) &&
676                                 ((this.getUserPasswordRepeat() == null) || (this.getUserPasswordRepeat().isEmpty())));
677         }
678
679         /**
680          * Post-initialization of this class
681          */
682         @PostConstruct
683         public void init () {
684                 // Try it
685                 try {
686                         // Get initial context
687                         Context context = new InitialContext();
688
689                         // Try to lookup
690                         this.userBean = (UserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
691                 } catch (final NamingException e) {
692                         // Throw again
693                         throw new FaceletException(e);
694                 }
695
696                 // Initialize user list
697                 this.userList = this.userBean.allUsers();
698
699                 // Get full user name list for reducing EJB calls
700                 this.userNameList = this.userBean.getUserNameList();
701
702                 // Is the user logged-in?
703                 if (this.userLoginController.isUserLoggedIn()) {
704                         // Is logged-in, so load also users visible to memebers
705                         this.visibleUserList = this.userBean.allMemberPublicVisibleUsers();
706                 } else {
707                         // Initialize user list
708                         this.visibleUserList = this.userBean.allPublicUsers();
709                 }
710         }
711
712         @Override
713         public boolean isContactFound (final Contact contact) {
714                 // The contact must be valid
715                 if (null == contact) {
716                         // Throw NPE
717                         throw new NullPointerException("contact is null"); //NOI18N
718                 } else if (contact.getContactId() == null) {
719                         // Throw again ...
720                         throw new NullPointerException("contact.contactId is null"); //NOI18N
721                 } else if (contact.getContactId() < 1) {
722                         // Not valid
723                         throw new IllegalArgumentException(MessageFormat.format("contact.contactId={0} is not valid", contact.getContactId())); //NOI18N
724                 }
725
726                 // Default is not found
727                 boolean isFound = false;
728
729                 // Get iterator
730                 Iterator<User> iterator = this.allUsers().iterator();
731
732                 // Loop through all entries
733                 while (iterator.hasNext()) {
734                         // Get user
735                         User next = iterator.next();
736
737                         // Compare both objects
738                         if (Objects.equals(contact, next.getUserContact())) {
739                                 // Found it
740                                 isFound = true;
741                                 break;
742                         }
743                 }
744
745                 // Return status
746                 return isFound;
747         }
748
749         @Override
750         public boolean isPublicUserProfileEnabled () {
751                 // Get context parameter
752                 String contextParameter = FacesContext.getCurrentInstance().getExternalContext().getInitParameter("is_public_profile_enabled"); //NOI18N
753
754                 // Is it set?
755                 boolean isEnabled = ((contextParameter instanceof String) && (contextParameter.toLowerCase().equals("true"))); //NOI18N
756
757                 // This requires user names being enabled, too.
758                 if ((isEnabled) && (!this.isUserNameRequired())) {
759                         // Not valid state, users must be able to modify their profile, especially when it is public
760                         throw new IllegalStateException("Public user profiles are enabled but user name requirement is disabled, this is not possible."); //NOI18N
761                 }
762
763                 // Return value
764                 return isEnabled;
765         }
766
767         @Override
768         public boolean isRequiredChangePersonalDataSet () {
769                 return ((this.getUserProfileMode() != null) &&
770                                 (this.getUserName() != null) && (!this.getUserName().isEmpty()) &&
771                                 (this.contactController.isRequiredChangePersonalDataSet()));
772         }
773
774         @Override
775         public boolean isRequiredPersonalDataSet () {
776                 if (this.featureController.isFeatureEnabled("user_register_multiple_page")) { //NOI18N
777                         // Multiple registration page
778                         return this.contactController.isRequiredPersonalDataSet();
779                 } else {
780                         // Single registration page
781                         return (((this.getUserName() != null) || (!this.isUserNameRequired())) &&
782                                         (this.getUserProfileMode() != null) &&
783                                         (this.contactController.isRequiredPersonalDataSet()) &&
784                                         (this.getUserPassword() != null) &&
785                                         (this.getUserPasswordRepeat() != null));
786                 }
787         }
788
789         @Override
790         public boolean isSamePasswordEntered () {
791                 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
792         }
793
794         @Override
795         public boolean isUserIdEmpty () {
796                 return ((this.getUserId() == null) || (this.getUserId() == 0));
797         }
798
799         @Override
800         public boolean isUserNameRegistered (final User user) {
801                 return ((this.userNameList instanceof List) && (this.userNameList.contains(user.getUserName())));
802         }
803
804         @Override
805         public boolean isUserNameRequired () {
806                 // Get context parameter
807                 String contextParameter = FacesContext.getCurrentInstance().getExternalContext().getInitParameter("is_user_name_required"); //NOI18N
808
809                 // Is it set?
810                 boolean isRequired = ((contextParameter instanceof String) && (contextParameter.toLowerCase().equals("true"))); //NOI18N
811
812                 // Return value
813                 return isRequired;
814         }
815
816         @Override
817         public boolean isVisibleUserFound () {
818                 return ((this.visibleUserList instanceof List) && (this.visibleUserList.size() > 0));
819         }
820
821         @Override
822         public User lookupUserByEmailAddress (final String emailAddress) throws UserEmailAddressNotFoundException {
823                 // Parameter must be valid
824                 if (null == emailAddress) {
825                         // Throw NPE
826                         throw new NullPointerException("emailAddress is null"); //NOI18N
827                 } else if (emailAddress.isEmpty()) {
828                         // Not valid
829                         throw new IllegalArgumentException("emailAddress is empty"); //NOI18N
830                 }
831
832                 // Init variable
833                 User user = null;
834
835                 // Try to lookup it in visible user list
836                 for (final Iterator<User> iterator = this.userList.iterator(); iterator.hasNext();) {
837                         // Get next user
838                         User next = iterator.next();
839
840                         // Contact should be set
841                         if (next.getUserContact() == null) {
842                                 // Contact is null
843                                 throw new NullPointerException(MessageFormat.format("next.userContact is null for user id {0}", next.getUserId())); //NOI18N
844                         } else if (next.getUserContact().getContactEmailAddress() == null) {
845                                 // Email address should be set
846                                 throw new NullPointerException(MessageFormat.format("next.userContact.contactEmailAddress is null for user id {0}", next.getUserId())); //NOI18N
847                         }
848
849                         // Is the email address found?
850                         if (Objects.equals(next.getUserContact().getContactEmailAddress(), emailAddress)) {
851                                 // Copy to other variable
852                                 user = next;
853                                 break;
854                         }
855                 }
856
857                 // Is it still null?
858                 if (null == user) {
859                         // Not visible for the current user
860                         throw new UserEmailAddressNotFoundException(emailAddress);
861                 }
862
863                 // Return it
864                 return user;
865         }
866
867         @Override
868         public User lookupUserById (final Long userId) throws UserNotFoundException {
869                 // Parameter must be valid
870                 if (null == userId) {
871                         // Throw NPE
872                         throw new NullPointerException("userId is null"); //NOI18N
873                 } else if (userId < 1) {
874                         // Not valid
875                         throw new IllegalArgumentException(MessageFormat.format("userId={0} is not valid.", userId)); //NOI18N
876                 }
877
878                 // Init variable
879                 User user = null;
880
881                 // Try to lookup it in visible user list
882                 for (final Iterator<User> iterator = this.userList.iterator(); iterator.hasNext();) {
883                         // Get next user
884                         User next = iterator.next();
885
886                         // Is the user id found?
887                         if (Objects.equals(next.getUserId(), userId)) {
888                                 // Copy to other variable
889                                 user = next;
890                                 break;
891                         }
892                 }
893
894                 // Is it still null?
895                 if (null == user) {
896                         // Not visible for the current user
897                         throw new UserNotFoundException(userId);
898                 }
899
900                 // Return it
901                 return user;
902         }
903
904         /**
905          * Adds user's name to bean's internal list. It also updates the public user
906          * list if the user has decided to have a public account,
907          * <p>
908          * @param user User instance
909          */
910         private void addUserName (final User user) {
911                 // Make sure the entry is not added yet
912                 if (this.userNameList.contains(user.getUserName())) {
913                         // Abort here
914                         throw new IllegalArgumentException(MessageFormat.format("User name {0} already added.", user.getUserName())); //NOI18N
915                 }
916
917                 // Add user name
918                 this.userNameList.add(user.getUserName());
919         }
920
921         /**
922          * Clears this bean
923          */
924         private void clear () {
925                 // Clear all data
926                 // - personal data
927                 this.setUserId(null);
928                 this.setUserProfileMode(null);
929
930                 // - other data
931                 this.setUserName(null);
932                 this.setUserPassword(null);
933                 this.setUserPasswordRepeat(null);
934         }
935
936         /**
937          * Copies given user into the controller
938          * <p>
939          * @param user User instance
940          */
941         private void copyUser (final User user) {
942                 // Make sure the instance is valid
943                 if (null == user) {
944                         // Throw NPE
945                         throw new NullPointerException("user is null"); //NOI18N
946                 } else if (user.getUserContact() == null) {
947                         // Throw again ...
948                         throw new NullPointerException("user.userContact is null"); //NOI18N
949                 }
950
951                 // Copy all fields:
952                 // - base data
953                 this.setUserId(user.getUserId());
954                 this.setUserProfileMode(user.getUserProfileMode());
955         }
956
957         /**
958          * Removes user from all lists
959          * <p>
960          * @param user User to remove
961          */
962         private void removeFromList (final User user) {
963                 // The user should be valid
964                 if (null == user) {
965                         // Throw NPE
966                         throw new NullPointerException("user is null"); //NOI18N
967                 } else if (user.getUserId() == null) {
968                         // ... again NPE
969                         throw new NullPointerException("user.userId is null"); //NOI18N
970                 } else if (user.getUserId() < 1) {
971                         // Invalid id
972                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is invalid", user.getUserId())); //NOI18N
973                 }
974
975                 // Remove it from lists
976                 this.userList.remove(user);
977                 this.visibleUserList.remove(user);
978
979                 // Remove name from list
980                 this.userNameList.remove(user.getUserName());
981         }
982
983         /**
984          * Updates list with given user instance
985          * <p>
986          * @param user User instance
987          */
988         private void updateList (final User user) {
989                 // The user should be valid
990                 if (null == user) {
991                         // Throw NPE
992                         throw new NullPointerException("user is null"); //NOI18N
993                 } else if (user.getUserId() == null) {
994                         // ... again NPE
995                         throw new NullPointerException("user.userId is null"); //NOI18N
996                 } else if (user.getUserId() < 1) {
997                         // Invalid id
998                         throw new IllegalArgumentException(MessageFormat.format("user.userId={0} is invalid", user.getUserId())); //NOI18N
999                 } else if (user.getUserContact() == null) {
1000                         // Throw again ...
1001                         throw new NullPointerException("user.userContact is null"); //NOI18N
1002                 } else if (user.getUserContact().getContactId() == null) {
1003                         // Throw again ...
1004                         throw new NullPointerException("user.userContact.contactId is null"); //NOI18N
1005                 } else if (user.getUserContact().getContactId() < 1) {
1006                         // Throw again ...
1007                         throw new NullPointerException(MessageFormat.format("user.userContact.contactId={0} is invalid.", user.getUserContact().getContactId())); //NOI18N
1008                 }
1009
1010                 // Get iterator from list
1011                 Iterator<User> iterator = this.userList.iterator();
1012
1013                 // "Walk" through all entries
1014                 while (iterator.hasNext()) {
1015                         // Get next element
1016                         User next = iterator.next();
1017
1018                         // Is user id number the same?
1019                         if (Objects.equals(user.getUserId(), next.getUserId())) {
1020                                 // Found entry, so remove it and abort
1021                                 this.userList.remove(next);
1022                                 break;
1023                         }
1024                 }
1025
1026                 // Re-add user
1027                 this.userList.add(user);
1028         }
1029
1030 }