com.sfs.whichdoctor.dao.BulkEmailDAOImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.sfs.whichdoctor.dao.BulkEmailDAOImpl.java

Source

/*******************************************************************************
 * Copyright (c) 2009 David Harrison.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl-3.0.html
 *
 * Contributors:
 *     David Harrison - initial API and implementation
 ******************************************************************************/
package com.sfs.whichdoctor.dao;

import com.sfs.beans.BuilderBean;
import com.sfs.beans.ObjectTypeBean;
import com.sfs.beans.PrivilegesBean;
import com.sfs.beans.UserBean;
import com.sfs.beans.EmailMessageBean;
import com.sfs.dao.EmailMessageDAO;
import com.sfs.dao.SFSDaoException;
import com.sfs.whichdoctor.beans.BulkEmailBean;
import com.sfs.whichdoctor.beans.EmailRecipientBean;
import com.sfs.whichdoctor.beans.OrganisationBean;
import com.sfs.whichdoctor.beans.PersonBean;
import com.sfs.whichdoctor.beans.PreferencesBean;
import com.sfs.whichdoctor.formatter.email.EmailFormatter;

import java.net.MalformedURLException;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.RowMapper;

/**
 * The Class BulkEmailDAOImpl.
 */
public class BulkEmailDAOImpl extends WhichDoctorBaseDAOImpl implements BulkEmailDAO {

    /** The data logger. */
    private static Logger dataLogger = Logger.getLogger(BulkEmailDAOImpl.class);

    /** The email message dao. */
    @Resource
    private EmailMessageDAO emailMessageDAO;

    /** The email recipient dao. */
    @Resource
    private EmailRecipientDAO emailRecipientDAO;

    /** The person dao. */
    @Resource
    private PersonDAO personDAO;

    /** The organisation dao. */
    @Resource
    private OrganisationDAO organisationDAO;

    /** The email formatters. */
    private Collection<EmailFormatter> emailFormatters;

    /**
     * Sets the email formatters.
     *
     * @param formatters the new email formatters
     */
    public final void setEmailFormatters(final Collection<EmailFormatter> formatters) {
        this.emailFormatters = formatters;
    }

    /**
     * Gets the configured email formatters.
     *
     * @return the email formatters
     */
    public final Collection<EmailFormatter> getEmailFormatters() {
        if (this.emailFormatters == null) {
            this.emailFormatters = new ArrayList<EmailFormatter>();
        }
        return this.emailFormatters;
    }

