at.gv.egovernment.moa.id.configuration.helper.MailHelper.java Source code

Java tutorial

Introduction

Here is the source code for at.gv.egovernment.moa.id.configuration.helper.MailHelper.java

Source

/*******************************************************************************
 * Copyright 2014 Federal Chancellery Austria
 * MOA-ID has been developed in a cooperation between BRZ, the Federal
 * Chancellery Austria - ICT staff unit, and Graz University of Technology.
 *
 * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
 * the European Commission - subsequent versions of the EUPL (the "Licence");
 * You may not use this work except in compliance with the Licence.
 * You may obtain a copy of the Licence at:
 * http://www.osor.eu/eupl/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the Licence is distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Licence for the specific language governing permissions and
 * limitations under the Licence.
 *
 * This product combines work with different licenses. See the "NOTICE" text
 * file for details on the various modules and licenses.
 * The "NOTICE" text file is part of the distribution. Any derivative works
 * that you distribute must include a readable copy of the "NOTICE" text file.
 *******************************************************************************/
package at.gv.egovernment.moa.id.configuration.helper;

import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import at.gv.egovernment.moa.id.commons.db.dao.config.UserDatabase;
import at.gv.egovernment.moa.id.configuration.Constants;
import at.gv.egovernment.moa.id.configuration.config.ConfigurationProvider;
import at.gv.egovernment.moa.id.configuration.exception.ConfigurationException;
import at.gv.egovernment.moa.util.FileUtils;
import at.gv.egovernment.moa.util.MiscUtil;

public class MailHelper {

    private static final Logger log = Logger.getLogger(MailHelper.class);

    private static final String PATTERN_GIVENNAME = "#GIVENNAME#";
    private static final String PATTERN_FAMILYNAME = "#FAMILYNAME#";
    private static final String PATTERN_URL = "#MANDATE_SERVICE_LINK#";
    private static final String PATTERN_DATE = "#TODAY_DATE#";
    private static final String PATTERN_OPENOAS = "#NUMBER_OAS#";
    private static final String PATTERN_OPENUSERS = "#NUMBER_USERSS#";
    private static final String PATTERN_OANAME = "#OANAME#";

    public static void sendUserMailAddressVerification(UserDatabase userdb) throws ConfigurationException {

        ConfigurationProvider config = ConfigurationProvider.getInstance();
        String templateurl = config.getMailUserAcountVerificationTemplate();

        String template = readTemplateFromURL(templateurl, config.getConfigRootDir());

        if (userdb.isIsMandateUser() != null && userdb.isIsMandateUser()) {
            template = template.replace(PATTERN_GIVENNAME, userdb.getInstitut());
            template = template.replace(PATTERN_FAMILYNAME, "");

        } else {
            template = template.replace(PATTERN_GIVENNAME, userdb.getGivenname());
            template = template.replace(PATTERN_FAMILYNAME, userdb.getFamilyname());
        }

        SimpleDateFormat dateformat = new SimpleDateFormat("dd.MM.yyyy");
        template = template.replace(PATTERN_DATE, dateformat.format(new Date()));

        String verificationURL = config.getPublicUrlPreFix(null);

        if (!verificationURL.endsWith("/"))
            verificationURL = verificationURL + "/";

        verificationURL = verificationURL + Constants.SERVLET_ACCOUNTVERIFICATION + "?"
                + Constants.REQUEST_USERREQUESTTOKKEN + "=" + userdb.getUserRequestTokken();
        template = template.replace(PATTERN_URL, verificationURL);

        sendMail(config, config.getMailUserAcountVerificationSubject(), userdb.getMail(), template);

    }

    public static void sendAdminMail(int numOpenOAs, int numOpenUsers) throws ConfigurationException {
        ConfigurationProvider config = ConfigurationProvider.getInstance();
        String templateurl = config.getMailAdminTemplate();

        String template = readTemplateFromURL(templateurl, config.getConfigRootDir());
        template = template.replace(PATTERN_OPENOAS, String.valueOf(numOpenOAs));
        template = template.replace(PATTERN_OPENUSERS, String.valueOf(numOpenUsers));

        SimpleDateFormat dateformat = new SimpleDateFormat("dd.MM.yyyy");
        template = template.replace(PATTERN_DATE, dateformat.format(new Date()));

        sendMail(config, config.getMailAdminSubject(), config.getMailAdminAddress(), template);

    }

    public static void sendUserAccountActivationMail(String givenname, String familyname, String institut,
            String mailurl) throws ConfigurationException {
        ConfigurationProvider config = ConfigurationProvider.getInstance();
        String templateurl = config.getMailUserAcountActivationTemplate();

        String template = readTemplateFromURL(templateurl, config.getConfigRootDir());
        if (MiscUtil.isNotEmpty(institut)) {
            template = template.replace(PATTERN_GIVENNAME, institut);
            template = template.replace(PATTERN_FAMILYNAME, "");

        } else {
            template = template.replace(PATTERN_GIVENNAME, givenname);
            template = template.replace(PATTERN_FAMILYNAME, familyname);
        }

        SimpleDateFormat dateformat = new SimpleDateFormat("dd.MM.yyyy");
        template = template.replace(PATTERN_DATE, dateformat.format(new Date()));

        String verificationURL = config.getPublicUrlPreFix(null);
        if (!verificationURL.endsWith("/"))
            verificationURL = verificationURL + "/";

        template = template.replace(PATTERN_URL, verificationURL);

        sendMail(config, config.getMailUserAcountActivationSubject(), mailurl, template);
    }

