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