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

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

Introduction

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

Prototype

@Override
public String getResponseBodyAsString() throws IOException 

Source Link

Document

Returns the response body of the HTTP method, if any, as a String .

Usage

From source file:com.rometools.propono.atom.client.OAuthStrategy.java

private void callOAuthUri(final String uri) throws ProponoException {

    final HttpClient httpClient = new HttpClient();

    final HttpMethodBase method;
    final String content;

    final Map<String, String> params = new HashMap<String, String>();
    params.put("oauth_version", "1.0");
    if (username != null) {
        params.put("xoauth_requestor_id", username);
    }//from w  w  w. ja v a  2 s  . co m
    params.put("oauth_consumer_key", consumerKey);
    params.put("oauth_signature_method", keyType);
    params.put("oauth_timestamp", Long.toString(timestamp));
    params.put("oauth_nonce", nonce);
    params.put("oauth_callback", "none");

    final OAuthServiceProvider provider = new OAuthServiceProvider(reqUrl, authzUrl, accessUrl);
    final OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, provider);
    final OAuthAccessor accessor = new OAuthAccessor(consumer);

    if (state == State.UNAUTHORIZED) {

        try {
            final OAuthMessage message = new OAuthMessage("GET", uri, params.entrySet());
            message.sign(accessor);

            final String finalUri = OAuth.addParameters(message.URL, message.getParameters());
            method = new GetMethod(finalUri);
            httpClient.executeMethod(method);
            content = method.getResponseBodyAsString();

        } catch (final Exception e) {
            throw new ProponoException("ERROR fetching request token", e);
        }

    } else if (state == State.REQUEST_TOKEN) {

        try {
            params.put("oauth_token", requestToken);
            params.put("oauth_token_secret", tokenSecret);
            accessor.tokenSecret = tokenSecret;

            final OAuthMessage message = new OAuthMessage("POST", uri, params.entrySet());
            message.sign(accessor);

            final String finalUri = OAuth.addParameters(message.URL, message.getParameters());
            method = new PostMethod(finalUri);
            httpClient.executeMethod(method);
            content = method.getResponseBodyAsString();

        } catch (final Exception e) {
            throw new ProponoException("ERROR fetching request token", e);
        }

    } else if (state == State.AUTHORIZED) {

        try {
            params.put("oauth_token", accessToken);
            params.put("oauth_token_secret", tokenSecret);
            accessor.tokenSecret = tokenSecret;

            final OAuthMessage message = new OAuthMessage("GET", uri, params.entrySet());
            message.sign(accessor);

            final String finalUri = OAuth.addParameters(message.URL, message.getParameters());
            method = new GetMethod(finalUri);
            httpClient.executeMethod(method);
            content = method.getResponseBodyAsString();

        } catch (final Exception e) {
            throw new ProponoException("ERROR fetching request token", e);
        }

    } else {
        method = null;
        content = null;
        return;
    }

    String token = null;
    String secret = null;

    if (content != null) {
        final String[] settings = content.split("&");
        for (final String setting2 : settings) {
            final String[] setting = setting2.split("=");
            if (setting.length > 1) {
                if ("oauth_token".equals(setting[0])) {
                    token = setting[1];
                } else if ("oauth_token_secret".equals(setting[0])) {
                    secret = setting[1];
                }
            }
        }
    }

    // TODO review switch without 'default'

    switch (state) {

    case UNAUTHORIZED:
        if (token != null && secret != null) {
            requestToken = token;
            tokenSecret = secret;
            state = State.REQUEST_TOKEN;
        } else {
            throw new ProponoException("ERROR: requestToken or tokenSecret is null");
        }
        break;

    case REQUEST_TOKEN:
        if (method.getStatusCode() == 200) {
            state = State.AUTHORIZED;
        } else {
            throw new ProponoException("ERROR: authorization returned code: " + method.getStatusCode());
        }
        break;

    case AUTHORIZED:
        if (token != null && secret != null) {
            accessToken = token;
            tokenSecret = secret;
            state = State.ACCESS_TOKEN;
        } else {
            throw new ProponoException("ERROR: accessToken or tokenSecret is null");
        }
        break;
    }
}

From source file:com.sun.syndication.propono.atom.client.OAuthStrategy.java

