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

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

Introduction

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

Prototype

public void setHost(URI paramURI) 

Source Link

Usage

From source file:org.apache.servicemix.http.processors.ProviderProcessor.java

private HostConfiguration getHostConfiguration(String locationURI, MessageExchange exchange,
        NormalizedMessage message) throws Exception {
    HostConfiguration host;
    URI uri = new URI(locationURI, false);
    if (uri.getScheme().equals("https")) {
        synchronized (this) {
            if (protocol == null) {
                ProtocolSocketFactory sf = new CommonsHttpSSLSocketFactory(endpoint.getSsl(),
                        KeystoreManager.Proxy.create(endpoint.getKeystoreManager()));
                protocol = new Protocol("https", sf, 443);
            }/*from w  w  w.j a  v  a 2  s  .co m*/
        }
        HttpHost httphost = new HttpHost(uri.getHost(), uri.getPort(), protocol);
        host = new HostConfiguration();
        host.setHost(httphost);
    } else {
        host = new HostConfiguration();
        host.setHost(uri.getHost(), uri.getPort());
    }
    if (endpoint.getProxy() != null) {
        if ((endpoint.getProxy().getProxyHost() != null) && (endpoint.getProxy().getProxyPort() != 0)) {
            host.setProxy(endpoint.getProxy().getProxyHost(), endpoint.getProxy().getProxyPort());
        }
        if (endpoint.getProxy().getProxyCredentials() != null) {
            endpoint.getProxy().getProxyCredentials().applyProxyCredentials(getClient(), exchange, message);
        }
    } else if ((getConfiguration().getProxyHost() != null) && (getConfiguration().getProxyPort() != 0)) {
        host.setProxy(getConfiguration().getProxyHost(), getConfiguration().getProxyPort());
    }
    //host.getParams().setLongParameter(HttpConnectionParams.CONNECTION_TIMEOUT, getClient().getParams().getSoTimeout());
    return host;
}

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

/**
 * Get a <code>HttpClient</code> instance.
 * This method returns a new client instance, when reset is true.
 *
 * @param httpURL The http URL to connect.  only used the authority part.
 * @param reset The reset flag to represent whether the saved information
 *              is used or not.// w ww.  ja  va2 s .c o  m
 * @return An instance of <code>HttpClient</code>.
 * @exception IOException
 */
public HttpClient getSessionInstance(HttpURL httpURL, boolean reset) throws IOException {

    if (reset || client == null) {
        client = new HttpClient();
        // Set a state which allows lock tracking
        client.setState(new WebdavState());
        HostConfiguration hostConfig = client.getHostConfiguration();
        hostConfig.setHost(httpURL);
        if (proxyHost != null && proxyPort > 0)
            hostConfig.setProxy(proxyHost, proxyPort);

        if (hostCredentials == null) {
            String userName = httpURL.getUser();
            if (userName != null && userName.length() > 0) {
                hostCredentials = new UsernamePasswordCredentials(userName, httpURL.getPassword());
            }
        }

        if (hostCredentials != null) {
            HttpState clientState = client.getState();
            clientState.setCredentials(null, httpURL.getHost(), hostCredentials);
            clientState.setAuthenticationPreemptive(true);
        }

        if (proxyCredentials != null) {
            client.getState().setProxyCredentials(null, proxyHost, proxyCredentials);
        }
    }

    return client;
}

From source file:org.apache.xmlrpc.CommonsXmlRpcTransport.java

public InputStream sendXmlRpc(byte[] request) throws IOException, XmlRpcClientException {
    method = new PostMethod(url.toString());
    method.setHttp11(http11);//  w  w w.j  a v a  2 s .  c o m
    method.setRequestHeader(new Header("Content-Type", "text/xml"));

    if (rgzip)
        method.setRequestHeader(new Header("Content-Encoding", "gzip"));

    if (gzip)
        method.setRequestHeader(new Header("Accept-Encoding", "gzip"));

    method.setRequestHeader(userAgentHeader);

    if (rgzip) {
        ByteArrayOutputStream lBo = new ByteArrayOutputStream();
        GZIPOutputStream lGzo = new GZIPOutputStream(lBo);
        lGzo.write(request);
        lGzo.finish();
        lGzo.close();
        byte[] lArray = lBo.toByteArray();
        method.setRequestBody(new ByteArrayInputStream(lArray));
        method.setRequestContentLength(-1);
    } else
        method.setRequestBody(new ByteArrayInputStream(request));

    URI hostURI = new URI(url.toString());
    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.setHost(hostURI);
    client.executeMethod(hostConfig, method);

    boolean lgzipo = false;

    Header lHeader = method.getResponseHeader("Content-Encoding");
    if (lHeader != null) {
        String lValue = lHeader.getValue();
        if (lValue != null)
            lgzipo = (lValue.indexOf("gzip") >= 0);
    }

    if (lgzipo)
        return (new GZIPInputStream(method.getResponseBodyAsStream()));
    else
        return method.getResponseBodyAsStream();
}

