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