mitm.application.djigzo.james.mailets.SenderTemplatePropertySendMail.java Source code

Java tutorial

Introduction

Here is the source code for mitm.application.djigzo.james.mailets.SenderTemplatePropertySendMail.java

Source

/*
 * Copyright (c) 2008-2011, Martijn Brinkers, Djigzo.
 * 
 * This file is part of Djigzo email encryption.
 *
 * Djigzo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License 
 * version 3, 19 November 2007 as published by the Free Software 
 * Foundation.
 *
 * Djigzo 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 Djigzo. If not, see <http://www.gnu.org/licenses/>
 *
 * Additional permission under GNU AGPL version 3 section 7
 * 
 * If you modify this Program, or any covered work, by linking or 
 * combining it with aspectjrt.jar, aspectjweaver.jar, tyrex-1.0.3.jar, 
 * freemarker.jar, dom4j.jar, mx4j-jmx.jar, mx4j-tools.jar, 
 * spice-classman-1.0.jar, spice-loggerstore-0.5.jar, spice-salt-0.8.jar, 
 * spice-xmlpolicy-1.0.jar, saaj-api-1.3.jar, saaj-impl-1.3.jar, 
 * wsdl4j-1.6.1.jar (or modified versions of these libraries), 
 * containing parts covered by the terms of Eclipse Public License, 
 * tyrex license, freemarker license, dom4j license, mx4j license,
 * Spice Software License, Common Development and Distribution License
 * (CDDL), Common Public License (CPL) the licensors of this Program grant 
 * you additional permission to convey the resulting work.
 */
package mitm.application.djigzo.james.mailets;

import java.io.IOException;
import java.io.StringReader;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;

import mitm.application.djigzo.User;
import mitm.application.djigzo.UserProperties;
import mitm.application.djigzo.james.MessageOriginatorIdentifier;
import mitm.application.djigzo.service.SystemServices;
import mitm.application.djigzo.workflow.UserWorkflow;
import mitm.common.hibernate.DatabaseActionExecutor;
import mitm.common.hibernate.DatabaseActionExecutorBuilder;
import mitm.common.hibernate.DatabaseException;
import mitm.common.hibernate.DatabaseVoidAction;
import mitm.common.hibernate.SessionManager;
import mitm.common.properties.HierarchicalPropertiesException;

import org.apache.commons.lang.StringUtils;
import org.apache.mailet.Mail;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freemarker.template.SimpleHash;
import freemarker.template.Template;

/**
 * Extension of SendMailTemplate that makes it possible to read the template from the sender's properties
 * 
 * @author Martijn Brinkers
 *
 */
public class SenderTemplatePropertySendMail extends SendMailTemplate {
    private final static Logger logger = LoggerFactory.getLogger(SenderTemplatePropertySendMail.class);

    /*
     * The mailet initialization parameters used by this mailet.
     */
    private enum Parameter {
        USER_PROPERTY("userProperty"), TEMPLATE_PROPERTY("templateProperty");

        private String name;

        private Parameter(String name) {
            this.name = name;
        }
    };

    /*
     * The name of the property from which the template is read
     */
    private String templateProperty;

    /*
     * The user properties which will retrieved from the user and stored in the tempplate root.   
     */
    private String[] userProperties;

    /*
     * manages database sessions
     */
    protected SessionManager sessionManager;

    /*
     * Used for adding and retrieving users
     */
    protected UserWorkflow userWorkflow;

    /*
     * Is used to identify the 'sender' (from or enveloped sender or...) of the message
     */
    private MessageOriginatorIdentifier messageOriginatorIdentifier;

    /*
     * Used to execute database actions in a transaction
     */
    protected DatabaseActionExecutor actionExecutor;

    @Override
    protected Logger getLogger() {
        return logger;
    }

    private void initUserProperties() {
        String properties = getInitParameter(Parameter.USER_PROPERTY.name);

        if (StringUtils.isNotBlank(properties)) {
            userProperties = StringUtils.split(properties, ',');
        }
    }

