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.activebpel.rt.axis.bpel.handlers.AeHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and then
 * reads the response SOAP message back from the SOAP server
 *
 * @param msgContext the message context
 *
 * @throws AxisFault/*from   w w w.  ja va2 s .c o m*/
 * @deprecated
 */
public void invoke(MessageContext msgContext) throws AxisFault {
    HttpMethodBase method = null;
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("enter00", //$NON-NLS-1$
                "CommonsHTTPSender::invoke")); //$NON-NLS-1$
    }
    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(connectionManager);
        // the timeout value for allocation of connections from the pool
        httpClient.setHttpConnectionFactoryTimeout(clientProperties.getConnectionPoolTimeout());

        HostConfiguration hostConfiguration = getHostConfiguration(httpClient, targetURL);
        httpClient.setHostConfiguration(hostConfiguration);

        // look for option to send credentials preemptively (w/out challenge)
        // Control of Preemptive is controlled via policy on a per call basis.
        String preemptive = (String) msgContext.getProperty("HTTPPreemptive"); //$NON-NLS-1$
        if ("true".equals(preemptive)) //$NON-NLS-1$
        {
            httpClient.getParams().setAuthenticationPreemptive(true);
        }

        String webMethod = null;
        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) {
            webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
            if (webMethod != null) {
                posting = webMethod.equals(HTTPConstants.HEADER_POST);
            }
        }

        Message reqMessage = msgContext.getRequestMessage();
        if (posting) {
            method = new PostMethod(targetURL.toString());
            addContextInfo(method, httpClient, msgContext, targetURL);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            reqMessage.writeTo(baos);
            ((PostMethod) method).setRequestBody(new ByteArrayInputStream(baos.toByteArray()));
            ((PostMethod) method).setUseExpectHeader(false); // workaround for
        } else {
            method = new GetMethod(targetURL.toString());
            addContextInfo(method, httpClient, msgContext, targetURL);
        }
        // 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();
            state.setCookiePolicy(CookiePolicy.COMPATIBILITY);
            String host = hostConfiguration.getHost();
            String path = targetURL.getPath();
            boolean secure = hostConfiguration.getProtocol().isSecure();
            String ck1 = (String) msgContext.getProperty(HTTPConstants.HEADER_COOKIE);

            String ck2 = (String) msgContext.getProperty(HTTPConstants.HEADER_COOKIE2);
            if (ck1 != null) {
                int index = ck1.indexOf('=');
                state.addCookie(new Cookie(host, ck1.substring(0, index), ck1.substring(index + 1), path, null,
                        secure));
            }
            if (ck2 != null) {
                int index = ck2.indexOf('=');
                state.addCookie(new Cookie(host, ck2.substring(0, index), ck2.substring(index + 1), path, null,
                        secure));
            }
            httpClient.setState(state);
        }
        boolean hasSoapFault = false;
        int returnCode = httpClient.executeMethod(method);
        String contentType = null;
        String contentLocation = null;
        String contentLength = null;
        if (method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE) != null) {
            contentType = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE).getValue();
        }
        if (method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LOCATION) != null) {
            contentLocation = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LOCATION).getValue();
        }
        if (method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LENGTH) != null) {
            contentLength = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_LENGTH).getValue();
        }
        contentType = (null == contentType) ? null : contentType.trim();
        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
            hasSoapFault = true;
        } else {
            String statusMessage = method.getStatusText();
            AxisFault fault = new AxisFault("HTTP", //$NON-NLS-1$
                    "(" + returnCode + ")" //$NON-NLS-1$ //$NON-NLS-2$
                            + statusMessage,
                    null, null);

            try {
                fault.setFaultDetailString(Messages.getMessage("return01", //$NON-NLS-1$
                        "" + returnCode, method.getResponseBodyAsString())); //$NON-NLS-1$
                fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                throw fault;
            } 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);

        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 (int i = 0; i < responseHeaders.length; i++) {
            Header responseHeader = responseHeaders[i];
            responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue());
        }

        OperationDesc operation = msgContext.getOperation();
        if (hasSoapFault || operation.getMep().equals(OperationType.REQUEST_RESPONSE)) {
            msgContext.setResponseMessage(outMsg);
        } else {
            // Change #1
            //
            // If the operation is a one-way, then don't set the response
            // on the msg context. Doing so will cause Axis to attempt to
            // read from a non-existent SOAP message which causes errors.
            //
            // Note: also checking to see if the return type is our "VOID"
            // QName from the AeInvokeHandler since that's our workaround
            // for avoiding Axis's Thread creation in Call.invokeOneWay()
            //
            // Since the message context won't have a chance to consume the
            // response stream (which closes the connection), close the
            // connection here.
            method.releaseConnection();
        }

        if (log.isDebugEnabled()) {
            if (null == contentLength) {
                log.debug("\n" //$NON-NLS-1$
                        + Messages.getMessage("no00", "Content-Length")); //$NON-NLS-1$ //$NON-NLS-2$
            }
            log.debug("\n" + Messages.getMessage("xmlRecd00")); //$NON-NLS-1$ //$NON-NLS-2$
            log.debug("-----------------------------------------------"); //$NON-NLS-1$
            log.debug(outMsg.getSOAPPartAsString());
        }

        // if we are maintaining session state,
        // handle cookies (if any)
        if (msgContext.getMaintainSession()) {
            Header[] headers = method.getResponseHeaders();
            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE))
                    msgContext.setProperty(HTTPConstants.HEADER_COOKIE, cleanupCookie(headers[i].getValue()));
                else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2))
                    msgContext.setProperty(HTTPConstants.HEADER_COOKIE2, cleanupCookie(headers[i].getValue()));
            }

        }

    } catch (Throwable t) {
        log.debug(t);

        if (method != null) {
            method.releaseConnection();
        }

        // We can call Axis.makeFault() if it's an exception; otherwise
        // construct the AxisFault directly.
        throw (t instanceof Exception) ? AxisFault.makeFault((Exception) t)
                : new AxisFault(t.getLocalizedMessage(), t);
    }

    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("exit00", //$NON-NLS-1$
                "CommonsHTTPSender::invoke")); //$NON-NLS-1$
    }
}