private void callOAuthUri(String uri) throws ProponoException {

    final HttpClient httpClient = new HttpClient();

    final HttpMethodBase method;
    final String content;

    Map<String, String> params = new HashMap<String, String>();
    if (params == null) {
        params = new HashMap<String, String>();
    }//  ww w . ja  v  a2  s .co m
    params.put("oauth_version", "1.0");
    if (username != null) {
        params.put("xoauth_requestor_id", username);
    }
    params.put("oauth_consumer_key", consumerKey);
    params.put("oauth_signature_method", keyType);
    params.put("oauth_timestamp", Long.toString(timestamp));
    params.put("oauth_nonce", nonce);
    params.put("oauth_callback", "none");

    OAuthServiceProvider provider = new OAuthServiceProvider(reqUrl, authzUrl, accessUrl);
    OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, provider);
    OAuthAccessor accessor = new OAuthAccessor(consumer);

    if (state == State.UNAUTHORIZED) {

        try {
            OAuthMessage message = new OAuthMessage("GET", uri, params.entrySet());
            message.sign(accessor);

            String finalUri = OAuth.addParameters(message.URL, message.getParameters());
            method = new GetMethod(finalUri);
            httpClient.executeMethod(method);
            content = method.getResponseBodyAsString();

        } catch (Exception e) {
            throw new ProponoException("ERROR fetching request token", e);
        }

    } else if (state == State.REQUEST_TOKEN) {

        try {
            params.put("oauth_token", requestToken);
            params.put("oauth_token_secret", tokenSecret);
            accessor.tokenSecret = tokenSecret;

            OAuthMessage message = new OAuthMessage("POST", uri, params.entrySet());
            message.sign(accessor);

            String finalUri = OAuth.addParameters(message.URL, message.getParameters());
            method = new PostMethod(finalUri);
            httpClient.executeMethod(method);
            content = method.getResponseBodyAsString();

        } catch (Exception e) {
            throw new ProponoException("ERROR fetching request token", e);
        }

    } else if (state == State.AUTHORIZED) {

        try {
            params.put("oauth_token", accessToken);
            params.put("oauth_token_secret", tokenSecret);
            accessor.tokenSecret = tokenSecret;

            OAuthMessage message = new OAuthMessage("GET", uri, params.entrySet());
            message.sign(accessor);

            String finalUri = OAuth.addParameters(message.URL, message.getParameters());
            method = new GetMethod(finalUri);
            httpClient.executeMethod(method);
            content = method.getResponseBodyAsString();

        } catch (Exception e) {
            throw new ProponoException("ERROR fetching request token", e);
        }

    } else {
        method = null;
        content = null;
        return;
    }

    String token = null;
    String secret = null;

    if (content != null) {
        String[] settings = content.split("&");
        for (int i = 0; i < settings.length; i++) {
            String[] setting = settings[i].split("=");
            if (setting.length > 1) {
                if ("oauth_token".equals(setting[0])) {
                    token = setting[1];
                } else if ("oauth_token_secret".equals(setting[0])) {
                    secret = setting[1];
                }
            }
        }
    }

    switch (state) {

    case UNAUTHORIZED:
        if (token != null && secret != null) {
            requestToken = token;
            tokenSecret = secret;
            state = State.REQUEST_TOKEN;
        } else {
            throw new ProponoException("ERROR: requestToken or tokenSecret is null");
        }
        break;

    case REQUEST_TOKEN:
        if (method.getStatusCode() == 200) {
            state = State.AUTHORIZED;
        } else {
            throw new ProponoException("ERROR: authorization returned code: " + method.getStatusCode());
        }
        break;

    case AUTHORIZED:
        if (token != null && secret != null) {
            accessToken = token;
            tokenSecret = secret;
            state = State.ACCESS_TOKEN;
        } else {
            throw new ProponoException("ERROR: accessToken or tokenSecret is null");
        }
        break;
    }
}

From source file:net.praqma.jenkins.rqm.request.RQMHttpClient.java