From source file:org.crosswire.common.util.WebResource.java

public WebResource(URI theURI, String theProxyHost, Integer theProxyPort) {
    uri = theURI;// w  w w.  j ava  2  s  .c om
    client = new HttpClient();
    HostConfiguration config = client.getHostConfiguration();
    config.setHost(new HttpHost(theURI.getHost(), theURI.getPort()));
    if (theProxyHost != null && theProxyHost.length() > 0) {
        config.setProxyHost(new ProxyHost(theProxyHost, theProxyPort == null ? -1 : theProxyPort.intValue()));
    }
}

From source file:org.elasticsearch.hadoop.rest.commonshttp.CommonsHttpTransport.java

public CommonsHttpTransport(Settings settings, String host) {
    this.settings = settings;
    httpInfo = host;//from   w ww . jav  a2s  .  c o  m

    HttpClientParams params = new HttpClientParams();
    params.setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(settings.getHttpRetries(), false) {

                @Override
                public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) {
                    if (super.retryMethod(method, exception, executionCount)) {
                        stats.netRetries++;
                        return true;
                    }
                    return false;
                }
            });

    params.setConnectionManagerTimeout(settings.getHttpTimeout());
    params.setSoTimeout((int) settings.getHttpTimeout());
    HostConfiguration hostConfig = new HostConfiguration();

    hostConfig = setupSSLIfNeeded(settings, hostConfig);
    hostConfig = setupSocksProxy(settings, hostConfig);
    Object[] authSettings = setupHttpProxy(settings, hostConfig);
    hostConfig = (HostConfiguration) authSettings[0];

    try {
        hostConfig.setHost(new URI(escapeUri(host, settings.getNetworkSSLEnabled()), false));
    } catch (IOException ex) {
        throw new EsHadoopTransportException("Invalid target URI " + host, ex);
    }
    client = new HttpClient(params, new SocketTrackingConnectionManager());
    client.setHostConfiguration(hostConfig);

    addHttpAuth(settings, authSettings);
    completeAuth(authSettings);

    HttpConnectionManagerParams connectionParams = client.getHttpConnectionManager().getParams();
    // make sure to disable Nagle's protocol
    connectionParams.setTcpNoDelay(true);

    if (log.isTraceEnabled()) {
        log.trace("Opening HTTP transport to " + httpInfo);
    }
}

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

public RestClient(Settings settings) {
    HttpClientParams params = new HttpClientParams();
    params.setConnectionManagerTimeout(settings.getHttpTimeout());

    client = new HttpClient(params);
    HostConfiguration hostConfig = new HostConfiguration();
    String targetUri = settings.getTargetUri();
    try {/*ww  w. ja va2 s  .c o m*/
        hostConfig.setHost(new URI(targetUri, false));
    } catch (IOException ex) {
        throw new IllegalArgumentException("Invalid target URI " + targetUri, ex);
    }
    client.setHostConfiguration(hostConfig);

    scrollKeepAlive = TimeValue.timeValueMillis(settings.getScrollKeepAlive());
    indexReadMissingAsEmpty = settings.getIndexReadMissingAsEmpty();
}

From source file:org.exoplatform.calendar.service.impl.RemoteCalendarServiceImpl.java