    /**
     * Used to get a BulkEmailBean for a specified BulkEmailId.
     *
     * @param bulkEmailId the bulk email id
     * @return the bulk email bean
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final BulkEmailBean load(final int bulkEmailId) throws WhichDoctorDaoException {
        return this.load(bulkEmailId, new BuilderBean());
    }

    /**
     * Used to get a BulkEmailBean for a specified BulkEmailId.
     *
     * @param bulkEmailId the bulk email id
     * @param loadDetails the load details
     * @return the bulk email bean
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final BulkEmailBean load(final int bulkEmailId, final BuilderBean loadDetails)
            throws WhichDoctorDaoException {

        dataLogger.info("BulkEmailId: " + bulkEmailId + " requested");

        final String loadId = getSQL().getValue("bulkEmail/load")
                + " WHERE bulk_email.BulkEmailId = ? GROUP BY bulk_email.GUID";

        BulkEmailBean bulkEmail = null;
        try {
            bulkEmail = (BulkEmailBean) this.getJdbcTemplateReader().queryForObject(loadId,
                    new Object[] { bulkEmailId }, new RowMapper() {
                        public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                            return loadBulkEmail(rs, loadDetails);
                        }
                    });

        } catch (IncorrectResultSizeDataAccessException ie) {
            // No results found for this search
            dataLogger.error("No result found for BulkEmailBean search", ie);
        }
        return bulkEmail;
    }

    /**
     * Used to get a BulkEmailBean for a specified GUID.
     *
     * @param guid the guid
     * @return the bulk email bean
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final BulkEmailBean loadGUID(final int guid) throws WhichDoctorDaoException {

        return this.loadGUID(guid, new BuilderBean());
    }

    /**
     * Used to get a BulkEmailBean for a specified GUID.
     *
     * @param guid the guid
     * @param loadDetails the load details
     * @return the bulk email bean
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final BulkEmailBean loadGUID(final int guid, final BuilderBean loadDetails)
            throws WhichDoctorDaoException {

        dataLogger.info("GUID: " + guid + " requested");

        final String loadId = getSQL().getValue("bulkEmail/load")
                + " WHERE bulk_email.GUID = ? GROUP BY bulk_email.GUID";

        BulkEmailBean bulkEmail = null;
        try {
            bulkEmail = (BulkEmailBean) this.getJdbcTemplateReader().queryForObject(loadId, new Object[] { guid },
                    new RowMapper() {
                        public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                            return loadBulkEmail(rs, loadDetails);
                        }
                    });

        } catch (IncorrectResultSizeDataAccessException ie) {
            // No results found for this search
            dataLogger.error("No result found for BulkEmailBean search");
        }
        return bulkEmail;
    }

    /**
     * Create an email message entry.
     *
     * @param bulkEmail the bulk email
     * @param checkUser the check user
     * @return the int
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final int create(final BulkEmailBean bulkEmail, final UserBean checkUser)
            throws WhichDoctorDaoException {

        bulkEmail.setActive(true);
        return save(bulkEmail, checkUser, "create");
    }

    /**
     * Update an email message entry.
     *
     * @param bulkEmail the bulk email
     * @param checkUser the check user
     * @return the int
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final int modify(final BulkEmailBean bulkEmail, final UserBean checkUser)
            throws WhichDoctorDaoException {

        bulkEmail.setActive(true);
        return save(bulkEmail, checkUser, "modify");
    }

    /**
     * Delete an email message (flag as non-active).
     *
     * @param bulkEmail the bulk email
     * @param checkUser the check user
     * @param privileges the privileges
     * @return true, if successful
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final boolean delete(final BulkEmailBean bulkEmail, final UserBean checkUser,
            final PrivilegesBean privileges) throws WhichDoctorDaoException {

        boolean success = false;

        if (!StringUtils.equalsIgnoreCase(checkUser.getDN(), bulkEmail.getCreatedBy())) {
            if (!privileges.getPrivilege(checkUser, "systemAdmin", "modify")) {
                // The user trying to delete the BulkEmailBean does not own
                // the object or is not a system administrator.
                throw new WhichDoctorDaoException("Insufficient user " + "credentials to delete bulk email");
            }
        }
        bulkEmail.setActive(false);
        int deleteId = save(bulkEmail, checkUser, "delete");
        if (deleteId > 0) {
            success = true;
        }
        return success;
    }

    /**
     * Send an email using the supplied BulkEmailBean to
     * the recipient identified by the supplied EmailRecipientBean.
     *
     * @param bulkEmail the bulk email
     * @param recipient the recipient
     * @param preferences the preferences
     * @param debugMode the debug mode flag
     * @return true, if successful
     */
    public final boolean sendEmail(final BulkEmailBean bulkEmail, final EmailRecipientBean recipient,
            final PreferencesBean preferences, final boolean debugMode) {

        boolean success = false;
        try {
            success = sendEmail(bulkEmail, recipient, null, preferences, debugMode);
        } catch (NullPointerException npe) {
            dataLogger.info(npe.getMessage());
        }
        return success;
    }

    /**
     * Send an email using the supplied BulkEmailBean to
     * the recipient identified by the supplied UserBean.
     *
     * @param bulkEmail the bulk email
     * @param user the user
     * @param preferences the preferences
     * @return true, if successful
     */
    public final boolean sendEmail(final BulkEmailBean bulkEmail, final UserBean user,
            final PreferencesBean preferences) {

        boolean success = false;
        try {
            success = sendEmail(bulkEmail, null, user, preferences, false);
        } catch (NullPointerException npe) {
            dataLogger.info(npe.getMessage());
        }
        return success;
    }

