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