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

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

Introduction

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

Prototype

public Protocol getProtocol() 

Source Link

Usage

From source file:org.apache.webdav.lib.WebdavResource.java

/**
 * Test that the httpURL is the same with the client.
 *
 * @return true if the given httpURL is the client for this resource.
 *///from   ww  w . j  a  v a  2  s .c  o m
protected synchronized boolean isTheClient() throws URIException {
    HostConfiguration hostConfig = client.getHostConfiguration();
    Credentials creds = client.getState().getCredentials(null, hostConfig.getHost());
    String userName = null;
    String password = null;

    if (creds instanceof UsernamePasswordCredentials) {
        UsernamePasswordCredentials upc = (UsernamePasswordCredentials) creds;
        userName = upc.getUserName();
        password = upc.getPassword();
    }
    String ref = httpURL.getUser();
    boolean userMatches = userName != null ? userName.equals(ref) : ref == null;
    if (userMatches) {
        ref = httpURL.getPassword();
        userMatches = password != null ? password.equals(ref) : ref == null;
    } else {
        return false;
    }
    if (userMatches) {
        return httpURL.getHost().equalsIgnoreCase(hostConfig.getHost())
                && httpURL.getPort() == hostConfig.getProtocol().resolvePort(hostConfig.getPort());
    }
    return false;
}

From source file:org.eclipse.mylyn.commons.tests.net.WebUtilTest.java

public void testLocationConnectSslClientCert() throws Exception {
    if (CommonTestUtil.isCertificateAuthBroken()) {
        return; // skip test
    }//w  w  w .  ja va  2  s .  co  m

    String url = "https://mylyn.org/secure/";
    AbstractWebLocation location = new WebLocation(url);
    HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);

    if (!((PollingSslProtocolSocketFactory) hostConfiguration.getProtocol().getSocketFactory())
            .hasKeyManager()) {
        return; // skip test if keystore property is not set
    }

    GetMethod method = new GetMethod(WebUtil.getRequestPath(url));
    int statusCode = client.executeMethod(hostConfiguration, method);
    assertEquals(200, statusCode);
}

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  a v 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.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);/*w w w .  j a v a 2s  . com*/

            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

private void assertMockSocketFactory(HostConfiguration hostConfig) {
    assertTrue(hostConfig.getProtocol().getSocketFactory() instanceof MockSecureProtocolFactory);
}

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

private void assertDefaultSocketFactory(HostConfiguration hostConfig) {
    assertTrue(hostConfig.getProtocol().getSocketFactory() instanceof DefaultProtocolSocketFactory);
}

From source file:smartrics.rest.fitnesse.fixture.support.http.DeleteMethod.java

@SuppressWarnings("deprecation")
public URI getURI() throws URIException {
    HostConfiguration conf = super.getHostConfiguration();
    String scheme = conf.getProtocol().getScheme();
    String host = conf.getHost();
    int port = conf.getPort();
    return new URIBuilder().getURI(scheme, host, port, getPath(), getQueryString(), getParams());
}