Example usage for org.apache.commons.httpclient HttpMethodBase releaseConnection

List of usage examples for org.apache.commons.httpclient HttpMethodBase releaseConnection

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethodBase releaseConnection.

Prototype

@Override
public void releaseConnection() 

Source Link

Document

Releases the connection being used by this HTTP method.

Usage

From source file:org.eclipse.mylyn.internal.provisional.commons.soap.CommonsHttpSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and then reads the response SOAP message back
 * from the SOAP server/*from ww w. j  av a2  s .c  om*/
 * 
 * @param msgContext
 *            the messsage context
 * @throws AxisFault
 */
public void invoke(MessageContext msgContext) throws AxisFault {
    HttpMethodBase method = null;
    //      if (log.isDebugEnabled()) {
    //         log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke"));
    //      }
    try {
        URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));

        // no need to retain these, as the cookies/credentials are
        // stored in the message context across multiple requests.
        // the underlying connection manager, however, is retained
        // so sockets get recycled when possible.
        HttpClient httpClient = new HttpClient(this.connectionManager);
        // the timeout value for allocation of connections from the pool
        httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout());

        HostConfiguration hostConfiguration = getHostConfiguration(httpClient, msgContext, targetURL);

        boolean posting = true;

        // If we're SOAP 1.2, allow the web method to be set from the
        // MessageContext.
        if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
            if (webMethod != null) {
                posting = webMethod.equals(HTTPConstants.HEADER_POST);
            }
        }

        if (posting) {
            Message reqMessage = msgContext.getRequestMessage();
            method = new PostMethod(targetURL.toString());

            // set false as default, addContetInfo can overwrite
            method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

            addContextInfo(method, httpClient, msgContext, targetURL);

            MessageRequestEntity requestEntity = null;
            if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
                requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream);
            } else {
                requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream);
            }
            ((PostMethod) method).setRequestEntity(requestEntity);
        } else {
            method = new GetMethod(targetURL.toString());
            addContextInfo(method, httpClient, msgContext, targetURL);
        }

        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null) {
            if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
                method.getParams().setVersion(HttpVersion.HTTP_1_0);
            }
            // assume 1.1
        }

        // don't forget the cookies!
        // Cookies need to be set on HttpState, since HttpMethodBase 
        // overwrites the cookies from HttpState
        if (msgContext.getMaintainSession()) {
            HttpState state = httpClient.getState();
            method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            String host = hostConfiguration.getHost();
            String path = targetURL.getPath();
            boolean secure = hostConfiguration.getProtocol().isSecure();
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure);
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure);
            httpClient.setState(state);
        }

        int returnCode = httpClient.executeMethod(hostConfiguration, method, null);

        String contentType = getHeader(method, HTTPConstants.HEADER_CONTENT_TYPE);
        String contentLocation = getHeader(method, HTTPConstants.HEADER_CONTENT_LOCATION);
        //         String contentLength = getHeader(method, HTTPConstants.HEADER_CONTENT_LENGTH);

        if ((returnCode > 199) && (returnCode < 300)) {

            // SOAP return is OK - so fall through
        } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            // For now, if we're SOAP 1.2, fall through, since the range of
            // valid result codes is much greater
        } else if ((contentType != null) && !contentType.equals("text/html") //$NON-NLS-1$
                && ((returnCode > 499) && (returnCode < 600))) {

            // SOAP Fault should be in here - so fall through
        } else {
            //            String statusMessage = method.getStatusText();
            //            AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

            try {
                //               fault.setFaultDetailString(Messages.getMessage("return01", "" + returnCode, //$NON-NLS-1$ //$NON-NLS-2$
                //                     method.getResponseBodyAsString()));
                //               fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                //               throw fault;
                throw AxisHttpFault.makeFault(method);
            } finally {
                method.releaseConnection(); // release connection back to pool.
            }
        }

        // wrap the response body stream so that close() also releases 
        // the connection back to the pool.
        InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method);

        Header contentEncoding = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
        if (contentEncoding != null) {
            if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) {
                releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream);
            } else if (contentEncoding.getValue().equals("") //$NON-NLS-1$
                    && msgContext.isPropertyTrue(SoapHttpSender.ALLOW_EMPTY_CONTENT_ENCODING)) {
                // assume no encoding
            } else {
                AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '" //$NON-NLS-1$ //$NON-NLS-2$
                        + contentEncoding.getValue() + "' found", null, null); //$NON-NLS-1$
                throw fault;
            }

        }
        Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation);
        // Transfer HTTP headers of HTTP message to MIME headers of SOAP message
        Header[] responseHeaders = method.getResponseHeaders();
        MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
        for (Header responseHeader : responseHeaders) {
            responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue());
        }
        outMsg.setMessageType(Message.RESPONSE);
        msgContext.setResponseMessage(outMsg);
        //         if (log.isDebugEnabled()) {
        //            if (null == contentLength) {
        //               log.debug("\n" + Messages.getMessage("no00", "Content-Length"));
        //            }
        //            log.debug("\n" + Messages.getMessage("xmlRecd00"));
        //            log.debug("-----------------------------------------------");
        //            log.debug(outMsg.getSOAPPartAsString());
        //         }

        // if we are maintaining session state,
        // handle cookies (if any)
        if (msgContext.getMaintainSession()) {
            Header[] headers = method.getResponseHeaders();

            for (Header header : headers) {
                if (header.getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE, header.getValue(), msgContext);
                } else if (header.getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE2, header.getValue(), msgContext);
                }
            }
        }

        // always release the connection back to the pool if 
        // it was one way invocation
        if (msgContext.isPropertyTrue("axis.one.way")) { //$NON-NLS-1$
            method.releaseConnection();
        }

    } catch (Exception e) {
        //         log.debug(e);
        throw AxisFault.makeFault(e);
    }

    //      if (log.isDebugEnabled()) {
    //         log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke"));
    //      }
}

