Example usage for org.apache.commons.httpclient HttpMethod abort

List of usage examples for org.apache.commons.httpclient HttpMethod abort

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod abort.

Prototype

public abstract void abort();

Source Link

Usage

From source file:nl.nn.adapterframework.http.HttpSender.java

public String sendMessageWithTimeoutGuarded(String correlationID, String message,
        ParameterResolutionContext prc) throws SenderException, TimeOutException {
    ParameterValueList pvl = null;/*from w w  w. jav a  2 s  .  c om*/
    try {
        if (prc != null && paramList != null) {
            pvl = prc.getValues(paramList);
        }
    } catch (ParameterException e) {
        throw new SenderException(
                getLogPrefix() + "Sender [" + getName() + "] caught exception evaluating parameters", e);
    }
    URI uri;
    HttpMethod httpmethod;
    HostConfiguration hostconfiguration = new HostConfiguration(hostconfigurationBase);
    try {
        if (urlParameter != null) {
            String url = (String) pvl.getParameterValue(getUrlParam()).getValue();
            uri = getURI(url);
        } else {
            uri = staticUri;
        }

        Map<String, String> headersParamsMap = new HashMap<String, String>();
        if (headersParams != null) {
            StringTokenizer st = new StringTokenizer(headersParams, ",");
            while (st.hasMoreElements()) {
                headersParamsMap.put(st.nextToken(), null);
            }
        }

        if (!isParamsInUrl()) {
            httpmethod = getPostMethodWithParamsInBody(uri, message, pvl, headersParamsMap, prc);
        } else {
            httpmethod = getMethod(uri, message, pvl, headersParamsMap);
            if (!"POST".equals(getMethodType()) && !"PUT".equals(getMethodType())
                    && !"REPORT".equals(getMethodType())) {
                httpmethod.setFollowRedirects(isFollowRedirects());
            }
        }

        int port = getPort(uri);

        if (socketfactory != null && "https".equals(uri.getScheme())) {
            Protocol authhttps = new Protocol(uri.getScheme(), socketfactory, port);
            hostconfiguration.setHost(uri.getHost(), port, authhttps);
        } else {
            hostconfiguration.setHost(uri.getHost(), port, uri.getScheme());
        }
        log.info(getLogPrefix() + "configured httpclient for host [" + hostconfiguration.getHostURL() + "]");

        if (credentials != null) {
            httpState.setCredentials(null, uri.getHost(), credentials);
        }
    } catch (URIException e) {
        throw new SenderException(e);
    }

    String result = null;
    int statusCode = -1;
    int count = getMaxExecuteRetries();
    String msg = null;
    while (count-- >= 0 && statusCode == -1) {
        try {
            if (log.isDebugEnabled())
                log.debug(getLogPrefix() + "executing method");
            statusCode = httpclient.executeMethod(hostconfiguration, httpmethod, httpState);
            if (log.isDebugEnabled())
                log.debug(getLogPrefix() + "executed method");

            if (statusCode != HttpServletResponse.SC_OK) {
                StatusLine statusline = httpmethod.getStatusLine();
                if (statusline != null) {
                    log.warn(getLogPrefix() + "status [" + statusline.toString() + "]");
                } else {
                    log.warn(getLogPrefix() + "no statusline found");
                }
            } else {
                if (log.isDebugEnabled())
                    log.debug(getLogPrefix() + "status [" + statusCode + "]");
            }
            HttpServletResponse response = null;
            if (isStreamResultToServlet()) {
                response = (HttpServletResponse) prc.getSession().get("restListenerServletResponse");
            }
            String fileName = null;
            if (StringUtils.isNotEmpty(getStreamResultToFileNameSessionKey())) {
                fileName = (String) prc.getSession().get(getStreamResultToFileNameSessionKey());
            }
            result = extractResult(httpmethod, prc, response, fileName);
            if (log.isDebugEnabled())
                log.debug(getLogPrefix() + "retrieved result [" + result + "]");
        } catch (HttpException e) {
            Throwable throwable = e.getCause();
            String cause = null;
            if (throwable != null) {
                cause = throwable.toString();
            }
            msg = e.getMessage();
            log.warn(getLogPrefix() + "httpException with message [" + msg + "] and cause [" + cause
                    + "], executeRetries left [" + count + "]");
        } catch (IOException e) {
            httpmethod.abort();
            if (e instanceof SocketTimeoutException) {
                throw new TimeOutException(e);
            }
            throw new SenderException(e);
        } finally {
            // In case of storeResultAsStreamInSessionKey release connection
            // is done by ReleaseConnectionAfterReadInputStream.
            if (StringUtils.isEmpty(getStoreResultAsStreamInSessionKey())) {
                httpmethod.releaseConnection();
            }
        }
    }

    if (statusCode == -1) {
        if (StringUtils.contains(msg.toUpperCase(), "TIMEOUTEXCEPTION")) {
            //java.net.SocketTimeoutException: Read timed out
            throw new TimeOutException("Failed to recover from timeout exception");
        }
        throw new SenderException("Failed to recover from exception");
    }

    if (isXhtml() && StringUtils.isNotEmpty(result)) {
        result = XmlUtils.skipDocTypeDeclaration(result.trim());
        if (result.startsWith("<html>") || result.startsWith("<html ")) {
            CleanerProperties props = new CleanerProperties();
            HtmlCleaner cleaner = new HtmlCleaner(props);
            TagNode tagNode = cleaner.clean(result);
            result = new SimpleXmlSerializer(props).getXmlAsString(tagNode);

            if (transformerPool != null) {
                log.debug(getLogPrefix() + " transforming result [" + result + "]");
                ParameterResolutionContext prc_xslt = new ParameterResolutionContext(result, null, true, true);
                try {
                    result = transformerPool.transform(prc_xslt.getInputSource(), null);
                } catch (Exception e) {
                    throw new SenderException("Exception on transforming input", e);
                }
            }
        }
    }
    return result;
}

