edu.byu.softwareDist.manager.impl.SendEmailImpl.java Source code

Java tutorial

Introduction

Here is the source code for edu.byu.softwareDist.manager.impl.SendEmailImpl.java

Source

package edu.byu.softwareDist.manager.impl;

import edu.byu.edge.person.basic.BasicPersonLookup;
import edu.byu.edge.person.basic.EmailAddressLookup;
import edu.byu.edge.person.basic.domain.BasicPerson;
import edu.byu.edge.person.basic.domain.Email;
import edu.byu.security.userdetails.IdentityDetails;
import edu.byu.softwareDist.domain.FileSet;
import edu.byu.softwareDist.domain.Purchase;
import edu.byu.softwareDist.domain.PurchaseLineItem;
import edu.byu.softwareDist.manager.SendEmail;
import edu.byu.spring.ByuAppStage;
import org.apache.log4j.Logger;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
import org.springframework.ui.velocity.VelocityEngineUtils;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

@Service("sendEmail")
public class SendEmailImpl implements SendEmail {

    private final static String fromEmail = "it@byu.edu";
    private final static String subject = "Order Confirmation";
    private final static SimpleDateFormat dateFmt = new SimpleDateFormat("MMMM dd, yyyy");
    private static final Logger LOG = Logger.getLogger(SendEmailImpl.class);

    private JavaMailSender mailSender;

    @Autowired
    @Qualifier("emailLookup")
    private EmailAddressLookup emailAddressLookup;

    @Autowired
    @Qualifier("basicPersonLookup")
    private BasicPersonLookup basicPersonLookup;

    @Autowired
    private VelocityEngine velocityEngine;

    @Autowired
    @Qualifier("emailAppStage")
    private ByuAppStage appStage;

    @Autowired
    public SendEmailImpl(JavaMailSenderImpl javaMailSender) {
        this.mailSender = javaMailSender;
    }

    @Override
    public void sendEmail(final Purchase purchase) {
        LOG.debug("Sending email.....");
        mailSender.send(new EmailPreparation("/softwareDistribution/email/purchase.vm", purchase));
        LOG.debug("Email was sent!");
    }

    @Override
    public void sendEmail(final PurchaseLineItem purchaseLineItem, final FileSet fileSet) {
        LOG.debug("Checking for Product Email");
        if (!fileSet.isEmailDefined()) {
            return;
        }
        final File template = saveTemplateToDisk(fileSet);
        if (template == null)
            return;

        try {
            mailSender.send(new EmailProductPreparation(template.getAbsolutePath(), purchaseLineItem, fileSet));
        } finally {
            template.delete();
        }

        LOG.debug("Generated Product Email");
    }

    @Override
    public void sendEmail(final PurchaseLineItem purchaseLineItem) {
        LOG.debug("Sending email...");
        mailSender.send(new CreditCardEmailPreparation(purchaseLineItem));
        LOG.debug("Email was sent!");
    }

    @Override
    public void sendEmail(final String productName, final Integer numberOfLicenses) {
        LOG.debug("Sending email.....");
        mailSender.send(new LowLicenseEmailPreparation(productName, numberOfLicenses));
        LOG.debug("Email was sent!");
    }

    private static File saveTemplateToDisk(final FileSet fileSet) {
        File f = null;
        PrintStream out = null;
        try {
            f = File.createTempFile("software-distribution-email-content." + fileSet.getFileSetId() + "-", ".vm");
            out = new PrintStream(new FileOutputStream(f));
            out.print(fileSet.getEmailContent());
            out.flush();
            return f;
        } catch (IOException e) {
            LOG.error("Error writing template to temporary file.", e);
            return null;
        } finally {
            if (f != null) {
                f.deleteOnExit();
            }
            if (out != null) {
                out.close();
            }
        }
    }

    private class EmailProductPreparation implements MimeMessagePreparator {
        private final String template;
        private final PurchaseLineItem purchaseLineItem;
        private final FileSet fileset;