From source file:org.eclipse.mylyn.internal.provisional.commons.soap.CommonsHttpSender.java

private InputStream createConnectionReleasingInputStream(final HttpMethodBase method) throws IOException {
    return new FilterInputStream(method.getResponseBodyAsStream()) {
        @Override/*from ww w.  ja v a  2  s  .c  om*/
        public void close() throws IOException {
            try {
                super.close();
            } finally {
                method.releaseConnection();
            }
        }
    };
}

From source file:org.eclipse.php.composer.core.HttpHelper.java

public static String executeGetRequest(String url, Map<String, String> parameters, Map<String, String> cookies,
        int expectedCode) {
    try {/*from  w ww. j av  a 2 s.  c  om*/
        HttpClient client = createHttpClient(url, ComposerCorePlugin.getProxyService());
        HttpMethodBase method = createGetRequest(url, parameters);
        setCookies(method, cookies);
        if (method != null) {
            int statusCode = -1;
            try {
                statusCode = client.executeMethod(method);
                if (statusCode == expectedCode) {
                    String responseContent = new String(method.getResponseBody());
                    return responseContent;
                }
            } finally {
                method.releaseConnection();
            }
        }
    } catch (IOException e) {
        ComposerCorePlugin.logError(e);
    } catch (URISyntaxException e) {
        ComposerCorePlugin.logError(e);
    }

    return null;
}

From source file:org.eclipse.smila.connectivity.framework.crawler.web.http.HttpResponse.java

/**
 * Creates new object and fills it with retrieved URL information.
 * /*from   www  .j  a  v a2s. co m*/
 * @param http
 *          HTTP protocol options HTTP to retrieve
 * @param filterProcessor
 *          filters to perform
 * @param urlString
 *          the url string
 * 
 * @throws IOException
 *           if error while retrieving URL occur
 */
