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