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