public int login() throws HttpException, IOException, GeneralSecurityException {
    log.finest("Register trusting ssl");
    registerTrustingSSL();//from  w w  w  .  jav  a  2s . c om

    GetMethod methodPart1 = new GetMethod(url.toString() + contextRoot + "/auth/authrequired");

    int response = executeMethod(methodPart1);

    followRedirects(methodPart1, response);

    GetMethod methodPart2 = new GetMethod(this.url.toString() + contextRoot + "/authenticated/identity");

    response = executeMethod(methodPart2);

    followRedirects(methodPart2, response);

    HttpMethodBase authenticationMethod = null;
    Header authenticateHeader = methodPart2.getResponseHeader("WWW-Authenticate"); //$NON-NLS-1$

    if ((response == HttpURLConnection.HTTP_UNAUTHORIZED) && (authenticateHeader != null)
            && (authenticateHeader.getValue().toLowerCase().indexOf("basic realm") == 0)) {

        super.getState().setCredentials(new AuthScope(host, port),
                new UsernamePasswordCredentials(getUsr(), getPassword()));

        String authMethod = this.url.toString() + "/authenticated/identity";
        authenticationMethod = new GetMethod(authMethod);
        response = super.executeMethod(methodPart2);
    } else {
        authenticationMethod = new PostMethod(this.url.toString() + contextRoot + "/j_security_check");
        NameValuePair[] nvps = new NameValuePair[2];
        nvps[0] = new NameValuePair("j_username", getUsr());
        nvps[1] = new NameValuePair("j_password", getPassword());
        ((PostMethod) (authenticationMethod)).addParameters(nvps);
        ((PostMethod) (authenticationMethod)).addRequestHeader("Content-Type",
                "application/x-www-form-urlencoded; charset=utf-8");
        response = executeMethod(authenticationMethod);
        Header location = authenticationMethod.getResponseHeader("X-com-ibm-team-repository-web-auth-msg");
        if (location != null && location.getValue().indexOf("authfailed") >= 0) {
            response = HttpURLConnection.HTTP_UNAUTHORIZED;
        }
    }

    if ((response != HttpURLConnection.HTTP_OK) && (response != HttpURLConnection.HTTP_MOVED_TEMP)) {
        if (response != HttpURLConnection.HTTP_UNAUTHORIZED) {
            String body = "";
            try {
                body = authenticationMethod.getResponseBodyAsString();
            } catch (Exception e) {
                log.severe(String.format("Failed to login, with response code %s %n Response body: %n %s",
                        response, body));
            }
            log.severe(String.format("Failed to login, with response code %s %n Response body: %n %s", response,
                    body));
        }
    } else {
        followRedirects(authenticationMethod, response);
        String methodText = String.format(
                "%s%s/service/com.ibm.team.repository.service.internal.webuiInitializer.IWebUIInitializerRestService/initializationData",
                url.toString(), contextRoot);
        GetMethod get3 = new GetMethod(methodText);
        response = executeMethod(get3);
        followRedirects(get3, response);
    }

    log.finest("Response was: " + response);
    return response;
}

From source file:fedora.server.security.servletfilters.pubcookie.ConnectPubcookie.java

