mitm.common.net.HTTPMethodExecutor.java Source code

Java tutorial

Introduction

Here is the source code for mitm.common.net.HTTPMethodExecutor.java

Source

/*
 * Copyright (c) 2010-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.common.net;

import java.io.IOException;

import mitm.common.scheduler.HTTPMethodAbortTimeoutTask;
import mitm.common.scheduler.Task;
import mitm.common.scheduler.TaskScheduler;
import mitm.common.scheduler.ThreadInterruptTimeoutTask;
import mitm.common.util.Check;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Helper class which can be used to execute HttpMethod's. The execute is protected with a watchdog to make sure that 
 * the connection will be interrupted when the connection takes too long.
 * 
 * @author Martijn Brinkers
 *
 */
public class HTTPMethodExecutor {
    private final static Logger logger = LoggerFactory.getLogger(HTTPMethodExecutor.class);

    private static final String TIMEOUT_ERROR = "A timeout has occured while executing the HTTP method. URI: ";

    /* 
     * max time in milliseconds the total HTTP call may take
     */
    private int totalTimeout;

    /* 
     * max time in milliseconds the HTTP connection may take
     */
    private int connectTimeout;

    /* 
     * socket read timeout in milliseconds
     */
    private int readTimeout;

    /*
     * Used to set the proxy for HttpClient
     */
    private final ProxyInjector proxyInjector;

    public static interface ResponseHandler {
        public void handleResponse(int statusCode, HttpMethod httpMethod, TaskScheduler watchdog)
                throws IOException;
    }

    public HTTPMethodExecutor(int totalTimeout, ProxyInjector proxyInjector) {
        if (totalTimeout <= 0) {
            throw new IllegalArgumentException("totalTimeout should be > 0");
        }

        this.totalTimeout = totalTimeout;
        this.proxyInjector = proxyInjector;
    }

    protected HttpClient createHttpClient() {
        return new HttpClient();
    }

    protected void initDefaultSettings(HttpMethod httpMethod) {
        httpMethod.setRequestHeader("User-Agent", NetUtils.HTTP_USER_AGENT);
    }

    protected void internalExecuteMethod(HttpMethod httpMethod, ResponseHandler responseHandler,
            TaskScheduler watchdog) throws IOException {
        HttpClient httpClient = createHttpClient();

        HttpConnectionManagerParams params = httpClient.getHttpConnectionManager().getParams();

        if (connectTimeout > 0) {
            params.setConnectionTimeout(connectTimeout);
        }

        if (readTimeout > 0) {
            params.setSoTimeout(readTimeout);
        }

        if (proxyInjector != null) {
            try {
                proxyInjector.setProxy(httpClient);
            } catch (ProxyException e) {
                throw new IOException(e);
            }
        }

        initDefaultSettings(httpMethod);

        /* 
         * Add last resort watchdog that will interrupt the thread on timeout. we want the abort the HTTP method 
         * first so add 50% to totalTimeout.
         */
        Task threadWatchdogTask = new ThreadInterruptTimeoutTask(Thread.currentThread(), watchdog.getName());
        watchdog.addTask(threadWatchdogTask, (long) (totalTimeout * 1.5));

        /* 
         * Add watchdog that will abort the HTTPMethod on timeout. 
         */
        Task httpMethodAbortTimeoutTask = new HTTPMethodAbortTimeoutTask(httpMethod, watchdog.getName());
        watchdog.addTask(httpMethodAbortTimeoutTask, (long) (totalTimeout));

        try {
            logger.debug("Setting up a connection to: " + httpMethod.getURI());

            int statusCode = 0;

            try {
                statusCode = httpClient.executeMethod(httpMethod);
            } catch (IllegalArgumentException e) {
                /* 
                 * HttpClient can throw IllegalArgumentException when the host is not set 
                 */
                throw new IOException(e);
            }

            responseHandler.handleResponse(statusCode, httpMethod, watchdog);

            if (threadWatchdogTask.hasRun() || httpMethodAbortTimeoutTask.hasRun()) {
                /* 
                 * a timeout has occurred. In most cases, a exception was probably already thrown because the 
                 * connection was forcefully closed.  
                 */
                throw new IOException(TIMEOUT_ERROR + httpMethod.getURI());
            }

        } finally {
            httpMethod.releaseConnection();
        }
    }

    public void executeMethod(HttpMethod httpMethod, ResponseHandler responseHandler) throws IOException {
        Check.notNull(httpMethod, "httpMethod");
        Check.notNull(responseHandler, "responseHandler");

        TaskScheduler watchdog = new TaskScheduler(HTTPMethodExecutor.class.getCanonicalName());

        try {
            internalExecuteMethod(httpMethod, responseHandler, watchdog);
        } finally {
            /* 
             * we must cancel the watchdogs
             */
            watchdog.cancel();
        }
    }

    public int getTotalTimeout() {
        return totalTimeout;
    }

    public void setTotalTimeout(int totalTimeout) {
        this.totalTimeout = totalTimeout;
    }

    public int getConnectTimeout() {
        return connectTimeout;
    }

    public void setConnectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public int getReadTimeout() {
        return readTimeout;
    }

    public void setReadTimeout(int readTimeout) {
        this.readTimeout = readTimeout;
    }
}