From source file:org.archive.wayback.liveweb.ArcRemoteLiveWebCache.java

public Resource getCachedResource(URL url, long maxCacheMS, boolean bUseOlder)
        throws LiveDocumentNotAvailableException, LiveWebCacheUnavailableException, LiveWebTimeoutException,
        IOException {//from   ww  w.j  a v a  2 s  .co m
    String urlString = url.toExternalForm();

    if (requestPrefix != null) {
        urlString = requestPrefix + urlString;
    }

    HttpMethod method = null;
    try {
        method = new GetMethod(urlString);
    } catch (IllegalArgumentException e) {
        LOGGER.warning("Bad URL for live web fetch:" + urlString);
        throw new LiveDocumentNotAvailableException("Url:" + urlString + "does not look like an URL?");
    }
    boolean success = false;
    try {
        int status = http.executeMethod(method);
        if (status == 200) {

            ByteArrayInputStream bais = new ByteArrayInputStream(method.getResponseBody());
            ARCRecord r = new ARCRecord(new GZIPInputStream(bais), "id", 0L, false, false, true);
            ArcResource ar = (ArcResource) ResourceFactory.ARCArchiveRecordToResource(r, null);
            if (ar.getStatusCode() == 502) {
                throw new LiveDocumentNotAvailableException(urlString);
            } else if (ar.getStatusCode() == 504) {
                throw new LiveWebTimeoutException("Timeout:" + urlString);
            }
            success = true;
            return ar;

        } else {
            throw new LiveWebCacheUnavailableException(urlString);
        }

    } catch (ResourceNotAvailableException e) {
        throw new LiveDocumentNotAvailableException(urlString);

    } catch (NoHttpResponseException e) {

        throw new LiveWebCacheUnavailableException("No Http Response for " + urlString);

    } catch (ConnectException e) {
        throw new LiveWebCacheUnavailableException(e.getLocalizedMessage() + " : " + urlString);
    } catch (SocketException e) {
        throw new LiveWebCacheUnavailableException(e.getLocalizedMessage() + " : " + urlString);
    } catch (SocketTimeoutException e) {
        throw new LiveWebTimeoutException(e.getLocalizedMessage() + " : " + urlString);
    } catch (ConnectTimeoutException e) {
        throw new LiveWebTimeoutException(e.getLocalizedMessage() + " : " + urlString);
    } finally {
        if (!success) {
            method.abort();
        }
        method.releaseConnection();
    }
}

From source file:org.eclipse.mylyn.commons.net.WebUtil.java

/**
 * @since 3.1//from  w w w. j av a  2 s . co m
 */