From source file:org.alfresco.repo.remoteconnector.RemoteConnectorServiceImpl.java

/**
 * Executes the specified request, and return the response
 *//*from ww  w . j a v  a  2  s. co  m*/
public RemoteConnectorResponse executeRequest(RemoteConnectorRequest request) throws IOException,
        AuthenticationException, RemoteConnectorClientException, RemoteConnectorServerException {
    RemoteConnectorRequestImpl reqImpl = (RemoteConnectorRequestImpl) request;
    HttpMethodBase httpRequest = reqImpl.getMethodInstance();

    // Attach the headers to the request
    for (Header hdr : request.getRequestHeaders()) {
        httpRequest.addRequestHeader(hdr);
    }

    // Attach the body, if possible
    if (httpRequest instanceof EntityEnclosingMethod) {
        if (request.getRequestBody() != null) {
            ((EntityEnclosingMethod) httpRequest).setRequestEntity(reqImpl.getRequestBody());
        }
    }

    // Grab our thread local HttpClient instance
    // Remember - we must then clean it up!
    HttpClient httpClient = HttpClientHelper.getHttpClient();

    // The url should already be vetted by the RemoteConnectorRequest
    URL url = new URL(request.getURL());

    // Use the appropriate Proxy Host if required
    if (httpProxyHost != null && url.getProtocol().equals("http") && requiresProxy(url.getHost())) {
        httpClient.getHostConfiguration().setProxyHost(httpProxyHost);
        if (logger.isDebugEnabled())
            logger.debug(" - using HTTP proxy host for: " + url);
        if (httpProxyCredentials != null) {
            httpClient.getState().setProxyCredentials(httpAuthScope, httpProxyCredentials);
            if (logger.isDebugEnabled())
                logger.debug(" - using HTTP proxy credentials for proxy: " + httpProxyHost.getHostName());
        }
    } else if (httpsProxyHost != null && url.getProtocol().equals("https") && requiresProxy(url.getHost())) {
        httpClient.getHostConfiguration().setProxyHost(httpsProxyHost);
        if (logger.isDebugEnabled())
            logger.debug(" - using HTTPS proxy host for: " + url);
        if (httpsProxyCredentials != null) {
            httpClient.getState().setProxyCredentials(httpsAuthScope, httpsProxyCredentials);
            if (logger.isDebugEnabled())
                logger.debug(" - using HTTPS proxy credentials for proxy: " + httpsProxyHost.getHostName());
        }
    } else {
        //host should not be proxied remove any configured proxies
        httpClient.getHostConfiguration().setProxyHost(null);
        httpClient.getState().clearProxyCredentials();
    }

    // Log what we're doing
    if (logger.isDebugEnabled()) {
        logger.debug("Performing " + request.getMethod() + " request to " + request.getURL());
        for (Header hdr : request.getRequestHeaders()) {
            logger.debug("Header: " + hdr);
        }
        Object requestBody = null;
        if (request != null) {
            requestBody = request.getRequestBody();
        }
        if (requestBody != null && requestBody instanceof StringRequestEntity) {
            StringRequestEntity re = (StringRequestEntity) request.getRequestBody();
            logger.debug("Payload (string): " + re.getContent());
        } else if (requestBody != null && requestBody instanceof ByteArrayRequestEntity) {
            ByteArrayRequestEntity re = (ByteArrayRequestEntity) request.getRequestBody();
            logger.debug("Payload (byte array): " + re.getContent().toString());
        } else {
            logger.debug("Payload is not of a readable type.");
        }
    }

    // Perform the request, and wrap the response
    int status = -1;
    String statusText = null;
    RemoteConnectorResponse response = null;
    try {
        status = httpClient.executeMethod(httpRequest);
        statusText = httpRequest.getStatusText();

        Header[] responseHdrs = httpRequest.getResponseHeaders();
        Header responseContentTypeH = httpRequest
                .getResponseHeader(RemoteConnectorRequestImpl.HEADER_CONTENT_TYPE);
        String responseCharSet = httpRequest.getResponseCharSet();
        String responseContentType = (responseContentTypeH != null ? responseContentTypeH.getValue() : null);

        if (logger.isDebugEnabled()) {
            logger.debug(
                    "response url=" + request.getURL() + ", length =" + httpRequest.getResponseContentLength()
                            + ", responceContentType " + responseContentType + ", statusText =" + statusText);
        }

        // Decide on how best to handle the response, based on the size
        // Ideally, we want to close the HttpClient resources immediately, but
        //  that isn't possible for very large responses
        // If we can close immediately, it makes cleanup simpler and fool-proof
        if (httpRequest.getResponseContentLength() > MAX_BUFFER_RESPONSE_SIZE
                || httpRequest.getResponseContentLength() == -1) {
            if (logger.isTraceEnabled()) {
                logger.trace("large response (or don't know length) url=" + request.getURL());
            }

            // Need to wrap the InputStream in something that'll close
            InputStream wrappedStream = new HttpClientReleasingInputStream(httpRequest);
            httpRequest = null;

            // Now build the response
            response = new RemoteConnectorResponseImpl(request, responseContentType, responseCharSet, status,
                    responseHdrs, wrappedStream);
        } else {
            if (logger.isTraceEnabled()) {
                logger.debug("small response for url=" + request.getURL());
            }
            // Fairly small response, just keep the bytes and make life simple
            response = new RemoteConnectorResponseImpl(request, responseContentType, responseCharSet, status,
                    responseHdrs, httpRequest.getResponseBody());

            // Now we have the bytes, we can close the HttpClient resources
            httpRequest.releaseConnection();
            httpRequest = null;
        }
    } finally {
        // Make sure, problems or not, we always tidy up (if not large stream based)
        // This is important because we use a thread local HttpClient instance
        if (httpRequest != null) {
            httpRequest.releaseConnection();
            httpRequest = null;
        }
    }

    // Log the response
    if (logger.isDebugEnabled())
        logger.debug("Response was " + status + " " + statusText);

    // Decide if we should throw an exception
    if (status >= 300) {
        // Tidy if needed
        if (httpRequest != null)
            httpRequest.releaseConnection();

        // Specific exceptions
        if (status == Status.STATUS_FORBIDDEN || status == Status.STATUS_UNAUTHORIZED) {
            // TODO Forbidden may need to be handled differently.
            // TODO Need to get error message into the AuthenticationException
            throw new AuthenticationException(statusText);
        }

        // Server side exceptions
        if (status >= 500 && status <= 599) {
            logger.error("executeRequest: remote connector server exception: [" + status + "] " + statusText);
            throw new RemoteConnectorServerException(status, statusText);
        }
        if (status == Status.STATUS_PRECONDITION_FAILED) {
            logger.error("executeRequest: remote connector client exception: [" + status + "] " + statusText);
            throw new RemoteConnectorClientException(status, statusText, response);
        } else {
            // Client request exceptions
            if (httpRequest != null) {
                // Response wasn't too big and is available, supply it
                logger.error(
                        "executeRequest: remote connector client exception: [" + status + "] " + statusText);
                throw new RemoteConnectorClientException(status, statusText, response);
            } else {
                // Response was too large, report without it
                logger.error(
                        "executeRequest: remote connector client exception: [" + status + "] " + statusText);
                throw new RemoteConnectorClientException(status, statusText, null);
            }
        }
    }

    // If we get here, then the request/response was all fine
    // So, return our created response
    return response;
}

