Example usage for org.apache.commons.httpclient HostConfiguration getHost

List of usage examples for org.apache.commons.httpclient HostConfiguration getHost

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HostConfiguration getHost.

Prototype

public String getHost() 

Source Link

Usage

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

/**
 * invoke creates a socket connection, sends the request SOAP message and then reads the response SOAP message back
 * from the SOAP server//  w  w  w . j av  a  2s  .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());

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

        boolean posting = true;

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

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

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

            addContextInfo(method, httpClient, msgContext, targetURL);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:org.intalio.tempo.workflow.tas.nuxeo.NuxeoStorageStrategy.java

/**
 * Everything we need to do to have an authenticated http client
 * //from  w  w  w  .  j a v a  2 s.com
 * @throws URIException
 */
private void initHttpClient() throws URIException {
    httpclient = new HttpClient();
    HostConfiguration hostConfig = new HostConfiguration();
    org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(getNuxeoRestUrl(), false);
    hostConfig.setHost(uri);
    HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    int maxHostConnections = 20;
    params.setMaxConnectionsPerHost(hostConfig, maxHostConnections);
    connectionManager.setParams(params);
    httpclient = new HttpClient(connectionManager);
    httpclient.setHostConfiguration(hostConfig);
    Credentials creds = new UsernamePasswordCredentials(userName, password);
    AuthScope authScope = new AuthScope(hostConfig.getHost(), hostConfig.getPort());
    httpclient.getState().setCredentials(authScope, creds);
    httpclient.getParams().setAuthenticationPreemptive(true);
}

From source file:org.mule.transport.http.MuleHostConfigurationTestCase.java

@Test
public void testSetHostViaUri() throws Exception {
    HostConfiguration hostConfig = createHostConfiguration();

    URI uri = new URI("http://www.mulesoft.org:8080", false);
    hostConfig.setHost(uri);//  w  w w. j av  a2 s . c o  m

    assertMockSocketFactory(hostConfig);
    assertEquals("www.mulesoft.org", hostConfig.getHost());
    assertEquals(8080, hostConfig.getPort());
}

From source file:org.mule.transport.http.MuleHostConfigurationTestCase.java

@Test
public void testSetHostViaUriWithDifferentProtocol() throws Exception {
    new DifferentProtocolTemplate() {
        protected void doTest() throws Exception {
            HostConfiguration hostConfig = createHostConfiguration();

            URI uri = new URI("httpx://www.mulesoft.org:8080", false);
            hostConfig.setHost(uri);/*from  ww  w .j  a  v  a 2 s. c o  m*/

            assertTrue(hostConfig.getProtocol().getSocketFactory() instanceof DefaultProtocolSocketFactory);
            assertEquals("www.mulesoft.org", hostConfig.getHost());
            assertEquals(8080, hostConfig.getPort());
        }
    }.test();
}

From source file:org.mule.transport.http.MuleHostConfigurationTestCase.java

@Test
public void testSetHostViaHttpHost() {
    HostConfiguration hostConfig = createHostConfiguration();

    HttpHost host = new HttpHost("www.mulesoft.org", 8080);
    hostConfig.setHost(host);/*from   ww  w.  j  av a  2 s  .c o  m*/

    assertMockSocketFactory(hostConfig);
    assertEquals("www.mulesoft.org", hostConfig.getHost());
    assertEquals(8080, hostConfig.getPort());
}

From source file:org.mule.transport.http.MuleHostConfigurationTestCase.java

@Test
public void testSetHostViaHostAndPortAndProtocolName() {
    HostConfiguration hostConfig = createHostConfiguration();

    hostConfig.setHost("www.mulesoft.org", 8080, "http");

    assertMockSocketFactory(hostConfig);
    assertEquals("www.mulesoft.org", hostConfig.getHost());
    assertEquals(8080, hostConfig.getPort());
}

From source file:org.mule.transport.http.MuleHostConfigurationTestCase.java

@Test
public void testSetHostViaHostAndPortAndProtocolNameWithDifferentProtocol() throws Exception {
    new DifferentProtocolTemplate() {
        protected void doTest() throws Exception {
            HostConfiguration hostConfig = createHostConfiguration();

            hostConfig.setHost("www.mulesoft.org", 8080, "httpx");

            assertDefaultSocketFactory(hostConfig);
            assertEquals("www.mulesoft.org", hostConfig.getHost());
            assertEquals(8080, hostConfig.getPort());
        }// www.  j  a  v a  2 s.c o m
    }.test();
}

From source file:org.mule.transport.http.MuleHostConfigurationTestCase.java

@SuppressWarnings("deprecation")
@Test/*from  ww  w . ja  va2s.  c om*/
public void testSetHostViaHostAndVirtualHostAndPortAndProtocol() {
    HostConfiguration hostConfig = createHostConfiguration();

    Protocol protocol = Protocol.getProtocol("http");
    hostConfig.setHost("www.mulesoft.org", "www.mulesoft.com", 8080, protocol);

    assertMockSocketFactory(hostConfig);
    assertEquals("www.mulesoft.org", hostConfig.getHost());
    assertEquals(8080, hostConfig.getPort());
    assertEquals("www.mulesoft.com", hostConfig.getVirtualHost());
}

From source file:org.mule.transport.http.MuleHostConfigurationTestCase.java

@SuppressWarnings("deprecation")
@Test/* ww  w. ja  v  a2s.  c  o  m*/
public void testSetHostViaHostAndVirtualHostAndPortAndProtocolWithDifferentProtocol() throws Exception {
    new DifferentProtocolTemplate() {
        protected void doTest() throws Exception {
            HostConfiguration hostConfig = createHostConfiguration();

            Protocol protocol = Protocol.getProtocol("httpx");
            hostConfig.setHost("www.mulesoft.org", "www.mulesoft.com", 8080, protocol);

            assertDefaultSocketFactory(hostConfig);
            assertEquals("www.mulesoft.org", hostConfig.getHost());
            assertEquals(8080, hostConfig.getPort());
            assertEquals("www.mulesoft.com", hostConfig.getVirtualHost());
        }
    }.test();
}

From source file:org.mule.transport.http.MuleHostConfigurationTestCase.java

@Test
public void testSetHostViaHostAndPort() {
    HostConfiguration hostConfig = createHostConfiguration();

    hostConfig.setHost("www.mulesoft.org", 8080);

    assertMockSocketFactory(hostConfig);
    assertEquals("www.mulesoft.org", hostConfig.getHost());
    assertEquals(8080, hostConfig.getPort());
}