]> git.mxchange.org Git - jjobs-war.git/blob - src/java/org/mxchange/jjobs/beans/user/JobsUserWebSessionBean.java
Continued with refacturing:
[jjobs-war.git] / src / java / org / mxchange / jjobs / beans / user / JobsUserWebSessionBean.java
1 /*
2  * Copyright (C) 2016 Roland Haeder
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU Affero General Public License as
6  * published by the Free Software Foundation, either version 3 of the
7  * License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU Affero General Public License for more details.
13  *
14  * You should have received a copy of the GNU Affero General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17 package org.mxchange.jjobs.beans.user;
18
19 import java.text.MessageFormat;
20 import java.util.Collections;
21 import java.util.Iterator;
22 import java.util.List;
23 import java.util.Objects;
24 import javax.annotation.PostConstruct;
25 import javax.enterprise.context.SessionScoped;
26 import javax.enterprise.event.Observes;
27 import javax.faces.view.facelets.FaceletException;
28 import javax.inject.Inject;
29 import javax.inject.Named;
30 import javax.naming.Context;
31 import javax.naming.InitialContext;
32 import javax.naming.NamingException;
33 import org.mxchange.jcontacts.contact.Contact;
34 import org.mxchange.jjobs.beans.contact.JobsContactWebSessionController;
35 import org.mxchange.jjobs.beans.login.JobsUserLoginWebSessionController;
36 import org.mxchange.jphone.phonenumbers.cellphone.DialableCellphoneNumber;
37 import org.mxchange.jphone.phonenumbers.fax.DialableFaxNumber;
38 import org.mxchange.jphone.phonenumbers.landline.DialableLandLineNumber;
39 import org.mxchange.jusercore.events.login.UserLoggedInEvent;
40 import org.mxchange.jusercore.events.registration.UserRegisteredEvent;
41 import org.mxchange.jusercore.exceptions.UserNotFoundException;
42 import org.mxchange.jusercore.exceptions.UserPasswordMismatchException;
43 import org.mxchange.jusercore.model.user.LoginUser;
44 import org.mxchange.jusercore.model.user.User;
45 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
46 import org.mxchange.jusercore.model.user.profilemodes.ProfileMode;
47
48 /**
49  * A user bean (controller)
50  * <p>
51  * @author Roland Haeder<roland@mxchange.org>
52  */
53 @Named ("userController")
54 @SessionScoped
55 public class JobsUserWebSessionBean implements JobsUserWebSessionController {
56
57         /**
58          * Serial number
59          */
60         private static final long serialVersionUID = 542_145_347_916L;
61
62         /**
63          * General contact controller
64          */
65         @Inject
66         private JobsContactWebSessionController contactController;
67
68         /**
69          * Login bean (controller)
70          */
71         @Inject
72         private JobsUserLoginWebSessionController loginController;
73
74         /**
75          * Remote user bean
76          */
77         private final UserSessionBeanRemote userBean;
78
79         /**
80          * User id
81          */
82         private Long userId;
83
84         /**
85          * User name
86          */
87         private String userName;
88
89         /**
90          * User name list
91          */
92         private List<String> userNameList;
93
94         /**
95          * User password (unencrypted from web form)
96          */
97         private String userPassword;
98
99         /**
100          * User password repeated (unencrypted from web form)
101          */
102         private String userPasswordRepeat;
103
104         /**
105          * Whether the user wants a public profile
106          */
107         private ProfileMode userProfileMode;
108
109         /**
110          * A list of all public user profiles
111          */
112         private List<User> visibleUserList;
113
114         /**
115          * Default constructor
116          */
117         public JobsUserWebSessionBean () {
118                 // Try it
119                 try {
120                         // Get initial context
121                         Context context = new InitialContext();
122
123                         // Try to lookup
124                         this.userBean = (UserSessionBeanRemote) context.lookup("java:global/jjobs-ejb/user!org.mxchange.jusercore.model.user.UserSessionBeanRemote"); //NOI18N
125                 } catch (final NamingException e) {
126                         // Throw again
127                         throw new FaceletException(e);
128                 }
129         }
130
131         @Override
132         public void afterRegistrationEvent (final @Observes UserRegisteredEvent event) {
133                 // Trace message
134                 System.out.println(MessageFormat.format("UserWebBean:afterRegistration: event={0} - CALLED!", event)); //NOI18N
135
136                 // event should not be null
137                 if (null == event) {
138                         // Throw NPE
139                         throw new NullPointerException("event is null"); //NOI18N
140                 } else if (event.getRegisteredUser() == null) {
141                         // Throw NPE again
142                         throw new NullPointerException("event.user is null"); //NOI18N
143                 } else if (event.getRegisteredUser().getUserId() == null) {
144                         // userId is null
145                         throw new NullPointerException("event.user.userId is null"); //NOI18N
146                 } else if (event.getRegisteredUser().getUserId() < 1) {
147                         // Not avalid id
148                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getRegisteredUser(), event.getRegisteredUser().getUserId())); //NOI18N
149                 }
150
151                 // Get user instance
152                 User registeredUser = event.getRegisteredUser();
153
154                 // Debug message
155                 System.out.println(MessageFormat.format("UserWebBean:afterRegistration: registeredUser={0}", registeredUser)); //NOI18N
156
157                 // Copy all data from registered->user
158                 this.copyUser(registeredUser);
159
160                 // Add user name and email address
161                 this.addUserNameEmailAddress(registeredUser);
162
163                 // Clear all data
164                 this.clear();
165
166                 // Set user id again
167                 this.setUserId(registeredUser.getUserId());
168
169                 // Is the account public?
170                 if (Objects.equals(registeredUser.getUserProfileMode(), ProfileMode.PUBLIC)) {
171                         // Also add it to this list
172                         this.visibleUserList.add(registeredUser);
173                 }
174
175                 // Trace message
176                 System.out.println("UserWebBean:afterRegistration: EXIT!"); //NOI18N
177         }
178
179         @Override
180         public void afterUserLogin (final @Observes UserLoggedInEvent event) {
181                 // Trace message
182                 System.out.println(MessageFormat.format("UserWebBean:afterUserLogin: event={0} - CALLED!", event)); //NOI18N
183
184                 // event should not be null
185                 if (null == event) {
186                         // Throw NPE
187                         throw new NullPointerException("event is null"); //NOI18N
188                 } else if (event.getLoggedInUser() == null) {
189                         // Throw NPE again
190                         throw new NullPointerException("event.user is null"); //NOI18N
191                 } else if (event.getLoggedInUser().getUserId() == null) {
192                         // userId is null
193                         throw new NullPointerException("event.user.userId is null"); //NOI18N
194                 } else if (event.getLoggedInUser().getUserId() < 1) {
195                         // Not avalid id
196                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getLoggedInUser(), event.getLoggedInUser().getUserId())); //NOI18N
197                 }
198
199                 // Re-initialize list
200                 this.visibleUserList = this.userBean.allMemberPublicVisibleUsers();
201
202                 // Copy all data to this bean
203                 this.copyUser(event.getLoggedInUser());
204
205                 // Trace message
206                 System.out.println(MessageFormat.format("UserWebBean:afterUserLogin: this.visibleUserList.size()={0} - EXIT!", this.visibleUserList.size())); //NOI18N
207         }
208
209         @Override
210         public List<User> allVisibleUsers () {
211                 // Return it
212                 return Collections.unmodifiableList(this.visibleUserList);
213         }
214
215         @Override
216         public User createUserInstance () {
217                 // User message
218                 //this.getLogger().logTrace("createUserInstance: CALLED!");
219
220                 // Required personal data must be set
221                 assert (this.isRequiredPersonalDataSet()) : "not all personal data is set"; //NOI18N
222
223                 // Create new user instance
224                 User localUser = new LoginUser();
225
226                 // Update all data ...
227                 localUser.setUserName(this.getUserName());
228                 localUser.setUserProfileMode(this.getUserProfileMode());
229
230                 // Create contact instance
231                 Contact contact = this.contactController.createContactInstance();
232
233                 // Set contact in user
234                 localUser.setUserContact(contact);
235
236                 // Trace message
237                 //this.getLogger().logTrace(MessageFormat.format("createUserInstance: user={0} - EXIT!", user));
238                 // Return it
239                 return localUser;
240         }
241
242         @Override
243         public String doChangePersonalData () {
244                 // This method shall only be called if the user is logged-in
245                 if (!this.loginController.isUserLoggedIn()) {
246                         // Not logged-in
247                         throw new IllegalStateException("User is not logged-in"); //NOI18N
248                 } else if (!this.isRequiredChangePersonalDataSet()) {
249                         // Not all required fields are set
250                         throw new FaceletException("Not all required fields are set."); //NOI18N
251                 } else if (!this.loginController.ifCurrentPasswordMatches()) {
252                         // Password not matching
253                         throw new FaceletException(new UserPasswordMismatchException(this.loginController.getLoggedInUser()));
254                 }
255
256                 // Get user instance
257                 User user = this.loginController.getLoggedInUser();
258
259                 // Copy contact data to contact instance
260                 this.contactController.updateContactDataFromController(user.getUserContact());
261
262                 // It should be there, so run some tests on it
263                 assert (user instanceof User) : "Instance loginController.loggedInUser is null";
264                 assert (user.getUserId() instanceof Long) : "Instance loginController.loggedInUser.userId is null";
265                 assert (user.getUserId() > 0) : MessageFormat.format("loginController.loggedInUser.userId={0} is invalid", user.getUserId());
266                 assert (user.getUserContact() instanceof Contact) : "Instance loginController.loggedInUser.userContact is null";
267                 assert (user.getUserContact().getContactId() instanceof Long) : "Instance loginController.userContact.contactId is null";
268                 assert (user.getUserContact().getContactId() > 0) : MessageFormat.format("Instance loginController.userContact.contactId={0} is invalid", user.getUserContact().getContactId());
269
270                 // Update all fields
271                 user.setUserProfileMode(this.getUserProfileMode());
272
273                 // Send it to the EJB
274                 this.userBean.updateUserPersonalData(user);
275
276                 // All fine
277                 return "user_data_saved"; //NOI18N
278         }
279
280         @Override
281         public Long getUserId () {
282                 return this.userId;
283         }
284
285         @Override
286         public void setUserId (final Long userId) {
287                 this.userId = userId;
288         }
289
290         @Override
291         public String getUserName () {
292                 return this.userName;
293         }
294
295         @Override
296         public void setUserName (final String userName) {
297                 this.userName = userName;
298         }
299
300         @Override
301         public String getUserPassword () {
302                 return this.userPassword;
303         }
304
305         @Override
306         public void setUserPassword (final String userPassword) {
307                 this.userPassword = userPassword;
308         }
309
310         @Override
311         public String getUserPasswordRepeat () {
312                 return this.userPasswordRepeat;
313         }
314
315         @Override
316         public void setUserPasswordRepeat (final String userPasswordRepeat) {
317                 this.userPasswordRepeat = userPasswordRepeat;
318         }
319
320         @Override
321         public ProfileMode getUserProfileMode () {
322                 return this.userProfileMode;
323         }
324
325         @Override
326         public void setUserProfileMode (final ProfileMode userProfileMode) {
327                 this.userProfileMode = userProfileMode;
328         }
329
330         /**
331          * Post-initialization of this class
332          */
333         @PostConstruct
334         public void init () {
335                 // Get full user name list for reducing EJB calls
336                 this.userNameList = this.userBean.getUserNameList();
337
338                 // Is the user logged-in?
339                 if (this.loginController.isUserLoggedIn()) {
340                         // Is logged-in, so load also users visible to memebers
341                         this.visibleUserList = this.userBean.allMemberPublicVisibleUsers();
342                 } else {
343                         // Initialize user list
344                         this.visibleUserList = this.userBean.allPublicUsers();
345                 }
346         }
347
348         @Override
349         public boolean isRequiredChangePersonalDataSet () {
350                 return ((this.getUserProfileMode() != null) &&
351                                 (this.contactController.isRequiredChangePersonalDataSet()));
352         }
353
354         @Override
355         public boolean isRequiredPersonalDataSet () {
356                 return ((this.getUserName() != null) &&
357                                 (this.getUserProfileMode() != null) &&
358                                 (this.contactController.isRequiredPersonalDataSet()) &&
359                                 (this.getUserPassword() != null) &&
360                                 (this.getUserPasswordRepeat() != null));
361         }
362
363         @Override
364         public boolean isSamePasswordEntered () {
365                 return ((!this.getUserPassword().isEmpty()) && (Objects.equals(this.getUserPassword(), this.getUserPasswordRepeat())));
366         }
367
368         @Override
369         public boolean isUserIdEmpty () {
370                 return ((this.getUserId() == null) || (this.getUserId() == 0));
371         }
372
373         @Override
374         public boolean isUserNameRegistered (final User user) {
375                 return ((this.userNameList instanceof List) && (this.userNameList.contains(user.getUserName())));
376         }
377
378         @Override
379         public boolean isVisibleUserFound () {
380                 return ((this.visibleUserList instanceof List) && (this.visibleUserList.size() > 0));
381         }
382
383         @Override
384         public User lookupUserById (final Long userId) throws UserNotFoundException {
385                 // Init variable
386                 User localUser = null;
387
388                 // Clear this bean
389                 this.clear();
390
391                 // Try to lookup it in visible user list
392                 for (final Iterator<User> iterator = this.visibleUserList.iterator(); iterator.hasNext();) {
393                         // Get next user
394                         User next = iterator.next();
395
396                         // Is the user id found?
397                         if (Objects.equals(next.getUserId(), userId)) {
398                                 // Copy to other variable
399                                 localUser = next;
400                                 break;
401                         }
402                 }
403
404                 // Is it still null?
405                 if (null == localUser) {
406                         // Not visible for the current user
407                         throw new UserNotFoundException(userId);
408                 }
409
410                 // Copy all data to this bean
411                 this.copyUser(localUser);
412
413                 // Return it
414                 return localUser;
415         }
416
417         /**
418          * Adds user's name and email address to bean's internal list. It also
419          * updates the public user list if the user has decided to ha   }
420          * <p>
421          * @param user User instance
422          */
423         private void addUserNameEmailAddress (final User user) {
424                 // Make sure the entry is not added yet
425                 if (this.userNameList.contains(user.getUserName())) {
426                         // Abort here
427                         throw new IllegalArgumentException(MessageFormat.format("User name {0} already added.", user.getUserName())); //NOI18N
428                 } else if (this.contactController.isEmailAddressRegistered(user.getUserContact())) {
429                         // Already added
430                         throw new IllegalArgumentException(MessageFormat.format("Email address {0} already added.", user.getUserContact().getContactEmailAddress())); //NOI18N
431                 }
432
433                 // Add user name
434                 this.userNameList.add(user.getUserName());
435
436                 // Add email addres
437                 this.contactController.addEmailAddress(user.getUserContact().getContactEmailAddress());
438         }
439
440         /**
441          * Clears this bean
442          */
443         private void clear () {
444                 // Clear all data
445                 // - personal data
446                 this.setUserId(null);
447                 this.setUserProfileMode(null);
448
449                 // - other data
450                 this.setUserName(null);
451                 this.setUserPassword(null);
452                 this.setUserPasswordRepeat(null);
453         }
454
455         /**
456          * Copies given user into the controller
457          * <p>
458          * @param user User instance
459          */
460         private void copyUser (final User user) {
461                 // Copy all fields:
462                 // - base data
463                 this.setUserId(user.getUserId());
464                 this.setUserProfileMode(user.getUserProfileMode());
465
466                 // Get cellphone, phone and fax instance
467                 DialableCellphoneNumber cellphone = user.getUserContact().getContactCellphoneNumber();
468                 DialableFaxNumber fax = user.getUserContact().getContactFaxNumber();
469                 DialableLandLineNumber phone = user.getUserContact().getContactLandLineNumber();
470         }
471 }