public static int execute(final HttpClient client, final HostConfiguration hostConfiguration,
        final HttpMethod method, final HttpState state, IProgressMonitor monitor) throws IOException {
    Assert.isNotNull(client);
    Assert.isNotNull(method);

    monitor = Policy.monitorFor(monitor);

    MonitoredRequest<Integer> executor = new MonitoredRequest<Integer>(monitor) {
        @Override
        public void abort() {
            super.abort();
            method.abort();
        }

        @Override
        public Integer execute() throws Exception {
            return client.executeMethod(hostConfiguration, method, state);
        }
    };

    return executeInternal(monitor, executor);
}

From source file:org.openrdf.http.client.HTTPClient.java

protected final void releaseConnection(HttpMethod method) {
    if (Thread.currentThread().isInterrupted()) {
        method.abort();
    } else {/*  w w w. j av a 2s .  c o  m*/
        method.releaseConnection();
    }
}

From source file:org.openrdf.repository.sparql.query.SPARQLBooleanQuery.java

public boolean evaluate() throws QueryEvaluationException {
    try {/*from  w ww  .  jav a  2s  .  co  m*/
        boolean complete = false;
        HttpMethod response = getResponse();
        try {
            boolean result = parser.parse(response.getResponseBodyAsStream());
            complete = true;
            return result;
        } catch (HttpException e) {
            throw new QueryEvaluationException(e);
        } catch (QueryResultParseException e) {
            throw new QueryEvaluationException(e);
        } finally {
            if (!complete) {
                response.abort();
            }
        }
    } catch (IOException e) {
        throw new QueryEvaluationException(e);
    }
}

From source file:org.openrdf.repository.sparql.query.SPARQLGraphQuery.java

public void evaluate(RDFHandler handler) throws QueryEvaluationException, RDFHandlerException {
    boolean complete = false;
    try {/*w  w w. j  a v a 2  s .c o m*/
        HttpMethod response = getResponse();
        try {
            RDFParser parser = getParser(response);
            parser.setRDFHandler(handler);
            parser.parse(response.getResponseBodyAsStream(), getUrl());
            complete = true;
        } catch (HttpException e) {
            throw new QueryEvaluationException(e);
        } catch (RDFParseException e) {
            throw new QueryEvaluationException(e);
        } catch (RDFHandlerException e) {
            throw new QueryEvaluationException(e);
        } finally {
            if (!complete) {
                response.abort();
            }
        }
    } catch (IOException e) {
        throw new QueryEvaluationException(e);
    }
}

From source file:org.openrdf.repository.sparql.query.SPARQLTupleQuery.java

public TupleQueryResult evaluate() throws QueryEvaluationException {
    try {//from ww  w.ja va2s  .c o m
        BackgroundTupleResult result = null;
        HttpMethod response = getResponse();
        try {
            InputStream in = response.getResponseBodyAsStream();
            result = new BackgroundTupleResult(parser, in, response);
            execute(result);
            InsertBindingSetCursor cursor = new InsertBindingSetCursor(result, getBindings());
            List<String> list = new ArrayList<String>(result.getBindingNames());
            list.addAll(getBindingNames());
            return new TupleQueryResultImpl(list, cursor);
        } catch (HttpException e) {
            throw new QueryEvaluationException(e);
        } finally {
            if (result == null) {
                response.abort();
            }
        }
    } catch (IOException e) {
        throw new QueryEvaluationException(e);
    }
}

From source file:org.openrdf.repository.sparql.query.SPARQLTupleQuery.java

public void evaluate(TupleQueryResultHandler handler)
        throws QueryEvaluationException, TupleQueryResultHandlerException {
    try {/*from  www  .j ava  2  s  . c o m*/
        boolean complete = false;
        HttpMethod response = getResponse();
        try {
            parser.setTupleQueryResultHandler(handler);
            parser.parse(response.getResponseBodyAsStream());
            complete = true;
        } catch (HttpException e) {
            throw new QueryEvaluationException(e);
        } catch (QueryResultParseException e) {
            throw new QueryEvaluationException(e);
        } catch (TupleQueryResultHandlerException e) {
            throw new QueryEvaluationException(e);
        } finally {
            if (!complete) {
                response.abort();
            }
        }
    } catch (IOException e) {
        throw new QueryEvaluationException(e);
    }
}