]> git.mxchange.org Git - jjobs-ejb.git/blob - src/java/org/mxchange/jusercore/model/user/email_address/JobsUserEmailChangeSessionBean.java
Please cherry-pick:
[jjobs-ejb.git] / src / java / org / mxchange / jusercore / model / user / email_address / JobsUserEmailChangeSessionBean.java
1 /*
2  * Copyright (C) 2016 - 2018 Free Software Foundation
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.jusercore.model.user.email_address;
18
19 import java.text.MessageFormat;
20 import java.util.Date;
21 import java.util.List;
22 import javax.ejb.EJB;
23 import javax.ejb.EJBException;
24 import javax.ejb.Stateless;
25 import javax.persistence.NoResultException;
26 import javax.persistence.Query;
27 import org.mxchange.jjobs.enterprise.BaseJobsEnterpriseBean;
28 import org.mxchange.jusercore.model.email_address.ChangeableEmailAddress;
29 import org.mxchange.jusercore.model.email_address.EmailAddressChange;
30 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
31 import org.mxchange.juserlogincore.login.UserLoginUtils;
32
33 /**
34  * A session-scoped bean for changing email addresses
35  * <p>
36  * @author Roland Häder<roland@mxchange.org>
37  */
38 @Stateless (name = "userEmailChange", description = "A bean handling user email changes")
39 public class JobsUserEmailChangeSessionBean extends BaseJobsEnterpriseBean implements UserEmailChangeSessionBeanRemote {
40
41         /**
42          * Serial number
43          */
44         private static final long serialVersionUID = 182_698_165_971_548L;
45
46         /**
47          * User bean
48          */
49         @EJB
50         private UserSessionBeanRemote userBean;
51
52         /**
53          * Default constructor
54          */
55         public JobsUserEmailChangeSessionBean () {
56                 // Call super constructor
57                 super("jms/jjobs-queue-factory", "jms/jjobs-email-queue"); //NOI18N
58         }
59
60         @Override
61         @SuppressWarnings ("unchecked")
62         public List<String> allQueuedAddresses () {
63                 // Trace message
64                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.allQueuedAddresses: CALLED!", this.getClass().getSimpleName())); //NOI18N
65
66                 // Get named query
67                 final Query query = this.getEntityManager().createNamedQuery("AllEmailAddressChanges", String.class); //NOI18N
68
69                 // Get all entries
70                 final List<String> emailAddresses = query.getResultList();
71
72                 // Trace message
73                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.allQueuedAddresses: emailAddresses.size()={1} - EXIT!", this.getClass().getSimpleName(), emailAddresses.size())); //NOI18N
74
75                 // Return it
76                 return emailAddresses;
77         }
78
79         @Override
80         public void enqueueEmailAddressForChange (final ChangeableEmailAddress emailChange, final String baseUrl) {
81                 // Trace message
82                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.enqueueEmailAddressForChange: emailChange={1},baseUrl={2} - CALLED!", this.getClass().getSimpleName(), emailChange, baseUrl)); //NOI18N
83
84                 // Email address change should be valid
85                 if (null == emailChange) {
86                         // Abort here
87                         throw new NullPointerException("emailChange is null"); //NOI18N
88                 } else if (emailChange.getEmailChangeUser() == null) {
89                         // Throw NPE again
90                         throw new NullPointerException("emailChange.emailChangeUser is null"); //NOI18N
91                 } else if (emailChange.getEmailChangeUser().getUserId() == null) {
92                         // Throw NPE again
93                         throw new NullPointerException("emailChange.emailChangeUser.userId is null"); //NOI18N
94                 } else if (emailChange.getEmailChangeUser().getUserId() < 1) {
95                         // Not valid id
96                         throw new IllegalArgumentException(MessageFormat.format("emailChange.emailChangeUser.userId={0} is invalid.", emailChange.getEmailChangeUser().getUserId())); //NOI18N
97                 } else if (!this.userBean.ifUserExists(emailChange.getEmailChangeUser())) {
98                         // User does not exist
99                         throw new EJBException(MessageFormat.format("Email change with id {0} does not exist.", emailChange.getEmailChangeId())); //NOI18N
100                 } else if (emailChange.getEmailAddress().trim().isEmpty()) {
101                         // Email address is empty
102                         throw new IllegalArgumentException("emailChange.emaiLAddress is empty."); //NOI18N
103                 } else if (this.isEmailAddressEnqueued(emailChange.getEmailAddress())) {
104                         // Email address is already enqueued
105                         throw new EJBException(MessageFormat.format("Email address {0} is already enqueued.", emailChange.getEmailAddress())); //NOI18N
106                 }
107
108                 // The email change is not (yet) there, add secure hash and "created" timestamp
109                 emailChange.setEmailChangeCreated(new Date());
110                 this.generateSecureHash(emailChange);
111
112                 // Make user managed
113                 emailChange.setEmailChangeUser(this.createManaged(emailChange.getEmailChangeUser()));
114
115                 // Persist it
116                 //@TODO Fix email delivery then allow this: this.getEntityManager().persist(emailChange);
117
118                 // Send email
119                 this.sendEmail("User email change", "user_email_change", emailChange.getEmailChangeUser(), baseUrl, null); //NOI18N
120
121                 // Trace message
122                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.enqueueEmailAddressForChange - EXIT!", this.getClass().getSimpleName())); //NOI18N
123         }
124
125         @Override
126         public boolean isEmailAddressEnqueued (final String emailAddress) {
127                 // Trace message
128                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.isEmailAddressEnqueued: emailAddress={1} - CALLED!", this.getClass().getSimpleName(), emailAddress)); //NOI18N
129
130                 // Create query instance
131                 final Query query = this.getEntityManager().createNamedQuery("SearchEmailChangeByEmail"); //NOI18N
132
133                 // Add email address as parameter
134                 query.setParameter("email", emailAddress); //NOI18N
135
136                 // Initialize variable
137                 boolean isFound = false;
138
139                 // Try it
140                 try {
141                         // Try to get single result
142                         final ChangeableEmailAddress dummy = (ChangeableEmailAddress) query.getSingleResult();
143
144                         // Found it
145                         isFound = true;
146                 } catch (final NoResultException ex) {
147                         // Log it
148                         this.getLoggerBeanLocal().logException(ex);
149                 }
150
151                 // Trace message
152                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.isEmailAddressEnqueued: isFound={1} - EXIT!", this.getClass().getSimpleName(), isFound)); //NOI18N
153
154                 // Return it
155                 return isFound;
156         }
157
158         @Override
159         public void updateEmailAddress (final ChangeableEmailAddress emailAddress) {
160                 // Trace message
161                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateEmailAddress: emailAddress={1} - CALLED!", this.getClass().getSimpleName(), emailAddress)); //NOI18N
162
163                 // Email address change should be valid
164                 if (null == emailAddress) {
165                         // Abort here
166                         throw new NullPointerException("emailAddress is null"); //NOI18N
167                 } else if (emailAddress.getEmailChangeId() == null) {
168                         // Throw NPE again
169                         throw new NullPointerException("emailAddress.emailChangeId is null"); //NOI18N
170                 } else if (emailAddress.getEmailChangeId() < 1) {
171                         // Not valid
172                         throw new IllegalArgumentException(MessageFormat.format("emailAddress.emailChangeId={0} is not valid.", emailAddress.getEmailChangeId())); //NOI18N
173                 } else if (emailAddress.getEmailAddress().trim().isEmpty()) {
174                         // Email address is empty
175                         throw new IllegalArgumentException("emailAddress.emaiLAddress is empty."); //NOI18N
176                 } else if (!this.userBean.ifUserExists(emailAddress.getEmailChangeUser())) {
177                         // User does not exist
178                         throw new EJBException(MessageFormat.format("Email change with id {0} does not exist.", emailAddress.getEmailChangeId())); //NOI18N
179                 } else if (!this.isEmailAddressEnqueued(emailAddress.getEmailAddress())) {
180                         // Email address is not enqueued
181                         throw new EJBException(MessageFormat.format("Email address {0} is not enqueued.", emailAddress.getEmailAddress())); //NOI18N
182                 }
183
184                 throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
185         }
186
187         /**
188          * Generates a secure, unique hash for given email address change. This
189          * requires to check if the hash is really not there.
190          * <p>
191          * @param emailAddressChange Email address change
192          */
193         private void generateSecureHash (final ChangeableEmailAddress emailAddressChange) {
194                 // Email address change should be valid
195                 if (null == emailAddressChange) {
196                         // Abort here
197                         throw new NullPointerException("emailAddressChange is null"); //NOI18N
198                 } else if (emailAddressChange.getEmailAddress().trim().isEmpty()) {
199                         // Email address is empty
200                         throw new IllegalArgumentException("emailAddressChange.emaiLAddress is empty."); //NOI18N
201                 }
202
203                 // Initialize loop with null
204                 String hash = null;
205
206                 // Default is not used
207                 boolean isUsed = true;
208
209                 // Search for free hash
210                 while (isUsed) {
211                         // Generate hash, there is already in UserUtils a nice method that can be used for this purpose.
212                         hash = UserLoginUtils.encryptPassword(String.format("%s:%s", emailAddressChange.getEmailAddress(), emailAddressChange.toString())); //NOI18N
213
214                         // The hash *may* be unique, better test it
215                         final Query query = this.getEntityManager().createNamedQuery("SearchEmailChangeByHash", EmailAddressChange.class); //NOI18N
216
217                         // Set hash as parameter
218                         query.setParameter("hash", hash); //NOI18N
219
220                         // Try to get single result
221                         try {
222                                 // Get single result
223                                 final ChangeableEmailAddress dummy = (ChangeableEmailAddress) query.getSingleResult();
224                         } catch (final NoResultException ex) {
225                                 // Not found
226                                 isUsed = false;
227                         }
228                 }
229
230                 // hash should not be null and set
231                 assert (hash != null) : "hash is null"; //NOI18N
232                 assert (!hash.isEmpty()) : "hash is empty"; //NOI18N
233
234                 // Set it in email change
235                 emailAddressChange.setEmailChangeHash(hash);
236         }
237
238 }