        private EmailProductPreparation(String template, PurchaseLineItem purchaseLineItem, FileSet fileset) {
            this.template = template;
            this.purchaseLineItem = purchaseLineItem;
            this.fileset = fileset;
        }

        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            if (appStage.isInProd()) {
                helper.setTo(fileset.getSendEmailTo());
            } else {
                helper.setTo(IdentityDetails.getCurrentIdentityDetails().getEmailAddress());
            }
            helper.setSubject(fileset.getEmailSubject());
            helper.setFrom(fromEmail);
            helper.setReplyTo(fromEmail);
            Map<String, Object> map = new HashMap<String, Object>();
            final PurchaseFor purchaseFor = new PurchaseFor(purchaseLineItem);
            map.put("emailAddress", purchaseFor.getEmailAddress());
            map.put("netId", purchaseFor.getNetId());
            map.put("name", purchaseFor.getName());
            map.put("product", purchaseLineItem.getProduct().getName());
            map.put("quantity", purchaseLineItem.getQty());
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, map);
            helper.setText(text, true);

        }
    }

    private class EmailPreparation implements MimeMessagePreparator {
        private final IdentityDetails student;
        private final String template;
        private final Purchase purchase;

        public EmailPreparation(String template, Purchase purchase) {
            this.template = template;
            this.student = IdentityDetails.getCurrentIdentityDetails();
            this.purchase = purchase;
        }

        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setTo(student.getEmailAddress());
            helper.setFrom(fromEmail);
            helper.setReplyTo(fromEmail);
            helper.setSubject(subject);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("student", student);
            map.put("purchase", purchase);
            map.put("purchaseDate", dateFmt.format(purchase.getPurchaseDate()));

            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, map);
            helper.setText(text, true);
        }
    }

    private class CreditCardEmailPreparation implements MimeMessagePreparator {

        private PurchaseLineItem purchaseLineItem;

        private CreditCardEmailPreparation(PurchaseLineItem purchaseLineItem) {
            this.purchaseLineItem = purchaseLineItem;
        }

        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            if (appStage.isInProd()) {
                helper.setTo("ccrefunds@byu.edu");
            } else {
                helper.setTo(IdentityDetails.getCurrentIdentityDetails().getEmailAddress());
            }
            helper.setFrom(fromEmail);
            helper.setReplyTo(fromEmail);
            helper.setSubject("Credit Card Refund");
            Map<String, Object> map = new HashMap<String, Object>();
            final PurchaseFor purchaseFor = new PurchaseFor(purchaseLineItem);
            map.put("name", purchaseFor.getName());
            map.put("netId", purchaseFor.getNetId());
            map.put("emailAddress", purchaseFor.getEmailAddress());
            map.put("product", purchaseLineItem.getProduct().getName());
            map.put("quantity", purchaseLineItem.getQty());
            map.put("price", purchaseLineItem.getUnitPrice());
            map.put("cashnetId", purchaseLineItem.getCashNetId());

            final String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "/softwareDistribution/email/products/CreditCardReturn.vm", map);
            helper.setText(text, true);
        }
    }

    private class LowLicenseEmailPreparation implements MimeMessagePreparator {

        private String productName;
        private Integer numberOfLicenses;

        private LowLicenseEmailPreparation(String productName, Integer numberOfLicenses) {
            this.productName = productName;
            this.numberOfLicenses = numberOfLicenses;
        }

        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            if (appStage.isInProd()) {
                helper.setTo("software@byu.edu");
            } else {
                helper.setTo(IdentityDetails.getCurrentIdentityDetails().getEmailAddress());
            }
            helper.setFrom(fromEmail);
            helper.setReplyTo(fromEmail);
            helper.setSubject("Low License For Product");
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("productName", productName);
            map.put("numberOfLicenses", numberOfLicenses);
            final String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                    "/softwareDistribution/email/License.vm", map);
            helper.setText(text, true);
        }
    }

    private class PurchaseFor {
        private String netId;
        private String emailAddress;
        private String name;

        private PurchaseFor(final PurchaseLineItem purchaseLineItem) {
            final BasicPerson basicPerson = basicPersonLookup
                    .getPersonByPersonId(purchaseLineItem.getPurchasedFor());
            final Email email = emailAddressLookup.getByPersonId(purchaseLineItem.getPurchasedFor());
            this.netId = basicPerson.getNetId();
            this.emailAddress = email.getEmailAddress();
            this.name = basicPerson.getName();
        }

        public String getNetId() {
            return netId;
        }

        public void setNetId(String netId) {
            this.netId = netId;
        }

        public String getEmailAddress() {
            return emailAddress;
        }

        public void setEmailAddress(String emailAddress) {
            this.emailAddress = emailAddress;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}