]> git.mxchange.org Git - addressbook-mailer-ejb.git/blob - src/java/org/mxchange/jusercore/model/user/email_address/AddressbookUserEmailChangeSessionBean.java
Please cherry-pick:
[addressbook-mailer-ejb.git] / src / java / org / mxchange / jusercore / model / user / email_address / AddressbookUserEmailChangeSessionBean.java
1 /*
2  * Copyright (C) 2016, 2017 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.jusercore.model.user.email_address;
18
19 import java.text.MessageFormat;
20 import java.util.GregorianCalendar;
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.addressbook.database.BaseAddressbookDatabaseBean;
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.jusercore.model.user.UserUtils;
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 AddressbookUserEmailChangeSessionBean extends BaseAddressbookDatabaseBean 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 AddressbookUserEmailChangeSessionBean () {
56                 // Call super constructor
57                 super("jms/addressbook-queue-factory", "jms/addressbook-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                 Query query = this.getEntityManager().createNamedQuery("AllEmailAddressChanges", String.class); //NOI18N
68
69                 // Get all entries
70                 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 GregorianCalendar());
110                 this.generateSecureHash(emailChange);
111
112                 // Persist it
113                 //@TODO Fix email delivery then allow this: this.getEntityManager().persist(emailChange);
114
115                 // Send email
116                 this.sendEmail("User email change", "user_email_change", emailChange.getEmailChangeUser(), baseUrl, null); //NOI18N
117
118                 // Trace message
119                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.enqueueEmailAddressForChange - EXIT!", this.getClass().getSimpleName())); //NOI18N
120         }
121
122         @Override
123         public boolean isEmailAddressEnqueued (final String emailAddress) {
124                 // Trace message
125                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.isEmailAddressEnqueued: emailAddress={1} - CALLED!", this.getClass().getSimpleName(), emailAddress)); //NOI18N
126
127                 // Create query instance
128                 Query query = this.getEntityManager().createNamedQuery("SearchEmailChangeByEmail"); //NOI18N
129
130                 // Add email address as parameter
131                 query.setParameter("email", emailAddress); //NOI18N
132
133                 // Initialize variable
134                 boolean isFound = false;
135
136                 // Try it
137                 try {
138                         // Try to get single result
139                         ChangeableEmailAddress dummy = (ChangeableEmailAddress) query.getSingleResult();
140
141                         // Found it
142                         isFound = true;
143                 } catch (final NoResultException ex) {
144                         // Log it
145                         this.getLoggerBeanLocal().logException(ex);
146                 }
147
148                 // Trace message
149                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.isEmailAddressEnqueued: isFound={1} - EXIT!", this.getClass().getSimpleName(), isFound)); //NOI18N
150
151                 // Return it
152                 return isFound;
153         }
154
155         @Override
156         public void updateEmailAddress (final ChangeableEmailAddress emailAddress) {
157                 // Trace message
158                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateEmailAddress: emailAddress={1} - CALLED!", this.getClass().getSimpleName(), emailAddress)); //NOI18N
159
160                 // Email address change should be valid
161                 if (null == emailAddress) {
162                         // Abort here
163                         throw new NullPointerException("emailAddress is null"); //NOI18N
164                 } else if (emailAddress.getEmailChangeId() == null) {
165                         // Throw NPE again
166                         throw new NullPointerException("emailAddress.emailChangeId is null"); //NOI18N
167                 } else if (emailAddress.getEmailChangeId() < 1) {
168                         // Not valid
169                         throw new IllegalArgumentException(MessageFormat.format("emailAddress.emailChangeId={0} is not valid.", emailAddress.getEmailChangeId())); //NOI18N
170                 } else if (emailAddress.getEmailAddress().trim().isEmpty()) {
171                         // Email address is empty
172                         throw new IllegalArgumentException("emailAddress.emaiLAddress is empty."); //NOI18N
173                 } else if (!this.userBean.ifUserExists(emailAddress.getEmailChangeUser())) {
174                         // User does not exist
175                         throw new EJBException(MessageFormat.format("Email change with id {0} does not exist.", emailAddress.getEmailChangeId())); //NOI18N
176                 } else if (!this.isEmailAddressEnqueued(emailAddress.getEmailAddress())) {
177                         // Email address is not enqueued
178                         throw new EJBException(MessageFormat.format("Email address {0} is not enqueued.", emailAddress.getEmailAddress())); //NOI18N
179                 }
180
181                 throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
182         }
183
184         /**
185          * Generates a secure, unique hash for given email address change. This
186          * requires to check if the hash is really not there.
187          * <p>
188          * @param emailAddress Email address change
189          */
190         private void generateSecureHash (final ChangeableEmailAddress emailAddress) {
191                 // Email address change should be valid
192                 if (null == emailAddress) {
193                         // Abort here
194                         throw new NullPointerException("emailAddress is null"); //NOI18N
195                 } else if (emailAddress.getEmailAddress().trim().isEmpty()) {
196                         // Email address is empty
197                         throw new IllegalArgumentException("emailAddress.emaiLAddress is empty."); //NOI18N
198                 }
199
200                 // Initialize loop with null
201                 String hash = null;
202
203                 // Default is not used
204                 boolean isUsed = true;
205
206                 // Search for free hash
207                 while (isUsed) {
208                         // Generate hash, there is already in UserUtils a nice method that can be used for this purpose.
209                         hash = UserUtils.encryptPassword(String.format("%s:%s", emailAddress.getEmailAddress(), emailAddress.toString())); //NOI18N
210
211                         // The hash *may* be unique, better test it
212                         Query query = this.getEntityManager().createNamedQuery("SearchEmailChangeByHash", EmailAddressChange.class); //NOI18N
213
214                         // Set hash as parameter
215                         query.setParameter("hash", hash); //NOI18N
216
217                         // Try to get single result
218                         try {
219                                 // Get single result
220                                 ChangeableEmailAddress dummy = (ChangeableEmailAddress) query.getSingleResult();
221                         } catch (final NoResultException ex) {
222                                 // Not found
223                                 isUsed = false;
224                         }
225                 }
226
227                 // hash should not be null and set
228                 assert (hash != null) : "hash is null"; //NOI18N
229                 assert (!hash.isEmpty()) : "hash is empty"; //NOI18N
230
231                 // Set it in email change
232                 emailAddress.setEmailChangeHash(hash);
233         }
234
235 }