2 * Copyright (C) 2016 Roland Haeder
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.
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.
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/>.
17 package org.mxchange.jusercore.model.email_address;
19 import java.text.MessageFormat;
20 import java.util.GregorianCalendar;
21 import java.util.List;
22 import java.util.Locale;
23 import java.util.Properties;
24 import javax.annotation.PostConstruct;
26 import javax.ejb.EJBException;
27 import javax.ejb.Stateless;
28 import javax.faces.FacesException;
29 import javax.jms.Connection;
30 import javax.jms.JMSException;
31 import javax.jms.MessageProducer;
32 import javax.jms.ObjectMessage;
33 import javax.jms.Queue;
34 import javax.jms.QueueConnectionFactory;
35 import javax.jms.Session;
36 import javax.mail.Address;
37 import javax.mail.internet.AddressException;
38 import javax.mail.internet.InternetAddress;
39 import javax.naming.Context;
40 import javax.naming.InitialContext;
41 import javax.naming.NamingException;
42 import javax.persistence.NoResultException;
43 import javax.persistence.Query;
44 import org.mxchange.jcoreee.database.BaseDatabaseBean;
45 import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
46 import org.mxchange.jusercore.model.user.UserUtils;
49 * A session bean for changing email addresses
51 * @author Roland Haeder<roland@mxchange.org>
53 @Stateless (name = "emailchange", description = "A bean handling email changes")
54 public class AddressbookEmailChangeSessionBean extends BaseDatabaseBean implements EmailChangeSessionBeanRemote {
59 private static final long serialVersionUID = 182_698_165_971_548L;
64 private Connection connection;
69 private ObjectMessage message;
74 private MessageProducer messageProducer;
77 * Mailer message queue
84 private Session session;
90 private UserSessionBeanRemote userBean;
95 public AddressbookEmailChangeSessionBean () {
99 @SuppressWarnings ("unchecked")
100 public List<String> allQueuedAddressesAsList () {
102 this.getLoggerBeanLocal().logTrace("allQueuedAddressesAsList: CALLED!"); //NOI18N
105 Query query = this.getEntityManager().createNamedQuery("AllEmailAddressChanges", List.class); //NOI18N
108 List<String> emailAddresses = query.getResultList();
111 this.getLoggerBeanLocal().logTrace(MessageFormat.format("allQueuedAddressesAsList: emailAddresses.size()={0} - EXIT!", emailAddresses.size())); //NOI18N
114 return emailAddresses;
118 public void enqueueEmailAddressForChange (final ChangeableEmailAddress emailChange) {
120 this.getLoggerBeanLocal().logTrace(MessageFormat.format("enqueueEmailAddressForChange: emailChange={0} - CALLED!", emailChange)); //NOI18N
122 // Email address change should be valid
123 if (null == emailChange) {
125 throw new NullPointerException("emailChange is null"); //NOI18N
126 } else if (emailChange.getEmailChangeUser() == null) {
128 throw new NullPointerException("emailChange.emailChangeUser is null"); //NOI18N
129 } else if (emailChange.getEmailChangeUser().getUserId() == null) {
131 throw new NullPointerException("emailChange.emailChangeUser.userId is null"); //NOI18N
132 } else if (emailChange.getEmailChangeUser().getUserId() < 1) {
134 throw new IllegalArgumentException(MessageFormat.format("emailChange.emailChangeUser.userId={0} is invalid.", emailChange.getEmailChangeUser().getUserId())); //NOI18N
135 } else if (!this.userBean.ifUserExists(emailChange.getEmailChangeUser())) {
136 // User does not exist
137 throw new EJBException(MessageFormat.format("Email change with id {0} does not exist.", emailChange.getEmailChangeId())); //NOI18N
138 } else if (emailChange.getEmailAddress().trim().isEmpty()) {
139 // Email address is empty
140 throw new IllegalArgumentException("emailChange.emaiLAddress is empty."); //NOI18N
141 } else if (this.isEmailAddressEnqueued(emailChange.getEmailAddress())) {
142 // Email address is already enqueued
143 throw new EJBException(MessageFormat.format("Email address {0} is already enqueued.", emailChange.getEmailAddress())); //NOI18N
146 // The email change is not (yet) there, add secure hash and "created" timestamp
147 emailChange.setEmailChangeCreated(new GregorianCalendar());
148 this.generateSecureHash(emailChange);
151 //this.getEntityManager().persist(emailChange);
153 // Prepare mail wrapper
154 WrapableEmailDelivery emailWrapper = new EmailDeliveryWrapper();
157 // Create email address and set
158 Address emailAddress = new InternetAddress(emailChange.getEmailAddress());
159 emailWrapper.setRecipient(emailAddress);
160 } catch (final AddressException ex) {
162 throw new EJBException(ex);
166 Properties variables = UserUtils.getAllUserFields(emailChange.getEmailChangeUser());
169 // @TODO Get locale from user + language from message bundle
170 emailWrapper.setLocale(Locale.GERMAN);
171 emailWrapper.setSubjectLine("Email change");
172 emailWrapper.setTemplateName("email_change"); //NOI18N
173 emailWrapper.setTemplateVariables(variables);
176 // Send out email change
177 this.message.setObject(emailWrapper);
180 this.sendMessage(this.message);
181 } catch (final JMSException ex) {
183 throw new EJBException(ex);
187 this.getLoggerBeanLocal().logTrace("enqueueEmailAddressForChange - EXIT!"); //NOI18N
191 * Initialization of this bean
194 public void init () {
196 this.getLoggerBeanLocal().logTrace("init: CALLED!"); //NOI18N
199 // Get initial context
200 Context context = new InitialContext();
202 // Get factory from JMS resource
203 QueueConnectionFactory connectionFactory = (QueueConnectionFactory) context.lookup("jms/jlandingpage-queue-factory"); //NOI18N
206 this.queue = (Queue) context.lookup("jms/jlandingpage-email-queue"); //NOI18N
209 this.connection = connectionFactory.createConnection();
211 // Init session instance
212 this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
214 // And message producer
215 this.messageProducer = this.session.createProducer(this.queue);
217 // Finally the message instance itself
218 this.message = this.session.createObjectMessage();
219 } catch (final NamingException | JMSException e) {
220 // Continued to throw
221 throw new FacesException(e);
226 public boolean isEmailAddressEnqueued (final String emailAddress) {
228 this.getLoggerBeanLocal().logTrace(MessageFormat.format("isEmailAddressEnqueued: emailAddress={0} - CALLED!", emailAddress)); //NOI18N
230 // Create query instance
231 Query query = this.getEntityManager().createNamedQuery("SearchEmailChangeByEmail"); //NOI18N
233 // Add email address as parameter
234 query.setParameter("email", emailAddress); //NOI18N
236 // Initialize variable
237 boolean isFound = false;
241 // Try to get single result
242 ChangeableEmailAddress dummy = (ChangeableEmailAddress) query.getSingleResult();
246 } catch (final NoResultException ex) {
248 this.getLoggerBeanLocal().logException(ex);
252 this.getLoggerBeanLocal().logTrace(MessageFormat.format("isEmailAddressEnqueued: isFound={0} - EXIT!", isFound)); //NOI18N
259 public void updateEmailAddress (final ChangeableEmailAddress emailAddress) {
261 this.getLoggerBeanLocal().logTrace(MessageFormat.format("updateEmailAddress: emailAddress={0} - CALLED!", emailAddress)); //NOI18N
263 // Email address change should be valid
264 if (null == emailAddress) {
266 throw new NullPointerException("emailAddress is null"); //NOI18N
267 } else if (emailAddress.getEmailChangeId() == null) {
269 throw new NullPointerException("emailAddress.emailChangeId is null"); //NOI18N
270 } else if (emailAddress.getEmailChangeId() < 1) {
272 throw new IllegalArgumentException(MessageFormat.format("emailAddress.emailChangeId={0} is not valid.", emailAddress.getEmailChangeId())); //NOI18N
273 } else if (emailAddress.getEmailAddress().trim().isEmpty()) {
274 // Email address is empty
275 throw new IllegalArgumentException("emailAddress.emaiLAddress is empty."); //NOI18N
276 } else if (!this.userBean.ifUserExists(emailAddress.getEmailChangeUser())) {
277 // User does not exist
278 throw new EJBException(MessageFormat.format("Email change with id {0} does not exist.", emailAddress.getEmailChangeId())); //NOI18N
279 } else if (!this.isEmailAddressEnqueued(emailAddress.getEmailAddress())) {
280 // Email address is not enqueued
281 throw new EJBException(MessageFormat.format("Email address {0} is not enqueued.", emailAddress.getEmailAddress())); //NOI18N
284 throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
288 * Generates a secure, unique hash for given email address change. This
289 * requires to check if the hash is really not there.
291 * @param emailAddress Email address change
293 private void generateSecureHash (final ChangeableEmailAddress emailAddress) {
294 // Email address change should be valid
295 if (null == emailAddress) {
297 throw new NullPointerException("emailAddress is null"); //NOI18N
298 } else if (emailAddress.getEmailAddress().trim().isEmpty()) {
299 // Email address is empty
300 throw new IllegalArgumentException("emailAddress.emaiLAddress is empty."); //NOI18N
303 // Initialize loop with null
306 // Default is not used
307 boolean isUsed = true;
309 // Search for free hash
311 // Generate hash, there is already in UserUtils a nice method that can be used for this purpose.
312 hash = UserUtils.encryptPassword(String.format("%s:%s", emailAddress.getEmailAddress(), emailAddress.toString())); //NOI18N
314 // The hash *may* be unique, better test it
315 Query query = this.getEntityManager().createNamedQuery("SearchEmailChangeByHash", EmailAddressChange.class); //NOI18N
317 // Set hash as parameter
318 query.setParameter("hash", hash); //NOI18N
320 // Try to get single result
323 ChangeableEmailAddress dummy = (ChangeableEmailAddress) query.getSingleResult();
324 } catch (final NoResultException ex) {
330 // hash should not be null and set
331 assert (hash != null) : "hash is null"; //NOI18N
332 assert (!hash.isEmpty()) : "hash is empty"; //NOI18N
334 // Set it in email change
335 emailAddress.setEmailChangeHash(hash);
339 * Sends given message to configured queue
341 * @param message Message to send
343 * @throws JMSException if something went wrong
345 private void sendMessage (final ObjectMessage message) throws JMSException {
346 // The parameter should be valid
347 if (null == message) {
349 throw new NullPointerException("message is null"); //NOI18N
353 this.messageProducer.send(message);