mitm.application.djigzo.james.matchers.SenderHeaderTrigger.java Source code

Java tutorial

Introduction

Here is the source code for mitm.application.djigzo.james.matchers.SenderHeaderTrigger.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.matchers;

import java.util.Collection;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

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.DatabaseAction;
import mitm.common.hibernate.DatabaseActionExecutor;
import mitm.common.hibernate.DatabaseActionExecutorBuilder;
import mitm.common.hibernate.DatabaseException;
import mitm.common.hibernate.SessionManager;
import mitm.common.mail.EmailAddressUtils;
import mitm.common.properties.HierarchicalPropertiesException;

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

/**
 * Matcher that matches on a specific header and header value. The matcher condition is the 
 * name of the property used to load a trigger value from the senders properties. 
 * 
 * The property value must be a name value pair separated by ":"
 * 
 * Example:
 * 
 * X-SIGN : .*
 * 
 * If there is only a header name and no reg expression all header values will be accepted.
 * 
 * If the property value is empty or not set or the regular expression is not a valid 
 * regular expression this matcher does not match.
 * 
 * @author Martijn Brinkers
 *
 */
public class SenderHeaderTrigger extends AbstractHeaderValueRegEx {
    private final static Logger logger = LoggerFactory.getLogger(SenderHeaderTrigger.class);

    /*
     * The key under which we store the activation context
     */
    protected static final String ACTIVATION_CONTEXT_KEY = "trigger";

    /*
     * The number of times a database action should be retried when a ConstraintViolation occurs
     */
    private final static int ACTION_RETRIES = 3;

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

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

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

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

    /*
     * Property under which the pattern is stored
     */
    private String property;

    protected static class Context {
        private final String header;

        private final Pattern pattern;

        public Context(String header, Pattern pattern) {
            this.header = header;
            this.pattern = pattern;
        }

        public String getHeader() {
            return header;
        }

        public Pattern getPattern() {
            return pattern;
        }
    }

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

    @Override
    public void init() throws MessagingException {
        getLogger().info("Initializing matcher: " + getMatcherName());

        property = getCondition();

        if (StringUtils.isBlank(property)) {
            throw new MessagingException("property condition is missing.");
        }

        sessionManager = SystemServices.getSessionManager();

        userWorkflow = SystemServices.getUserWorkflow();

        messageOriginatorIdentifier = SystemServices.getMessageOriginatorIdentifier();

        actionExecutor = DatabaseActionExecutorBuilder.createDatabaseActionExecutor(sessionManager);

        assert (actionExecutor != null);
    }

    @Override
    protected String getHeader(Mail mail) throws MessagingException {
        Context context = getActivationContext().get(ACTIVATION_CONTEXT_KEY, Context.class);

        if (context == null) {
            return null;
        }

        return context.getHeader();
    }

    @Override
    protected Pattern getHeaderValuePattern(Mail mail) throws MessagingException {
        Context context = getActivationContext().get(ACTIVATION_CONTEXT_KEY, Context.class);

        if (context == null) {
            return null;
        }

        return context.getPattern();
    }

    private String getTrigger(final Mail mail) throws DatabaseException {
        /*
         * loadTriggerDetailsAction will be executed in a transaction. Under 'normal' circumstances this should never
         * result in a ConstraintViolationException. But, when a new user is added at the same time this action is executed
         * it can result in a ConstraintViolationException even though no data is written in loadTriggerDetailsAction.
         * We therefore retry at max. COMMIT_RETRIES times when a ConstraintViolationException occurs.
         */
        String triggerPattern = actionExecutor.executeTransaction(new DatabaseAction<String>() {
            @Override
            public String doAction(Session session) throws DatabaseException {
                Session previousSession = sessionManager.getSession();

                sessionManager.setSession(session);

                try {
                    return getTriggerAction(mail);
                } finally {
                    sessionManager.setSession(previousSession);
                }
            }
        }, ACTION_RETRIES);

        return triggerPattern;
    }

    private String getTriggerAction(Mail mail) throws DatabaseException {
        String trigger = null;

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

            if (originator != null) {
                String userEmail = originator.getAddress();

                userEmail = EmailAddressUtils.canonicalizeAndValidate(userEmail, false);

                User user = userWorkflow.getUser(userEmail, UserWorkflow.GetUserMode.CREATE_IF_NOT_EXIST);

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

                trigger = userProperties.getProperty(property, false);
            }

            return trigger;
        } catch (MessagingException e) {
            throw new DatabaseException(e);
        } catch (HierarchicalPropertiesException e) {
            throw new DatabaseException(e);
        }
    }

    @Override
    public Collection<MailAddress> matchMail(Mail mail) throws MessagingException {
        try {
            String trigger = getTrigger(mail);

            /*
             * Trigger must be a name value pair:
             * 
             * Header : Reg. Epxr
             * 
             * If there is only a header any value will be accepted 
             */

            if (StringUtils.isNotBlank(trigger)) {
                try {
                    String[] pair = StringUtils.stripAll(StringUtils.split(trigger, ":", 2));

                    Pattern pattern = Pattern.compile(pair.length > 1 ? pair[1] : ".*");

                    Context context = new Context(pair[0], pattern);

                    getActivationContext().set(ACTIVATION_CONTEXT_KEY, context);
                } catch (PatternSyntaxException e) {
                    logger.warn("Invalid pattern. Trigger: " + trigger, e);
                }
            }

            return super.matchMail(mail);
        } catch (DatabaseException e) {
            throw new MessagingException("Error getting pattern", e);
        }
    }
}