    @Override
    public void initMailet() throws MessagingException {
        super.initMailet();

        templateProperty = getInitParameter(Parameter.TEMPLATE_PROPERTY.name);

        initUserProperties();

        sessionManager = SystemServices.getSessionManager();

        userWorkflow = SystemServices.getUserWorkflow();

        messageOriginatorIdentifier = SystemServices.getMessageOriginatorIdentifier();

        actionExecutor = DatabaseActionExecutorBuilder.createDatabaseActionExecutor(sessionManager);

        assert (actionExecutor != null);

        getLogger().info("templateProperty " + templateProperty);
    }

    /*
     * Reads the template from the user
     */
    protected Template getTemplateFromUser(User user, SimpleHash root)
            throws MessagingException, HierarchicalPropertiesException, IOException {
        Template template = null;

        UserProperties properties = user.getUserPreferences().getProperties();

        /*
         * Load the template from the user properties
         */
        String templateSource = properties.getProperty(templateProperty, false);

        if (templateSource != null) {
            StringReader reader = new StringReader(templateSource);

            template = getTemplateBuilder().createTemplate(reader);
        }

        return template;
    }

    /*
     * The template will be retrieved from the user property. If no template is available, the
     * static template specified in the mailet config will be used.
     * 
     * (non-Javadoc)
     * @see mitm.application.djigzo.james.mailets.SendMailTemplate#getTemplate(org.apache.mailet.Mail, 
     * freemarker.template.SimpleHash)
     */
    @Override
    protected Template getTemplate(Mail mail, final SimpleHash root) throws IOException, MessagingException {
        Template template = null;

        try {
            InternetAddress originator = messageOriginatorIdentifier.getOriginator(mail);

            if (templateProperty != null && originator != null) {
                User user = userWorkflow.getUser(originator.getAddress(),
                        UserWorkflow.GetUserMode.CREATE_IF_NOT_EXIST);

                template = getTemplateFromUser(user, root);

                /*
                 * Get the property values from the user so they can be stored in the template root
                 */
                if (userProperties != null) {
                    UserProperties properties = user.getUserPreferences().getProperties();

                    for (String userProperty : userProperties) {
                        userProperty = StringUtils.trimToNull(userProperty);

                        if (userProperty == null) {
                            continue;
                        }

                        String value = properties.getProperty(userProperty, false);

                        if (value != null) {
                            root.put(userProperty, value);
                        }
                    }
                }
            }

            if (template == null) {
                getLogger().debug("No template found for " + originator);
                /*
                 * The sender was not a valid user or did not have a template. Use the default static 
                 * template specified in the mailet config. 
                 */
                template = super.getTemplate(mail, root);
            }
        } catch (HierarchicalPropertiesException e) {
            throw new MessagingException("Error getting template.", e);
        }

        return template;
    }

    /*
     * serviceMail is overridden to wrap the serviceMail call in a database transaction. 
     * 
     * Note: method is made final to make sure that extensions of this class do not 'remove' the 
     * transaction mechnism
     */
    @Override
    final public void serviceMail(final Mail mail) {
        try {
            actionExecutor.executeTransaction(new DatabaseVoidAction() {
                @Override
                public void doAction(Session session) throws DatabaseException {
                    Session previousSession = sessionManager.getSession();

                    sessionManager.setSession(session);

                    try {
                        /*
                         * Call the super serviceMail method now wrapped in a transaction
                         */
                        SenderTemplatePropertySendMail.super.serviceMail(mail);
                    } finally {
                        sessionManager.setSession(previousSession);
                    }
                }
            });
        } catch (DatabaseException e) {
            getLogger().error("Database error servicing email.", e);
        }
    }

    public MessageOriginatorIdentifier getMessageOriginatorIdentifier() {
        return messageOriginatorIdentifier;
    }

    public UserWorkflow getUserWorkflow() {
        return userWorkflow;
    }
}