From source file:org.apache.ambari.funtest.server.AmbariHttpWebRequest.java

/**
 * Executes the current request by using HttpClient methods and returns the response.
 *
 * @return - Response from the Ambari server/Agent server.
 * @throws IOException/*from   w w  w.j a v a2 s  .  c om*/
 */
private WebResponse executeRequest() throws IOException {
    HttpMethodBase methodBase = null;
    String httpMethod;

    httpMethod = getHttpMethod();

    if (httpMethod.equals("GET")) {
        methodBase = getGetMethod();
    } else if (httpMethod.equals("POST")) {
        methodBase = getPostMethod();
    } else if (httpMethod.equals("PUT")) {
        methodBase = getPutMethod();
    } else if (httpMethod.equals("DELETE")) {
        methodBase = getDeleteMethod();
    } else {
        new RuntimeException(String.format("Unsupported HTTP method: %s", httpMethod));
    }

    WebResponse response = new WebResponse();
    HttpClient httpClient = new HttpClient();
    Map<String, String> headers = getHeaders();

    for (Map.Entry<String, String> header : headers.entrySet()) {
        methodBase.addRequestHeader(header.getKey(), header.getValue());
    }

    methodBase.setQueryString(getQueryString());

    try {
        int statusCode = httpClient.executeMethod(methodBase);
        response.setStatusCode(statusCode);
        response.setContent(methodBase.getResponseBodyAsString());
    } finally {
        methodBase.releaseConnection();
    }

    return response;
}

