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