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

Java tutorial

Introduction

Here is the source code for mitm.application.djigzo.james.matchers.SubjectTrigger.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.io.IOException;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import mitm.application.djigzo.james.DjigzoMailAttributes;
import mitm.application.djigzo.james.DjigzoMailAttributesImpl;

import org.apache.commons.lang.text.StrBuilder;
import org.apache.mailet.Mail;
import org.apache.mailet.MailAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A Matcher that matches the subject against a regular expression. The matching pattern is removed from the subject.
 * This is a side effect of this matcher, which matchers normally should not have, because matchers should only match 
 * and not modify the message. Because of optimizations I decided to accept this side effect. 
 * 
 * Usage:
 * 
 * SubjectTrigger=matchOnError=false,(?i)test | Matches when the subject contains test (case insensitive)
 * 
 * If matchOnError is true, this matcher matches when an exception has been thrown by the matcher and
 * vice versa.
 * 
 * Note: A possible solution to the mentioned side effect that does not require to match the subject twice
 * is to add the filtered subject as a mail property and create a mailet that replaces the subject with
 * the subject from the property.
 * 
 * @author Martijn Brinkers
 *
 */
public class SubjectTrigger extends AbstractHeaderValueRegEx {
    private final static Logger logger = LoggerFactory.getLogger(SubjectTrigger.class);

    /*
     * How many levels of trigger depth are we going to check
     */
    private final static int MAX_SUBJECT_RECURSIVE_DEPTH = 3;

    /*
     * The subject when the max recursion depth has been reached
     */
    protected final static String MAX_SUBJECT_RECURSIVE_DEPTH_REACHED = "Subject removed. Max recursion level reached.";

    /*
     * The pattern which is matched against the subject
     */
    private Pattern subjectPattern;

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

    protected String getSubjectExpression() {
        return getCondition();
    }

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

        String expression = getSubjectExpression();

        if (expression == null || "".equals(expression)) {
            throw new IllegalArgumentException("Expression is missing.");
        }

        subjectPattern = Pattern.compile(expression);

        StrBuilder sb = new StrBuilder();

        sb.append("subjectPattern: ");
        sb.append(subjectPattern);

        getLogger().info(sb.toString());
    }

    private String removePatternFromSubject(String subject, Matcher matcher, int level) {
        subject = matcher.replaceAll("");

        /*
         * We need to check if the new subject does not contain the pattern again.
         */
        matcher.reset(subject);

        if (matcher.find()) {
            if (level < MAX_SUBJECT_RECURSIVE_DEPTH) {
                /*
                 * Recusively remove pattern
                 */
                subject = removePatternFromSubject(subject, matcher, ++level);
            } else {
                logger.warn(MAX_SUBJECT_RECURSIVE_DEPTH_REACHED);

                subject = MAX_SUBJECT_RECURSIVE_DEPTH_REACHED;
            }
        }

        return subject;
    }

    /*
     * Removes the matching part from the subject.
     */
    protected void removePattern(Mail mail, Matcher matcher) throws MessagingException, IOException {
        MimeMessage message = mail.getMessage();

        String subject = message.getSubject();

        /*
         * Store the subject in the Mail attributes before we remove the pattern from the subject. 
         * This will allow other mailets/matchers to get the original subject.
         * 
         * TODO: make the attribute under which the subject should be set, a parameter of the
         * matcher.
         */
        DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail);

        /*
         * Only set the original subject if it has not yet been set
         */
        if (mailAttributes.getOriginalSubject() == null) {
            mailAttributes.setOriginalSubject(subject);
        }

        subject = removePatternFromSubject(subject, matcher, 1);

        message.setSubject(subject);
    }

    @Override
    protected Collection<MailAddress> onMatch(Mail mail, Matcher matcher) throws MessagingException, IOException {
        /*
         * Remove the pattern from the subject.
         */
        removePattern(mail, matcher);

        return super.onMatch(mail, matcher);
    }

    @Override
    protected String getHeader(Mail mail) throws MessagingException {
        return "subject";
    }

    @Override
    protected Pattern getHeaderValuePattern(Mail mail) throws MessagingException {
        return subjectPattern;
    }
}