@Override
public boolean isValidRemoteUrl(String url, String type, String remoteUser, String remotePassword)
        throws IOException, UnsupportedOperationException {
    try {/*from   w  w  w  . ja  v  a  2 s.  c  o  m*/
        HttpClient client = new HttpClient();
        HostConfiguration hostConfig = new HostConfiguration();
        String host = new URL(url).getHost();
        if (StringUtils.isEmpty(host))
            host = url;
        hostConfig.setHost(host);
        client.setHostConfiguration(hostConfig);
        Credentials credentials = null;
        client.setHostConfiguration(hostConfig);
        if (!StringUtils.isEmpty(remoteUser)) {
            credentials = new UsernamePasswordCredentials(remoteUser, remotePassword);
            client.getState().setCredentials(new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                    credentials);
        }

        if (CalendarService.ICALENDAR.equals(type)) {
            GetMethod get = new GetMethod(url);
            client.executeMethod(get);
            int statusCode = get.getStatusCode();
            get.releaseConnection();
            return (statusCode == HttpURLConnection.HTTP_OK);
        } else {
            if (CalendarService.CALDAV.equals(type)) {
                OptionsMethod options = new OptionsMethod(url);
                client.executeMethod(options);
                Header header = options.getResponseHeader("DAV");
                options.releaseConnection();
                if (header == null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Cannot connect to remoter server or not support WebDav access");
                    }
                    return false;
                }
                Boolean support = header.toString().contains("calendar-access");
                options.releaseConnection();
                if (!support) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Remote server does not support CalDav access");
                    }
                    throw new UnsupportedOperationException("Remote server does not support CalDav access");
                }
                return support;
            }
            return false;
        }
    } catch (MalformedURLException e) {
        if (logger.isDebugEnabled())
            logger.debug(e.getMessage(), e);
        throw new IOException("URL is invalid. Maybe no legal protocol or URl could not be parsed");
    } catch (IOException e) {
        if (logger.isDebugEnabled())
            logger.debug(e.getMessage(), e);
        throw new IOException("Error occurs when connecting to remote server");
    }
}

From source file:org.exoplatform.calendar.service.impl.RemoteCalendarServiceImpl.java

/**
 * Get the HttpClient object to prepare for the connection with remote server
 * @param remoteCalendar holds information about remote server
 * @return HttpClient object/*from   w  ww. j a  v  a 2 s .co  m*/
 * @throws Exception
 */
public HttpClient getRemoteClient(RemoteCalendar remoteCalendar) throws Exception {
    HostConfiguration hostConfig = new HostConfiguration();
    String host = new URL(remoteCalendar.getRemoteUrl()).getHost();
    if (Utils.isEmpty(host))
        host = remoteCalendar.getRemoteUrl();
    hostConfig.setHost(host);
    HttpClient client = new HttpClient();
    client.setHostConfiguration(hostConfig);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
    client.getHttpConnectionManager().getParams().setSoTimeout(10000);
    // basic authentication
    if (!Utils.isEmpty(remoteCalendar.getRemoteUser())) {
        Credentials credentials = new UsernamePasswordCredentials(remoteCalendar.getRemoteUser(),
                remoteCalendar.getRemotePassword());
        client.getState().setCredentials(new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                credentials);
    }
    return client;
}

From source file:org.gss_project.gss.web.client.TestClient.java

public static void main(String[] args) {
    String user = "ebstest@grnet-hq.admin.grnet.gr";
    String token = "PcxaZ/4oIqCqIvCYgsUcKr1hAFcsW40G3kcWJSRPJV5GjzoNuo8RsA==";
    String host = "pithos.grnet.gr";
    String restPath = "/pithos/rest";
    String path = "/" + user + "/files/";
    String now = DateUtil.formatDate(new Date());
    String signature = sign("GET", now, path, token);
    HttpClient client = new HttpClient();
    HostConfiguration hostconfig = new HostConfiguration();
    hostconfig.setHost(host);
    HttpMethod method = new GetMethod(restPath + path);
    Collection<Header> headers = new ArrayList<Header>();
    Header auth = new Header("Authorization", user + " " + signature);
    headers.add(auth);/*from   ww w .j  a  va2  s.c o m*/
    Header date = new Header("X-GSS-Date", now);
    headers.add(date);
    System.out.println(headers.toString());
    hostconfig.getParams().setParameter("http.default-headers", headers);
    try {
        // Execute the method.
        int statusCode = client.executeMethod(hostconfig, method);

        if (statusCode != HttpStatus.SC_OK)
            System.err.println("Method failed: " + method.getStatusLine());

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        System.out.println(new String(responseBody));
    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

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