public HttpResponse(HttpBase http, String urlString, FilterProcessor filterProcessor) throws IOException {
    _http = http;
    _urlString = urlString;
    HttpMethodBase httpMethod = null;
    try {
        httpMethod = getHttpMethod();
        setHttpParameters(http, httpMethod);
        _statusCode = Http.getClient().executeMethod(httpMethod);
        final Header[] headers = httpMethod.getResponseHeaders();
        for (int i = 0; i < headers.length; i++) {
            _headers.set(headers[i].getName(), headers[i].getValue());
        }
        // Content-Type filter should go here
        // TODO: Guess content type when Content-Type header is empty
        boolean contentTypeMatches = true;
        final String contentType = _headers.get(Response.CONTENT_TYPE);
        if ((contentType != null) && (filterProcessor != null)) {
            contentTypeMatches = filterProcessor.evaluateContentTypeFilters(contentType);
            LOG.debug("Content type header: " + contentType + ", passed filters: " + contentTypeMatches);
        }
        if (contentTypeMatches) {
            // always read content. Sometimes content is useful to find a cause for error.
            try {
                final InputStream in = httpMethod.getResponseBodyAsStream();
                if (in != null) {
                    final byte[] buffer = new byte[HttpBase.BUFFER_SIZE];
                    int totalRead = 0;
                    final ByteArrayOutputStream out = new ByteArrayOutputStream();
                    int tryAndRead = calculateTryToRead(totalRead);
                    int bufferFilled = in.read(buffer, 0, buffer.length);
                    while (bufferFilled != -1 && tryAndRead > 0) {
                        totalRead += bufferFilled;
                        out.write(buffer, 0, bufferFilled);
                        tryAndRead = calculateTryToRead(totalRead);
                        bufferFilled = in.read(buffer, 0, buffer.length);
                    }
                    _content = out.toByteArray();
                    in.close();
                }
            } catch (HttpException exception) {
                LOG.error("Http error occured ", exception);
                throw new IOException(exception.toString());
            } catch (IOException exception) {
                if (_statusCode == HttpResponseCode.CODE_200) {
                    throw new IOException(exception.toString());
                }
                // for codes other than 200 OK, we are fine with empty content
            }
            if (_content != null) {
                // check if we have to uncompress it
                final String contentEncoding = _headers.get(Response.CONTENT_ENCODING);
                if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) {
                    _content = http.processGzipEncoded(_content, urlString);
                }
                if (("application/x-gzip".equals(contentType)) || ("application/gzip".equals(contentType))) {
                    _content = http.processGzipEncoded(_content, urlString);
                }
            }
        } else {
            // URL wasn't fetched
            _statusCode = -1;
        }
    } catch (ProtocolException exception) {
        if (LOG.isErrorEnabled()) {
            LOG.error(exception);
        }
        throw new IOException(exception.toString());
    } catch (URISyntaxException exception) {
        if (LOG.isErrorEnabled()) {
            LOG.error(exception);
        }
        throw new IOException(exception.toString());
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:org.eclipse.swordfish.plugins.resolver.proxy.impl.HttpCilentProxy.java

@Override
public ClientResponse invoke(ClientRequest request) {
    ClientResponse response = new ClientResponseImpl();
    HttpMethodBase method = getMethod(request.getMethod());

    try {// w w  w  .j a  v  a  2  s  . c  o  m
        method.setURI(new URI(request.getURI().toString(), true));
        int statusCode = getClient().executeMethod(method);
        response.setStatus(Status.get(statusCode));

        String responseBody = method.getResponseBodyAsString();
        if (request.getEntityType() != null) {
            Reader responseReader = new StringReader(responseBody);
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            try {
                Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
                response.setEntity(JAXB.unmarshal(responseReader, request.getEntityType()));
            } finally {
                Thread.currentThread().setContextClassLoader(cl);
            }
        } else {
            response.setEntity(responseBody);
        }
    } catch (HttpException e) {
        response.setStatus(Status.ERROR);
        response.setEntity(e);
    } catch (IOException e) {
        response.setStatus(Status.ERROR);
        response.setEntity(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    return response;
}

From source file:org.elasticsearch.hadoop.rest.RestClient.java

byte[] execute(HttpMethodBase method, boolean checkStatus) {
    try {// www .  j  a  va 2 s  . c o m
        int status = client.executeMethod(method);
        if (checkStatus && status >= HttpStatus.SC_MULTI_STATUS) {
            String body;
            try {
                body = method.getResponseBodyAsString();
            } catch (IOException ex) {
                body = "";
            }
            throw new IllegalStateException(String.format("[%s] on [%s] failed; server[%s] returned [%s]",
                    method.getName(), method.getURI(), client.getHostConfiguration().getHostURL(), body));
        }
        return method.getResponseBody();
    } catch (IOException io) {
        String target;
        try {
            target = method.getURI().toString();
        } catch (IOException ex) {
            target = method.getPath();
        }
        throw new IllegalStateException(
                String.format("Cannot get response body for [%s][%s]", method.getName(), target));
    } finally {
        method.releaseConnection();
    }
}

From source file:org.entando.entando.plugins.jpoauthclient.aps.system.services.client.ProviderConnectionManager.java

private String invokeGetDeleteMethod(String url, boolean isGet, Properties parameters) throws Throwable {
    String result = null;//from www.  ja v a  2s.  co m
    HttpMethodBase method = null;
    InputStream inputStream = null;
    try {
        HttpClient client = new HttpClient();
        if (isGet) {
            method = new GetMethod(url);
        } else {
            method = new DeleteMethod(url);
        }
        this.addQueryString(method, parameters);
        client.executeMethod(method);
        inputStream = method.getResponseBodyAsStream();
        result = IOUtils.toString(inputStream, "UTF-8");
        //byte[] responseBody = method.getResponseBody();
        //result = new String(responseBody);
    } catch (Throwable t) {
        _logger.error("Error invoking Get or Delete Method", t);
    } finally {
        if (null != inputStream) {
            inputStream.close();
        }
        if (null != method) {
            method.releaseConnection();
        }
    }
    return result;
}

From source file:org.fao.geonet.csw.common.requests.CatalogRequest.java

private Element doExecute(HttpMethodBase httpMethod) throws IOException, JDOMException {
    client.getHostConfiguration().setHost(host, port, protocol);

    byte[] data = null;

    try {/*from w  ww .  j ava 2 s .c  o m*/
        client.executeMethod(httpMethod);

        ///data = httpMethod.getResponseBody();
        // If server return HTTP Error 500 Server error 
        // when retrieving the data return null
        if (httpMethod.getStatusCode() == 500) {
            System.out.println("  Status code: " + httpMethod.getStatusCode());
            return null;
        } else {
            return Xml.loadStream(httpMethod.getResponseBodyAsStream());
        }
    } finally {
        httpMethod.releaseConnection();
        try {
            setupSentData(httpMethod);
            setupReceivedData(httpMethod, data);
        } catch (Throwable e) {
            Log.warning(Geonet.HARVESTER,
                    "Exception was raised during cleanup of a CSW request : " + Util.getStackTrace(e));
        }
    }
}

From source file:org.fao.oaipmh.requests.Transport.java

private Element doExecute(HttpMethodBase httpMethod) throws IOException, JDOMException {
    config.setHost(host, port, Protocol.getProtocol(protocol));

    if (useProxy)
        config.setProxy(proxyHost, proxyPort);

    byte[] data = null;

    try {//from   www.  j  a  va2 s  .c  om
        client.executeMethod(httpMethod);
        data = httpMethod.getResponseBody();

        Element response = Xml.loadStream(new ByteArrayInputStream(data));

        setupSentData(httpMethod);
        setupReceivedData(httpMethod, data);

        return response;
    } finally {
        httpMethod.releaseConnection();
    }
}

From source file:org.genemania.util.HttpRetriever.java

public String post(String url, Hashtable<String, String> params) {
    String ret = "";
    try {/*from   w ww.  j ava 2 s  .  c  o m*/
        HttpClient client = new HttpClient();
        HttpMethodBase method = new PostMethod(url);
        Enumeration<String> paramNames = params.keys();
        while (paramNames.hasMoreElements()) {
            String nextParamName = paramNames.nextElement();
            String nextParamValue = params.get(nextParamName);
            ((PostMethod) (method)).addParameter(nextParamName, nextParamValue);
        }
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            System.out.println("HttpRetriever error: " + method.getStatusLine());
        } else {
            byte[] responseBody = method.getResponseBody();
            method.releaseConnection();
            ret = new String(responseBody);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return ret;
}