public final void connect(String urlString, Map requestParameters, Cookie[] requestCookies,
        String truststoreLocation, String truststorePassword) {
    log.debug(this.getClass().getName() + ".connect() " + " url==" + urlString + " requestParameters=="
            + requestParameters + " requestCookies==" + requestCookies);
    responseCookies2 = null;//  w w w .j av a  2s .com
    URL url = null;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException mue) {
        log.error(this.getClass().getName() + ".connect() " + "bad configured url==" + urlString);
    }

    if (urlString.startsWith("https:") && null != truststoreLocation && !"".equals(truststoreLocation)
            && null != truststorePassword && !"".equals(truststorePassword)) {
        log.debug("setting " + FilterPubcookie.TRUSTSTORE_LOCATION_KEY + " to " + truststoreLocation);
        System.setProperty(FilterPubcookie.TRUSTSTORE_LOCATION_KEY, truststoreLocation);
        log.debug("setting " + FilterPubcookie.TRUSTSTORE_PASSWORD_KEY + " to " + truststorePassword);
        System.setProperty(FilterPubcookie.TRUSTSTORE_PASSWORD_KEY, truststorePassword);

        log.debug("setting " + FilterPubcookie.KEYSTORE_LOCATION_KEY + " to " + truststoreLocation);
        System.setProperty(FilterPubcookie.KEYSTORE_LOCATION_KEY, truststoreLocation);
        log.debug("setting " + FilterPubcookie.KEYSTORE_PASSWORD_KEY + " to " + truststorePassword);
        System.setProperty(FilterPubcookie.KEYSTORE_PASSWORD_KEY, truststorePassword);

        System.setProperty("javax.net.debug", "ssl,handshake,data,trustmanager");

    } else {
        log.debug("DIAGNOSTIC urlString==" + urlString);
        log.debug("didn't set " + FilterPubcookie.TRUSTSTORE_LOCATION_KEY + " to " + truststoreLocation);
        log.debug("didn't set " + FilterPubcookie.TRUSTSTORE_PASSWORD_KEY + " to " + truststorePassword);
    }

    /*
     * log.debug("\n-a-"); Protocol easyhttps = null; try { easyhttps = new
     * Protocol("https", (ProtocolSocketFactory) new
     * EasySSLProtocolSocketFactory(), 443); } catch (Throwable t) {
     * log.debug(t); log.debug(t.getMessage()); if (t.getCause() != null)
     * log.debug(t.getCause().getMessage()); } log.debug("\n-b-");
     * Protocol.registerProtocol("https", easyhttps); log.debug("\n-c-");
     */

    HttpClient client = new HttpClient();
    log.debug(this.getClass().getName() + ".connect() " + " b4 calling setup");
    log.debug(this.getClass().getName() + ".connect() requestCookies==" + requestCookies);
    HttpMethodBase method = setup(client, url, requestParameters, requestCookies);
    log.debug(this.getClass().getName() + ".connect() " + " after calling setup");
    int statusCode = 0;
    try {
        log.debug(this.getClass().getName() + ".connect() " + " b4 calling executeMethod");
        client.executeMethod(method);
        log.debug(this.getClass().getName() + ".connect() " + " after calling executeMethod");
        statusCode = method.getStatusCode();
        log.debug(
                this.getClass().getName() + ".connect() " + "(with configured url) statusCode==" + statusCode);
    } catch (Exception e) {
        log.error(this.getClass().getName() + ".connect() " + "failed original connect, url==" + urlString);
        log.error(e);
        log.error(e.getMessage());
        if (e.getCause() != null) {
            log.error(e.getCause().getMessage());
        }
        e.printStackTrace();
    }

    log.debug(this.getClass().getName() + ".connect() " + " status code==" + statusCode);

    if (302 == statusCode) {
        Header redirectHeader = method.getResponseHeader("Location");
        if (redirectHeader != null) {
            String redirectString = redirectHeader.getValue();
            if (redirectString != null) {
                URL redirectURL = null;
                try {
                    redirectURL = new URL(redirectString);
                    method = setup(client, redirectURL, requestParameters, requestCookies);
                } catch (MalformedURLException mue) {
                    log.error(this.getClass().getName() + ".connect() " + "bad redirect, url==" + urlString);
                }
                statusCode = 0;
                try {
                    client.executeMethod(method);
                    statusCode = method.getStatusCode();
                    log.debug(this.getClass().getName() + ".connect() " + "(on redirect) statusCode=="
                            + statusCode);
                } catch (Exception e) {
                    log.error(this.getClass().getName() + ".connect() " + "failed redirect connect");
                }
            }
        }
    }
    if (statusCode == 200) { // this is either the original, non-302, status code or the status code after redirect
        log.debug(this.getClass().getName() + ".connect() " + "status code 200");
        String content = null;
        try {
            log.debug(this.getClass().getName() + ".connect() " + "b4 gRBAS()");
            content = method.getResponseBodyAsString();
            log.debug(this.getClass().getName() + ".connect() " + "after gRBAS() content==" + content);
        } catch (IOException e) {
            log.error(this.getClass().getName() + ".connect() " + "couldn't get content");
            return;
        }
        if (content == null) {
            log.error(this.getClass().getName() + ".connect() content==null");
            return;
        } else {
            log.debug(this.getClass().getName() + ".connect() content != null, about to new Tidy");
            Tidy tidy = null;
            try {
                tidy = new Tidy();
            } catch (Throwable t) {
                log.debug("new Tidy didn't");
                log.debug(t);
                log.debug(t.getMessage());
                if (t != null) {
                    log.debug(t.getCause().getMessage());
                }
            }
            log.debug(this.getClass().getName() + ".connect() after newing Tidy, tidy==" + tidy);
            byte[] inputBytes = content.getBytes();
            log.debug(this.getClass().getName() + ".connect() A1");
            ByteArrayInputStream inputStream = new ByteArrayInputStream(inputBytes);
            log.debug(this.getClass().getName() + ".connect() A2");
            responseDocument = tidy.parseDOM(inputStream, null); //use returned root node as only output
            log.debug(this.getClass().getName() + ".connect() A3");
        }
        log.debug(this.getClass().getName() + ".connect() " + "b4 getState()");
        HttpState state = client.getState();
        log.debug(this.getClass().getName() + ".connect() state==" + state);
        try {
            responseCookies2 = method.getRequestHeaders();
            log.debug(this.getClass().getName() + ".connect() just got headers");
            for (Header element : responseCookies2) {
                log.debug(this.getClass().getName() + ".connect() header==" + element);
            }
            responseCookies = state.getCookies();
            log.debug(this.getClass().getName() + ".connect() responseCookies==" + responseCookies);
        } catch (Throwable t) {
            log.error(this.getClass().getName() + ".connect() exception==" + t.getMessage());
            if (t.getCause() != null) {
                log.error(this.getClass().getName() + ".connect() cause==" + t.getCause().getMessage());
            }
        }
        completedFully = true;
        log.debug(this.getClass().getName() + ".connect() completedFully==" + completedFully);
    }
}