    /**
     * Prepare the email message bean.
     *
     * @param bulkEmail the bulk email
     * @param recipient the recipient
     * @param preferences the preferences
     * @param includeWrapper the include wrapper
     * @param embedImage the embed image
     * @return the bulk email bean
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final EmailMessageBean prepareEmailMessage(final BulkEmailBean bulkEmail,
            final EmailRecipientBean recipient, final PreferencesBean preferences, final boolean includeWrapper,
            final boolean embedImage) throws WhichDoctorDaoException {

        EmailMessageBean message = new EmailMessageBean();

        BuilderBean loadDetails = new BuilderBean();
        loadDetails.setParameter("EMAIL", true);
        if (StringUtils.isNotBlank(bulkEmail.getEmailClass())) {
            loadDetails.setParameter("EMAIL_CLASS", bulkEmail.getEmailClass());
        }
        if (StringUtils.isNotBlank(bulkEmail.getEmailType())) {
            loadDetails.setParameter("EMAIL_TYPE", bulkEmail.getEmailType());
        }
        loadDetails.setParameter("FINANCIAL_SUMMARY", true);

        PersonBean person = null;
        OrganisationBean org = null;

        if (recipient != null) {
            if (recipient.getPersonGUID() > 0) {
                try {
                    loadDetails.setParameter("MEMBERSHIP", true);
                    person = this.personDAO.loadGUID(recipient.getPersonGUID(), loadDetails);
                    if (person != null && person.getFirstEmailAddress() != null) {
                        message.setTo(person.getFirstEmailAddress().getEmail());
                    }
                } catch (WhichDoctorDaoException wde) {
                    dataLogger.error("Error loading recipient (person): " + wde.getMessage());
                    throw new WhichDoctorDaoException("Error loading recipient (person): " + wde.getMessage());
                }
            }
            if (recipient.getOrganisationGUID() > 0) {
                try {
                    org = this.organisationDAO.loadGUID(recipient.getOrganisationGUID(), loadDetails);
                    if (org != null && org.getFirstEmailAddress() != null) {
                        message.setTo(org.getFirstEmailAddress().getEmail());
                    }
                } catch (WhichDoctorDaoException wde) {
                    dataLogger.error("Error loading email recipient organisation: " + wde.getMessage());
                    throw new WhichDoctorDaoException(
                            "Error loading recipient " + "(organisation): " + wde.getMessage());
                }
            }
            if (StringUtils.isNotBlank(recipient.getCustomEmailAddress())) {
                message.setTo(recipient.getCustomEmailAddress());
            }
        }

        message.setFrom(bulkEmail.getEmailAddress());
        message.setFromName(bulkEmail.getSenderName());
        message.setPriority(bulkEmail.getPriority());
        message.setHtmlMessage(true);

        // Set the email subject
        message.setSubject(bulkEmail.getSubject());

        message.setMessage(bulkEmail.getHtmlMessage(preferences, includeWrapper, embedImage, person, org,
                this.getEmailFormatters()));

        if (StringUtils.isNotBlank(preferences.getOption("email", "logo"))) {
            // Add the logo as an attachment to this email
            try {
                message.addAttachment("whichdoctorLogo", new URL(preferences.getOption("email", "logo")));
            } catch (MalformedURLException me) {
                dataLogger.error("Error with attachment URL: " + me.getMessage());
            }
        }
        return message;
    }

    /**
     * Save the bulk email.
     *
     * @param bulkEmail the bulk email
     * @param checkUser the check user
     * @param action the action
     * @return the int
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    private int save(final BulkEmailBean bulkEmail, final UserBean checkUser, final String action)
            throws WhichDoctorDaoException {

        /* Check required information within BulkEmailBean is present */
        if (StringUtils.isBlank(bulkEmail.getSubject())) {
            throw new WhichDoctorDaoException("Email message requires a subject");
        }
        if (StringUtils.isBlank(bulkEmail.getMessage())) {
            throw new WhichDoctorDaoException("Email message requires a message");
        }

