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