    public static void sendUserOnlineApplicationActivationMail(String givenname, String familyname, String institut,
            String oaname, String mailurl) throws ConfigurationException {
        ConfigurationProvider config = ConfigurationProvider.getInstance();
        String templateurl = config.getMailOAActivationTemplate();

        String template = readTemplateFromURL(templateurl, config.getConfigRootDir());
        if (MiscUtil.isNotEmpty(institut)) {
            template = template.replace(PATTERN_GIVENNAME, institut);
            template = template.replace(PATTERN_FAMILYNAME, "");

        } else {
            template = template.replace(PATTERN_GIVENNAME, givenname);
            template = template.replace(PATTERN_FAMILYNAME, familyname);
        }

        template = template.replace(PATTERN_OANAME, oaname);

        SimpleDateFormat dateformat = new SimpleDateFormat("dd.MM.yyyy");
        template = template.replace(PATTERN_DATE, dateformat.format(new Date()));

        String verificationURL = config.getPublicUrlPreFix(null);
        if (!verificationURL.endsWith("/"))
            verificationURL = verificationURL + "/";

        template = template.replace(PATTERN_URL, verificationURL);

        sendMail(config, config.getMailOAActivationSubject(), mailurl, template);
    }

    public static void sendUserAccountRevocationMail(UserDatabase userdb) throws ConfigurationException {
        ConfigurationProvider config = ConfigurationProvider.getInstance();
        String templateurl = config.getMailUserAcountRevocationTemplate();

        String template = readTemplateFromURL(templateurl, config.getConfigRootDir());

        if (userdb.isIsMandateUser() != null && userdb.isIsMandateUser()) {
            template = template.replace(PATTERN_GIVENNAME, userdb.getInstitut());
            template = template.replace(PATTERN_FAMILYNAME, "");

        } else {
            template = template.replace(PATTERN_GIVENNAME, userdb.getGivenname());
            template = template.replace(PATTERN_FAMILYNAME, userdb.getFamilyname());
        }

        SimpleDateFormat dateformat = new SimpleDateFormat("dd.MM.yyyy");
        template = template.replace(PATTERN_DATE, dateformat.format(new Date()));

        sendMail(config, config.getMailUserAcountActivationSubject(), userdb.getMail(), template);
    }

    private static String readTemplateFromURL(String templateurl, String rootDir) throws ConfigurationException {
        InputStream input;
        try {

            URL keystoreURL = new URL(FileUtils.makeAbsoluteURL(templateurl, rootDir));
            input = keystoreURL.openStream();
            StringWriter writer = new StringWriter();
            IOUtils.copy(input, writer);
            input.close();
            return writer.toString();

        } catch (Exception e) {
            log.warn("Mailtemplate can not be read from source" + templateurl);
            throw new ConfigurationException("Mailtemplate can not be read from source" + templateurl);

        }
    }

    private static void sendMail(ConfigurationProvider config, String subject, String recipient, String content)
            throws ConfigurationException {
        try {
            log.debug("Sending mail.");
            MiscUtil.assertNotNull(subject, "subject");
            MiscUtil.assertNotNull(recipient, "recipient");
            MiscUtil.assertNotNull(content, "content");

            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.host", config.getSMTPMailHost());
            log.trace("Mail host: " + config.getSMTPMailHost());
            if (config.getSMTPMailPort() != null) {
                log.trace("Mail port: " + config.getSMTPMailPort());
                props.setProperty("mail.port", config.getSMTPMailPort());
            }
            if (config.getSMTPMailUsername() != null) {
                log.trace("Mail user: " + config.getSMTPMailUsername());
                props.setProperty("mail.user", config.getSMTPMailUsername());
            }
            if (config.getSMTPMailPassword() != null) {
                log.trace("Mail password: " + config.getSMTPMailPassword());
                props.setProperty("mail.password", config.getSMTPMailPassword());
            }

            Session mailSession = Session.getDefaultInstance(props, null);
            Transport transport = mailSession.getTransport();

            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject(subject);
            log.trace("Mail from: " + config.getMailFromName() + "/" + config.getMailFromAddress());
            message.setFrom(new InternetAddress(config.getMailFromAddress(), config.getMailFromName()));
            log.trace("Recipient: " + recipient);
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

            log.trace("Creating multipart content of mail.");
            MimeMultipart multipart = new MimeMultipart("related");

            log.trace("Adding first part (html)");
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(content, "text/html; charset=ISO-8859-15");
            multipart.addBodyPart(messageBodyPart);

            //         log.trace("Adding mail images");
            //         messageBodyPart = new MimeBodyPart();
            //         for (Image image : images) {
            //            messageBodyPart.setDataHandler(new DataHandler(image));
            //            messageBodyPart.setHeader("Content-ID", "<" + image.getContentId() + ">");
            //            multipart.addBodyPart(messageBodyPart);
            //         }

            message.setContent(multipart);
            transport.connect();
            log.trace("Sending mail message.");
            transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
            log.trace("Successfully sent.");
            transport.close();

        } catch (MessagingException e) {
            throw new ConfigurationException(e);

        } catch (UnsupportedEncodingException e) {
            throw new ConfigurationException(e);

        }
    }
}