        int emailTypeId = 0;
        try {
            ObjectTypeBean object = this.getObjectTypeDAO().load("Email Type", bulkEmail.getEmailType(),
                    bulkEmail.getEmailClass());
            emailTypeId = object.getObjectTypeId();
        } catch (Exception e) {
            dataLogger.info("Error loading objecttype for email type: " + e.getMessage());
        }

        int bulkEmailId = 0;

        Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis());

        ArrayList<Object> parameters = new ArrayList<Object>();
        parameters.add(bulkEmail.getEmailAddress());
        parameters.add(bulkEmail.getSenderName());
        parameters.add(bulkEmail.getAdditionalRecipients());
        parameters.add(bulkEmail.getSubject());
        parameters.add(bulkEmail.getMessage());
        parameters.add(bulkEmail.getPriority());
        parameters.add(bulkEmail.getAppendContact());
        parameters.add(bulkEmail.getAppendLogo());
        parameters.add(bulkEmail.getAppendPrivacy());
        parameters.add(bulkEmail.getDeliverOutOfHours());
        parameters.add(emailTypeId);
        parameters.add(bulkEmail.getActive());
        parameters.add(sqlTimeStamp);
        parameters.add(checkUser.getDN());
        parameters.add(bulkEmail.getLogMessage(action));

        try {
            Integer[] result = this.performUpdate("bulkEmail", bulkEmail.getGUID(), parameters, "Bulk Email",
                    checkUser, action);
            /* Set the returned guid and id values */
            bulkEmail.setGUID(result[0]);
            bulkEmailId = result[1];
        } catch (Exception e) {
            dataLogger.error("Error processing email message record: " + e.getMessage());
            throw new WhichDoctorDaoException("Error processing email message " + "record: " + e.getMessage());
        }

        if (StringUtils.equals(action, "create") && bulkEmailId > 0 && bulkEmail.getEmailRecipients() != null) {
            for (EmailRecipientBean rcpt : bulkEmail.getEmailRecipients()) {
                if (rcpt != null) {
                    this.emailRecipientDAO.create(bulkEmail.getGUID(), rcpt.getPersonGUID(),
                            rcpt.getOrganisationGUID(), rcpt.getCustomEmailAddress(), true,
                            bulkEmail.getDeliverOutOfHours());
                }
            }
        }
        if (StringUtils.equals(action, "delete") && bulkEmailId > 0) {
            /** Delete any email recipients for this entry **/
            this.emailRecipientDAO.delete(bulkEmail.getGUID());
        }

        return bulkEmailId;
    }

    /**
     * Load bulk email.
     *
     * @param rs the rs
     * @param loadDetails the load details
     * @return the bulk email bean
     * @throws SQLException the sQL exception
     */
    private BulkEmailBean loadBulkEmail(final ResultSet rs, final BuilderBean loadDetails) throws SQLException {

        BulkEmailBean bulkEmail = new BulkEmailBean();

        bulkEmail.setId(rs.getInt("BulkEmailId"));
        bulkEmail.setGUID(rs.getInt("GUID"));
        bulkEmail.setEmailAddress(rs.getString("EmailAddress"));
        bulkEmail.setSenderName(rs.getString("SenderName"));
        bulkEmail.setAdditionalRecipients(rs.getString("AdditionalRecipients"));
        bulkEmail.setSubject(rs.getString("Subject"));
        bulkEmail.setPriority(rs.getInt("Priority"));
        bulkEmail.setAppendContact(rs.getBoolean("AppendContact"));
        bulkEmail.setAppendLogo(rs.getBoolean("AppendLogo"));
        bulkEmail.setAppendPrivacy(rs.getBoolean("AppendPrivacy"));
        bulkEmail.setDeliverOutOfHours(rs.getBoolean("DeliverOutOfHours"));
        bulkEmail.setMessage(rs.getString("Message"));
        bulkEmail.setEmailClass(rs.getString("EmailClass"));
        bulkEmail.setEmailType(rs.getString("EmailType"));

        bulkEmail.setSentCount(rs.getInt("SentCount"));
        bulkEmail.setFailedCount(rs.getInt("FailedCount"));
        bulkEmail.setPendingCount(rs.getInt("PendingCount"));

        bulkEmail.setActive(rs.getBoolean("Active"));
        try {
            bulkEmail.setCreatedDate(rs.getTimestamp("CreatedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error reading CreatedDate: " + sqe.getMessage());
        }
        bulkEmail.setCreatedBy(rs.getString("CreatedBy"));
        try {
            bulkEmail.setModifiedDate(rs.getTimestamp("ModifiedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error reading ModifiedDate: " + sqe.getMessage());
        }
        bulkEmail.setModifiedBy(rs.getString("ModifiedBy"));

        // Load user details from DB
        UserBean user = new UserBean();
        user.setDN(rs.getString("CreatedBy"));
        user.setPreferredName(rs.getString("CreatedFirstName"));
        user.setLastName(rs.getString("CreatedLastName"));
        bulkEmail.setCreatedUser(user);

        UserBean modified = new UserBean();
        modified.setDN(rs.getString("ModifiedBy"));
        modified.setPreferredName(rs.getString("ModifiedFirstName"));
        modified.setLastName(rs.getString("ModifiedLastName"));
        bulkEmail.setModifiedUser(modified);

        if (loadDetails.getBoolean("EMAIL_RECIPIENTS")) {
            try {
                bulkEmail.setEmailRecipients(this.emailRecipientDAO.load(bulkEmail.getGUID()));
            } catch (Exception e) {
                dataLogger.error("Error loading email recipients: " + e.getMessage());
            }
        }
        return bulkEmail;
    }

    /**
     * Send email.
     *
     * @param bulkEmail the bulk email
     * @param recipient the recipient
     * @param user the user
     * @param preferences the preferences
     * @param debugMode the debug mode flag
     * @return true, if successful
     */
    private boolean sendEmail(final BulkEmailBean bulkEmail, final EmailRecipientBean recipient,
            final UserBean user, final PreferencesBean preferences, final boolean debugMode) {

        boolean success = false;

        if (bulkEmail == null) {
            throw new NullPointerException("The bulk email bean cannot be null");
        }

        boolean updateRecipient = false;
        String logMessage = "No email address";

        EmailMessageBean message = null;
        try {
            message = this.prepareEmailMessage(bulkEmail, recipient, preferences, true, true);
        } catch (WhichDoctorDaoException wde) {
            dataLogger.error("Error generating message: " + wde.getMessage());
            logMessage = wde.getMessage();
        }

        if (recipient != null && recipient.getPending()) {
            // The message exists, there's a recipient, it is pending and has an address
            updateRecipient = true;
        }

        if (message != null) {
            // Override the recipient address is a user is supplied
            if (user != null) {
                message.setTo(user.getEmail());
            }

            if (StringUtils.isNotBlank(message.getTo()) && !debugMode) {
                try {
                    this.emailMessageDAO.send(message);
                    success = true;
                    logMessage = "";
                } catch (SFSDaoException sde) {
                    success = false;
                    dataLogger.error("Error sending bulk email message: " + sde.getMessage());
                    logMessage = "Error sending bulk email message: " + sde.getMessage();
                }
            }
        }

        if (updateRecipient) {
            // Update the email recipient entry
            this.emailRecipientDAO.update(recipient.getReferenceGUID(), recipient.getPersonGUID(),
                    recipient.getOrganisationGUID(), recipient.getCustomEmailAddress(), success, logMessage);
        }
        return success;
    }

}