From source file:org.apache.axis.transport.http.CommonsHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and then
 * reads the response SOAP message back from the SOAP server
 *
 * @param msgContext the messsage context
 *
 * @throws AxisFault/*  w ww.  j  a va  2  s  . co m*/
 */
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")
                && ((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);

            try {
                fault.setFaultDetailString(
                        Messages.getMessage("return01", "" + returnCode, method.getResponseBodyAsString()));
                fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                throw fault;
            } 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 {
                AxisFault fault = new AxisFault("HTTP",
                        "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null,
                        null);
                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 (int i = 0; i < responseHeaders.length; i++) {
            Header responseHeader = responseHeaders[i];
            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 (int i = 0; i < headers.length; i++) {
                if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE, headers[i].getValue(), msgContext);
                } else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE2, headers[i].getValue(), msgContext);
                }
            }
        }

        // always release the connection back to the pool if 
        // it was one way invocation
        if (msgContext.isPropertyTrue("axis.one.way")) {
            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.apache.axis2.transport.http.HTTPSender.java

/**
 * Used to handle the HTTP Response//from ww  w  .j av  a2  s. c  o  m
 *
 * @param msgContext - The MessageContext of the message
 * @param method     - The HTTP method used
 * @throws IOException - Thrown in case an exception occurs
 */
private void handleResponse(MessageContext msgContext, HttpMethodBase method) throws IOException {
    int statusCode = method.getStatusCode();
    HTTPStatusCodeFamily family = getHTTPStatusCodeFamily(statusCode);
    log.trace("Handling response - " + statusCode);
    Set<Integer> nonErrorCodes = (Set<Integer>) msgContext
            .getProperty(HTTPConstants.NON_ERROR_HTTP_STATUS_CODES);
    Set<Integer> errorCodes = new HashSet<Integer>();
    String strRetryErrorCodes = (String) msgContext.getProperty(HTTPConstants.ERROR_HTTP_STATUS_CODES); // Fixing
    // ESBJAVA-3178
    if (strRetryErrorCodes != null && !strRetryErrorCodes.trim().equals("")) {
        for (String strRetryErrorCode : strRetryErrorCodes.split(",")) {
            try {
                errorCodes.add(Integer.valueOf(strRetryErrorCode));
            } catch (NumberFormatException e) {
                log.warn(strRetryErrorCode + " is not a valid status code");
            }
        }
    }
    if (statusCode == HttpStatus.SC_ACCEPTED) {
        /* When an HTTP 202 Accepted code has been received, this will be the case of an execution 
         * of an in-only operation. In such a scenario, the HTTP response headers should be returned,
         * i.e. session cookies. */
        obtainHTTPHeaderInformation(method, msgContext);
        // Since we don't expect any content with a 202 response, we must release the connection
        method.releaseConnection();
    } else if (HTTPStatusCodeFamily.SUCCESSFUL.equals(family)) {
        // Save the HttpMethod so that we can release the connection when cleaning up
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        processResponse(method, msgContext);
    } else if (!errorCodes.contains(statusCode) && (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR
            || statusCode == HttpStatus.SC_BAD_REQUEST || statusCode == HttpStatus.SC_CONFLICT)) {
        // Save the HttpMethod so that we can release the connection when cleaning up
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        Header contenttypeHeader = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        String value = null;
        if (contenttypeHeader != null) {
            value = contenttypeHeader.getValue();
        }
        OperationContext opContext = msgContext.getOperationContext();
        if (opContext != null) {
            MessageContext inMessageContext = opContext.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
            if (inMessageContext != null) {
                inMessageContext.setProcessingFault(true);
            }
        }
        if (value != null) {

            processResponse(method, msgContext);
        }

        if (org.apache.axis2.util.Utils.isClientThreadNonBlockingPropertySet(msgContext)) {
            throw new AxisFault(
                    Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText()));
        }
    } else if (nonErrorCodes != null && nonErrorCodes.contains(statusCode)) {
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        processResponse(method, msgContext);
        return;
    } else {
        // Since we don't process the response, we must release the connection immediately
        method.releaseConnection();
        throw new AxisFault(
                Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText()));
    }
}

