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