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