From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.java

/**
 * Used to handle the HTTP Response//from   w  w w  . j a v  a 2  s .  c o m
 * 
 * @param msgContext
 *            - The MessageContext of the message
 * @param method
 *            - The HTTP method used
 * @throws IOException
 *             - Thrown in case an exception occurs
 */
protected void handleResponse(MessageContext msgContext, Object httpMethodBase) throws IOException {
    HttpMethodBase method;
    if (httpMethodBase instanceof HttpMethodBase) {
        method = (HttpMethodBase) httpMethodBase;
    } else {
        log.trace("HttpMethodBase expected, but found - " + httpMethodBase);
        return;
    }
    int statusCode = method.getStatusCode();
    HTTPStatusCodeFamily family = getHTTPStatusCodeFamily(statusCode);
    log.trace("Handling response - " + statusCode);
    if (statusCode == HttpStatus.SC_ACCEPTED) {
        /* When an HTTP 202 Accepted code has been received, this will be the case of an execution 
         * of an in-only operation. In such a scenario, the HTTP response headers should be returned,
         * i.e. session cookies. */
        obtainHTTPHeaderInformation(method, msgContext);
        // Since we don't expect any content with a 202 response, we must release the connection
        method.releaseConnection();
    } else if (HTTPStatusCodeFamily.SUCCESSFUL.equals(family)) {
        // Save the HttpMethod so that we can release the connection when cleaning up
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        processResponse(method, msgContext);
    } else if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR || statusCode == HttpStatus.SC_BAD_REQUEST) {
        // Save the HttpMethod so that we can release the connection when
        // cleaning up
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        Header contenttypeHeader = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        String value = null;
        if (contenttypeHeader != null) {
            value = contenttypeHeader.getValue();
        }
        OperationContext opContext = msgContext.getOperationContext();
        if (opContext != null) {
            MessageContext inMessageContext = opContext.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
            if (inMessageContext != null) {
                inMessageContext.setProcessingFault(true);
            }
        }
        if (value != null) {

            processResponse(method, msgContext);
        }

        if (org.apache.axis2.util.Utils.isClientThreadNonBlockingPropertySet(msgContext)) {
            throw new AxisFault(
                    Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText()));
        }
    } else {
        // Since we don't process the response, we must release the
        // connection immediately
        method.releaseConnection();
        throw new AxisFault(
                Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText()));
    }
}

