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

Java tutorial

Introduction

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

Source

/*
 * Copyright (c) 2008-2012, 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 javax.mail.MessagingException;

import mitm.application.djigzo.james.DjigzoMailAttributesImpl;
import mitm.common.util.LogLevel;
import mitm.common.util.ThreadAwareContext;

import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.text.StrBuilder;
import org.apache.mailet.GenericMailet;
import org.apache.mailet.Mail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Extension of GenericMailet which adds some basic functionality shared by all Djigzo Mailets.
 *
 * The following initialization parameters are supported by AbstractDjigzoMailet.
 *
 * log                    : Log message
 * logLevel               : The log level of the log message (one of INFO, WARN, ERROR, DEBUG)
 * catchRuntimeExceptions : If true the service handler of the mailet catches RuntimeException's
 * catchErrors            : If true the service handler of the mailet catches Error's
 *
 * @author Martijn Brinkers
 *
 */
public abstract class AbstractDjigzoMailet extends GenericMailet {
    /*
     * The logger to be used for logging the log parameter message. This is done to allow all the logs to be changed
     * at once. Only the log message from the mailet config (see log parameter) is logged with this logger. Classes
     * extending AbstractDjigzoMailet should use #getLogger()
     */
    private final static Logger logLogger = LoggerFactory
            .getLogger("mitm.application.djigzo.james.mailets.Default");

    /*
     * The activationContext can be used to store objects used in the matcher in a thread safe way.
     */
    private ThreadAwareContext activationContext = new ThreadAwareContext();

    public ThreadAwareContext getActivationContext() {
        return activationContext;
    }

    /*
     * The log message to show when the mailet is executed
     */
    private String log;

    /*
     * logLevel used for logging log message (see above)
     */
    private LogLevel logLevel;

    /*
      * If true RuntimeExceptions are caught.
      */
    private boolean catchRuntimeExceptions = true;

    /*
     * If true Errors are caught.
     */
    private boolean catchErrors = true;

    /*
     * The mailet initialization parameters used by this mailet.
     */
    private enum Parameter {
        LOG("log"), LOG_LEVEL("logLevel"), CATCH_RUNTIMEEXCEPTIONS("catchRuntimeExceptions"), CATCH_ERRORS(
                "catchErrors");

        private String name;

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

    abstract protected Logger getLogger();

    protected LogLevel getLogLevel() {
        return logLevel;
    }

    protected void setLogLevel(LogLevel logLevel) {
        this.logLevel = logLevel;
    }

    protected boolean isCatchRuntimeExceptions() {
        return catchRuntimeExceptions;
    }

    protected boolean isCatchErrors() {
        return catchErrors;
    }

    protected String getLog() {
        return log;
    }

    protected Integer getIntegerInitParameter(String name, Integer defaultIfEmpty) {
        Integer value = defaultIfEmpty;

        String parameter = getInitParameter(name);

        if (StringUtils.isNotEmpty(parameter)) {
            value = Integer.parseInt(parameter);
        }

        return value;
    }

    protected Long getLongInitParameter(String name, Long defaultIfEmpty) {
        Long value = defaultIfEmpty;

        String parameter = getInitParameter(name);

        if (StringUtils.isNotEmpty(parameter)) {
            value = Long.parseLong(parameter);
        }

        return value;
    }

    protected Boolean getBooleanInitParameter(String name, Boolean defaultIfEmpty) {
        Boolean value = defaultIfEmpty;

        String parameter = getInitParameter(name);

        if (StringUtils.isNotEmpty(parameter)) {
            value = BooleanUtils.toBooleanObject(parameter);

            if (value == null) {
                throw new IllegalArgumentException(parameter + " is not a valid boolean value.");
            }
        }

        return value;
    }

    @Override
    public final void init() throws MessagingException {
        log = getInitParameter(Parameter.LOG.name);

        String param = getInitParameter(Parameter.LOG_LEVEL.name);

        if (param != null) {
            logLevel = LogLevel.valueOf(param.trim().toUpperCase());
        }

        if (logLevel == null) {
            logLevel = LogLevel.INFO;
        }

        param = getInitParameter(Parameter.CATCH_RUNTIMEEXCEPTIONS.name);

        if (param != null) {
            Boolean bool = BooleanUtils.toBooleanObject(param);

            if (bool == null) {
                throw new IllegalArgumentException(param + " is not a valid boolean.");
            }

            catchRuntimeExceptions = bool;
        }

        param = getInitParameter(Parameter.CATCH_ERRORS.name);

        if (param != null) {
            Boolean bool = BooleanUtils.toBooleanObject(param);

            if (bool == null) {
                throw new IllegalArgumentException(param + " is not a valid boolean.");
            }

            catchErrors = bool;
        }

        StrBuilder sb = new StrBuilder();

        sb.append("catchRuntimeExceptions: ");
        sb.append(catchRuntimeExceptions);
        sb.append("; ");
        sb.append("catchErrors: ");
        sb.append(catchErrors);

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

        initMailet();
    }

    protected void initMailet() throws MessagingException {
        // override to add behavior.
    }

    private void logMessage(String message) {
        switch (getLogLevel()) {
        case WARN:
            logLogger.warn(message);
            return;
        case ERROR:
            logLogger.error(message);
            return;
        case DEBUG:
            logLogger.debug(message);
            return;
        case TRACE:
            logLogger.trace(message);
            return;
        default:
            break;
        }

        /*
         * Default info level
         */
        logLogger.info(message);
    }

    @Override
    public final void service(Mail mail) {
        try {
            String log = getLog();

            if (log != null) {
                StrBuilder sb = new StrBuilder();

                sb.append(log);

                String mailID = DjigzoMailAttributesImpl.getInstance(mail).getMailID();

                if (mailID != null) {
                    sb.append("; MailID: ").append(mailID);
                }

                logMessage(sb.toString());
            }

            try {
                serviceMail(mail);
            } finally {
                activationContext.clear();
            }
        } catch (RuntimeException e) {
            getLogger().error("Unhandled RuntimeException.", e);

            if (!isCatchRuntimeExceptions()) {
                throw e;
            }
        } catch (Error e) {
            getLogger().error("Unhandled Error.", e);

            if (!isCatchErrors()) {
                throw e;
            }
        }
    }

    public abstract void serviceMail(Mail mail);
}