+/*
+ * Copyright (C) 2016 Roland Haeder
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.mxchange.jusercore.model.email_address;
+
+import java.text.MessageFormat;
+import java.util.GregorianCalendar;
+import java.util.List;
+import javax.ejb.EJB;
+import javax.ejb.EJBException;
+import javax.ejb.Stateless;
+import javax.mail.Address;
+import javax.mail.internet.AddressException;
+import javax.mail.internet.InternetAddress;
+import javax.persistence.NoResultException;
+import javax.persistence.Query;
+import org.mxchange.addressbook.database.BaseAddressbookDatabaseBean;
+import org.mxchange.jusercore.model.user.UserSessionBeanRemote;
+import org.mxchange.jusercore.model.user.UserUtils;
+
+/**
+ * A session bean for changing email addresses
+ * <p>
+ * @author Roland Haeder<roland@mxchange.org>
+ */
+@Stateless (name = "userEmailChange", description = "A bean handling user email changes")
+public class AddressbookUserEmailChangeSessionBean extends BaseAddressbookDatabaseBean implements EmailChangeSessionBeanRemote {
+
+ /**
+ * Serial number
+ */
+ private static final long serialVersionUID = 182_698_165_971_548L;
+
+ /**
+ * User bean
+ */
+ @EJB
+ private UserSessionBeanRemote userBean;
+
+ /**
+ * Default constructor
+ */
+ public AddressbookUserEmailChangeSessionBean () {
+ }
+
+ @Override
+ @SuppressWarnings ("unchecked")
+ public List<String> allQueuedAddresses () {
+ // Trace message
+ this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.allQueuedAddresses: CALLED!", this.getClass().getSimpleName())); //NOI18N
+
+ // Get named query
+ Query query = this.getEntityManager().createNamedQuery("AllEmailAddressChanges", String.class); //NOI18N
+
+ // Get all entries
+ List<String> emailAddresses = query.getResultList();
+
+ // Trace message
+ this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.allQueuedAddresses: emailAddresses.size()={1} - EXIT!", this.getClass().getSimpleName(), emailAddresses.size())); //NOI18N
+
+ // Return it
+ return emailAddresses;
+ }
+
+ @Override
+ public void enqueueEmailAddressForChange (final ChangeableEmailAddress emailChange, final String baseUrl) {
+ // Trace message
+ this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.enqueueEmailAddressForChange: emailChange={1},baseUrl={2} - CALLED!", this.getClass().getSimpleName(), emailChange, baseUrl)); //NOI18N
+
+ // Email address change should be valid
+ if (null == emailChange) {
+ // Abort here
+ throw new NullPointerException("emailChange is null"); //NOI18N
+ } else if (emailChange.getEmailChangeUser() == null) {
+ // Throw NPE again
+ throw new NullPointerException("emailChange.emailChangeUser is null"); //NOI18N
+ } else if (emailChange.getEmailChangeUser().getUserId() == null) {
+ // Throw NPE again
+ throw new NullPointerException("emailChange.emailChangeUser.userId is null"); //NOI18N
+ } else if (emailChange.getEmailChangeUser().getUserId() < 1) {
+ // Not valid id
+ throw new IllegalArgumentException(MessageFormat.format("emailChange.emailChangeUser.userId={0} is invalid.", emailChange.getEmailChangeUser().getUserId())); //NOI18N
+ } else if (!this.userBean.ifUserExists(emailChange.getEmailChangeUser())) {
+ // User does not exist
+ throw new EJBException(MessageFormat.format("Email change with id {0} does not exist.", emailChange.getEmailChangeId())); //NOI18N
+ } else if (emailChange.getEmailAddress().trim().isEmpty()) {
+ // Email address is empty
+ throw new IllegalArgumentException("emailChange.emaiLAddress is empty."); //NOI18N
+ } else if (this.isEmailAddressEnqueued(emailChange.getEmailAddress())) {
+ // Email address is already enqueued
+ throw new EJBException(MessageFormat.format("Email address {0} is already enqueued.", emailChange.getEmailAddress())); //NOI18N
+ }
+
+ // The email change is not (yet) there, add secure hash and "created" timestamp
+ emailChange.setEmailChangeCreated(new GregorianCalendar());
+ this.generateSecureHash(emailChange);
+
+ // Persist it
+ //@TODO Fix email delivery then allow this: this.getEntityManager().persist(emailChange);
+ // Init variable
+ Address emailAddress;
+
+ try {
+ // Create email address and set
+ emailAddress = new InternetAddress(emailChange.getEmailAddress());
+ } catch (final AddressException ex) {
+ // Throw again
+ throw new EJBException(ex);
+ }
+
+ // Send email
+ this.sendEmail("Email change", "email_change", emailAddress, emailChange.getEmailChangeUser(), baseUrl); //NOI18N
+
+ // Trace message
+ this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.enqueueEmailAddressForChange - EXIT!", this.getClass().getSimpleName())); //NOI18N
+ }
+
+ @Override
+ public boolean isEmailAddressEnqueued (final String emailAddress) {
+ // Trace message
+ this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.isEmailAddressEnqueued: emailAddress={1} - CALLED!", this.getClass().getSimpleName(), emailAddress)); //NOI18N
+
+ // Create query instance
+ Query query = this.getEntityManager().createNamedQuery("SearchEmailChangeByEmail"); //NOI18N
+
+ // Add email address as parameter
+ query.setParameter("email", emailAddress); //NOI18N
+
+ // Initialize variable
+ boolean isFound = false;
+
+ // Try it
+ try {
+ // Try to get single result
+ ChangeableEmailAddress dummy = (ChangeableEmailAddress) query.getSingleResult();
+
+ // Found it
+ isFound = true;
+ } catch (final NoResultException ex) {
+ // Log it
+ this.getLoggerBeanLocal().logException(ex);
+ }
+
+ // Trace message
+ this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.isEmailAddressEnqueued: isFound={1} - EXIT!", this.getClass().getSimpleName(), isFound)); //NOI18N
+
+ // Return it
+ return isFound;
+ }
+
+ @Override
+ public void updateEmailAddress (final ChangeableEmailAddress emailAddress) {
+ // Trace message
+ this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.updateEmailAddress: emailAddress={1} - CALLED!", this.getClass().getSimpleName(), emailAddress)); //NOI18N
+
+ // Email address change should be valid
+ if (null == emailAddress) {
+ // Abort here
+ throw new NullPointerException("emailAddress is null"); //NOI18N
+ } else if (emailAddress.getEmailChangeId() == null) {
+ // Throw NPE again
+ throw new NullPointerException("emailAddress.emailChangeId is null"); //NOI18N
+ } else if (emailAddress.getEmailChangeId() < 1) {
+ // Not valid
+ throw new IllegalArgumentException(MessageFormat.format("emailAddress.emailChangeId={0} is not valid.", emailAddress.getEmailChangeId())); //NOI18N
+ } else if (emailAddress.getEmailAddress().trim().isEmpty()) {
+ // Email address is empty
+ throw new IllegalArgumentException("emailAddress.emaiLAddress is empty."); //NOI18N
+ } else if (!this.userBean.ifUserExists(emailAddress.getEmailChangeUser())) {
+ // User does not exist
+ throw new EJBException(MessageFormat.format("Email change with id {0} does not exist.", emailAddress.getEmailChangeId())); //NOI18N
+ } else if (!this.isEmailAddressEnqueued(emailAddress.getEmailAddress())) {
+ // Email address is not enqueued
+ throw new EJBException(MessageFormat.format("Email address {0} is not enqueued.", emailAddress.getEmailAddress())); //NOI18N
+ }
+
+ throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
+ }
+
+ /**
+ * Generates a secure, unique hash for given email address change. This
+ * requires to check if the hash is really not there.
+ * <p>
+ * @param emailAddress Email address change
+ */
+ private void generateSecureHash (final ChangeableEmailAddress emailAddress) {
+ // Email address change should be valid
+ if (null == emailAddress) {
+ // Abort here
+ throw new NullPointerException("emailAddress is null"); //NOI18N
+ } else if (emailAddress.getEmailAddress().trim().isEmpty()) {
+ // Email address is empty
+ throw new IllegalArgumentException("emailAddress.emaiLAddress is empty."); //NOI18N
+ }
+
+ // Initialize loop with null
+ String hash = null;
+
+ // Default is not used
+ boolean isUsed = true;
+
+ // Search for free hash
+ while (isUsed) {
+ // Generate hash, there is already in UserUtils a nice method that can be used for this purpose.
+ hash = UserUtils.encryptPassword(String.format("%s:%s", emailAddress.getEmailAddress(), emailAddress.toString())); //NOI18N
+
+ // The hash *may* be unique, better test it
+ Query query = this.getEntityManager().createNamedQuery("SearchEmailChangeByHash", EmailAddressChange.class); //NOI18N
+
+ // Set hash as parameter
+ query.setParameter("hash", hash); //NOI18N
+
+ // Try to get single result
+ try {
+ // Get single result
+ ChangeableEmailAddress dummy = (ChangeableEmailAddress) query.getSingleResult();
+ } catch (final NoResultException ex) {
+ // Not found
+ isUsed = false;
+ }
+ }
+
+ // hash should not be null and set
+ assert (hash != null) : "hash is null"; //NOI18N
+ assert (!hash.isEmpty()) : "hash is empty"; //NOI18N
+
+ // Set it in email change
+ emailAddress.setEmailChangeHash(hash);
+ }
+
+}