From source file:org.apache.cloudstack.network.opendaylight.api.NeutronRestApi.java

public void executeMethod(final HttpMethodBase method) throws NeutronRestApiException {
    try {//from w w w.j  av a2 s  . co  m
        client.executeMethod(method);
    } catch (HttpException e) {
        s_logger.error("HttpException caught while trying to connect to the Neutron Controller", e);
        method.releaseConnection();
        throw new NeutronRestApiException("API call to Neutron Controller Failed", e);
    } catch (IOException e) {
        s_logger.error("IOException caught while trying to connect to the Neutron Controller", e);
        method.releaseConnection();
        throw new NeutronRestApiException("API call to Neutron Controller Failed", e);
    }
}

From source file:org.apache.cloudstack.network.opendaylight.api.test.NeutronRestApiTest.java

@Override
public void executeMethod(final HttpMethodBase method) throws NeutronRestApiException {
    try {//from w w w. j  a  v a2 s .c  o m
        client.executeMethod(method);
    } catch (HttpException e) {
        method.releaseConnection();
        throw new NeutronRestApiException("API call to Neutron NVP Controller Failed", e);
    } catch (IOException e) {
        method.releaseConnection();
        throw new NeutronRestApiException("API call to Neutron NVP Controller Failed", e);
    }
}

From source file:org.apache.geronimo.javaee6.asynejb.test.AsynEJBTest.java

@Test
public void AsynEJBTest() throws Exception {
    String contextRoot = System.getProperty("appContext");
    HttpClient nclient = new HttpClient();
    String url = "http://localhost:8080/" + contextRoot + "/testServlet";
    HttpMethodBase httpMethod2;
    httpMethod2 = new PostMethod(url);
    int status = nclient.executeMethod(httpMethod2);
    Assert.assertEquals(200, status);//from   w  ww . j  a  v a  2s .  c  o m
    String result = null;
    if (status == 200) {
        String response = new String(httpMethod2.getResponseBodyAsString().getBytes("8859_1"));
        Matcher m = Pattern.compile("The notify process(.)+? testServlet.").matcher(response);

        while (m.find()) {
            result = m.group();
        }
    }
    Assert.assertEquals(result, "The notify process is undergoing at testServlet.");

    httpMethod2.releaseConnection();
}

From source file:org.apache.geronimo.javaee6.jndi.test.jndiEJBTest.java

@Test
public void AsynEJBTest() throws Exception {
    String VersionPara = System.getProperty("moduleVersion");
    String contextRoot = System.getProperty("appContext");

    HttpClient nclient = new HttpClient();
    String url = "http://localhost:8080/" + contextRoot + "/globalJNDITest?version=" + VersionPara;
    HttpMethodBase httpMethod;
    httpMethod = new PostMethod(url);

    int status = nclient.executeMethod(httpMethod);
    Assert.assertEquals(200, status);//www .ja  va2 s  .  co  m

    String result1 = null;
    String result2 = null;
    String result3 = null;
    if (status == 200) {
        String response = new String(httpMethod.getResponseBodyAsString().getBytes("8859_1"));
        result1 = findRes("global (.)+? at testServlet.", response);
        result2 = findRes("app (.)+? at testServlet.", response);
        result3 = findRes("module (.)+? at testServlet.", response);
    }
    Assert.assertEquals(result1, "global says:hello at testServlet.");
    Assert.assertEquals(result2, "app says:hello at testServlet.");
    Assert.assertEquals(result3, "module says:hello at testServlet.");

    httpMethod.releaseConnection();
}