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