From source file:com.polarion.alm.ws.client.internal.connection.CommonsHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and
 * then reads the response SOAP message back from the SOAP server
 * /*ww w .  j  a va 2  s  .  c  o  m*/
 * @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());
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new RetryHandler());

        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:com.jaspersoft.ireport.jasperserver.ws.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//from  ww w.j  av a 2 s  . com
 */
public void invoke(MessageContext msgContext) throws AxisFault {

    //test();

    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.

        //org.apache.log4j.LogManager.getRootLogger().setLevel(org.apache.log4j.Level.DEBUG);

        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);
            }

            method.addRequestHeader(HTTPConstants.HEADER_CONTENT_LENGTH, "" + requestEntity.getContentLength());
            ((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 = targetURL.getHost();
            String path = targetURL.getPath();
            boolean secure = targetURL.getProtocol().equals("https");

            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(method);

        org.apache.log4j.LogManager.getRootLogger().setLevel(org.apache.log4j.Level.ERROR);

        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:gov.va.med.imaging.proxy.ImageXChangeHttpCommonsSender.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//  w ww. j a  va2s .c o  m
*            the messsage context
* 
* @throws AxisFault
*/
public void invoke(MessageContext msgContext) throws AxisFault {
    HttpMethodBase method = null;
    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());
            log.info("POST message created with target [" + targetURL.toString() + "]");
            TransactionContext transactionContext = TransactionContextFactory.get();
            transactionContext
                    .addDebugInformation("POST message created with target [" + targetURL.toString() + "]");

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

            addContextInfo(method, httpClient, msgContext, targetURL);

            Credentials cred = httpClient.getState().getCredentials(AuthScope.ANY);
            if (cred instanceof UsernamePasswordCredentials) {
                log.trace("POST message created on client with credentials ["
                        + ((UsernamePasswordCredentials) cred).getUserName() + ", "
                        + ((UsernamePasswordCredentials) cred).getPassword() + "].");
            }

            MessageRequestEntity requestEntity = null;
            if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
                requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream);
                log.info("HTTPCommonsSender - zipping request.");
            } else {
                requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream);
                log.info("HTTPCommonsSender - not zipping request");
            }
            ((PostMethod) method).setRequestEntity(requestEntity);
        } else {
            method = new GetMethod(targetURL.toString());
            log.info("GET message created with target [" + targetURL.toString() + "]");
            addContextInfo(method, httpClient, msgContext, targetURL);
        }

        if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP))
            log.info("HTTPCommonsSender - accepting GZIP");
        else
            log.info("HTTPCommonsSender - NOT accepting GZIP");

        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null && httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10))
            method.getParams().setVersion(HttpVersion.HTTP_1_0);

        // 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);
        }

        // add HTTP header fields that the application thinks are "interesting"
        // the expectation is that these would be non-standard HTTP headers, 
        // by convention starting with "xxx-"
        VistaRealmPrincipal principal = VistaRealmSecurityContext.get();

        if (principal != null) {
            log.info("SecurityContext credentials for '" + principal.getAccessCode() + "' are available.");
            String duz = principal.getDuz();
            if (duz != null && duz.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderDuz, duz);

            String fullname = principal.getFullName();
            if (fullname != null && fullname.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderFullName, fullname);

            String sitename = principal.getSiteName();
            if (sitename != null && sitename.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSiteName, sitename);

            String sitenumber = principal.getSiteNumber();
            if (sitenumber != null && sitenumber.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSiteNumber, sitenumber);

            String ssn = principal.getSsn();
            if (ssn != null && ssn.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderSSN, ssn);

            String securityToken = principal.getSecurityToken();
            if (securityToken != null && securityToken.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderBrokerSecurityTokenId,
                        securityToken);

            String cacheLocationId = principal.getCacheLocationId();
            if (cacheLocationId != null && cacheLocationId.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderCacheLocationId,
                        cacheLocationId);

            String userDivision = principal.getUserDivision();
            if (userDivision != null && userDivision.length() > 0)
                method.addRequestHeader(TransactionContextHttpHeaders.httpHeaderUserDivision, userDivision);
        } else
            log.debug("SecurityContext credentials are NOT available.");

        method.addRequestHeader(HTTPConstants.HEADER_CACHE_CONTROL, "no-cache,no-store");
        method.addRequestHeader(HTTPConstants.HEADER_PRAGMA, "no-cache");

        try {
            log.info("Executing method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL()
                    + "]");
        } catch (IllegalStateException isX) {
        }

        // send the HTTP request and wait for a response 
        int returnCode = httpClient.executeMethod(hostConfiguration, method, null);

        TransactionContext transactionContext = TransactionContextFactory.get();
        // don't set the response code here - this is not the response code we send out, but the resposne code we get back from the data source
        //transactionContext.setResponseCode (String.valueOf (returnCode));

        // How many bytes received?
        transactionContext.setDataSourceBytesReceived(method.getBytesReceived());

        // How long did it take to start getting a response coming back?
        Long timeSent = method.getTimeRequestSent();
        Long timeReceived = method.getTimeFirstByteReceived();
        if (timeSent != null && timeReceived != null) {
            long timeTook = timeReceived.longValue() - timeSent.longValue();
            transactionContext.setTimeToFirstByte(new Long(timeTook));
        }

        // Looks like it wasn't found in cache - is there a place to set this to true if it was?
        transactionContext.setItemCached(Boolean.FALSE);

        // extract the basic HTTP header fields for content type, location and length
        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();
            try {
                log.warn("Method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL()
                        + "] failed - '" + statusMessage + "'.");
            } catch (IllegalStateException isX) {
            }

            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);
        log.info("HTTPCommonsSender - " + HTTPConstants.HEADER_CONTENT_ENCODING + "="
                + (contentEncoding == null ? "null" : contentEncoding.getValue()));

        if (contentEncoding != null) {
            if (HTTPConstants.COMPRESSION_GZIP.equalsIgnoreCase(contentEncoding.getValue())) {
                releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream);

                log.debug("HTTPCommonsSender - receiving gzipped stream.");
            } else if (ENCODING_DEFLATE.equalsIgnoreCase(contentEncoding.getValue())) {
                releaseConnectionOnCloseStream = new java.util.zip.InflaterInputStream(
                        releaseConnectionOnCloseStream);

                log.debug("HTTPCommonsSender - receiving 'deflated' stream.");
            } else {
                AxisFault fault = new AxisFault("HTTP",
                        "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null,
                        null);
                log.warn(fault.getMessage());
                throw fault;
            }

        }
        try {
            log.warn("Method [" + method.getPath() + "] on target [" + hostConfiguration.getHostURL()
                    + "] succeeded, parsing response.");
        } catch (IllegalStateException isX) {
        }

        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.isTraceEnabled()) {
            if (null == contentLength)
                log.trace("\n" + Messages.getMessage("no00", "Content-Length"));
            log.trace("\n" + Messages.getMessage("xmlRecd00"));
            log.trace("-----------------------------------------------");
            log.trace(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.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. j a v a 2  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.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 ww w  .j av  a  2 s . c o  m
 */
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/*  ww  w .  j  av  a 2  s. c o 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"));
    }
}