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(String paramString, int paramInt, Protocol paramProtocol) 

Source Link

Usage

From source file:com.urswolfer.intellij.plugin.gerrit.rest.SslSupport.java

@Nullable
private static HttpMethod handleCertificateExceptionAndRetry(@NotNull IOException e, @NotNull String host,
        @NotNull HttpClient client, @NotNull URI uri,
        @NotNull ThrowableConvertor<String, HttpMethod, IOException> methodCreator) throws IOException {
    if (!isCertificateException(e)) {
        throw e;/* w ww  .j av a2s.c  o  m*/
    }

    if (isTrusted(host)) {
        // creating a special configuration that allows connections to non-trusted HTTPS hosts
        // see the javadoc to EasySSLProtocolSocketFactory for details
        Protocol easyHttps = new Protocol("https", (ProtocolSocketFactory) new EasySSLProtocolSocketFactory(),
                443);
        HostConfiguration hc = new HostConfiguration();
        hc.setHost(host, 443, easyHttps);
        String relativeUri = new URI(uri.getPathQuery(), false).getURI();
        // it is important to use relative URI here, otherwise our custom protocol won't work.
        // we have to recreate the method, because HttpMethod#setUri won't overwrite the host,
        // and changing host by hands (HttpMethodBase#setHostConfiguration) is deprecated.
        HttpMethod method = methodCreator.convert(relativeUri);
        client.executeMethod(hc, method);
        return method;
    }
    throw e;
}

From source file:com.datos.vfs.provider.http.HttpClientFactory.java

/**
 * Creates a new connection to the server.
 * @param builder The HttpFileSystemConfigBuilder.
 * @param scheme The protocol./*from w ww.j  a  v  a2s . c o m*/
 * @param hostname The hostname.
 * @param port The port number.
 * @param username The username.
 * @param password The password
 * @param fileSystemOptions The file system options.
 * @return a new HttpClient connection.
 * @throws FileSystemException if an error occurs.
 * @since 2.0
 */
public static HttpClient createConnection(final HttpFileSystemConfigBuilder builder, final String scheme,
        final String hostname, final int port, final String username, final String password,
        final FileSystemOptions fileSystemOptions) throws FileSystemException {
    HttpClient client;
    try {
        final HttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
        final HttpConnectionManagerParams connectionMgrParams = mgr.getParams();

        client = new HttpClient(mgr);

        final HostConfiguration config = new HostConfiguration();
        config.setHost(hostname, port, scheme);

        if (fileSystemOptions != null) {
            final String proxyHost = builder.getProxyHost(fileSystemOptions);
            final int proxyPort = builder.getProxyPort(fileSystemOptions);

            if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
                config.setProxy(proxyHost, proxyPort);
            }

            final UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions);
            if (proxyAuth != null) {
                final UserAuthenticationData authData = UserAuthenticatorUtils.authenticate(proxyAuth,
                        new UserAuthenticationData.Type[] { UserAuthenticationData.USERNAME,
                                UserAuthenticationData.PASSWORD });

                if (authData != null) {
                    final UsernamePasswordCredentials proxyCreds = new UsernamePasswordCredentials(
                            UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
                                    UserAuthenticationData.USERNAME, null)),
                            UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
                                    UserAuthenticationData.PASSWORD, null)));

                    final AuthScope scope = new AuthScope(proxyHost, AuthScope.ANY_PORT);
                    client.getState().setProxyCredentials(scope, proxyCreds);
                }

                if (builder.isPreemptiveAuth(fileSystemOptions)) {
                    final HttpClientParams httpClientParams = new HttpClientParams();
                    httpClientParams.setAuthenticationPreemptive(true);
                    client.setParams(httpClientParams);
                }
            }

            final Cookie[] cookies = builder.getCookies(fileSystemOptions);
            if (cookies != null) {
                client.getState().addCookies(cookies);
            }
        }
        /**
         * ConnectionManager set methods must be called after the host & port and proxy host & port
         * are set in the HostConfiguration. They are all used as part of the key when HttpConnectionManagerParams
         * tries to locate the host configuration.
         */
        connectionMgrParams.setMaxConnectionsPerHost(config,
                builder.getMaxConnectionsPerHost(fileSystemOptions));
        connectionMgrParams.setMaxTotalConnections(builder.getMaxTotalConnections(fileSystemOptions));

        connectionMgrParams.setConnectionTimeout(builder.getConnectionTimeout(fileSystemOptions));
        connectionMgrParams.setSoTimeout(builder.getSoTimeout(fileSystemOptions));

        client.setHostConfiguration(config);

        if (username != null) {
            final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
            final AuthScope scope = new AuthScope(hostname, AuthScope.ANY_PORT);
            client.getState().setCredentials(scope, creds);
        }
    } catch (final Exception exc) {
        throw new FileSystemException("vfs.provider.http/connect.error", exc, hostname);
    }

    return client;
}

From source file:lucee.commons.net.http.httpclient3.HTTPEngine3Impl.java

/**
 * FUNKTIONIERT NICHT, HOST WIRD NICHT UEBERNOMMEN
 * Clones a http method and sets a new url
 * @param src/* ww w.ja  v  a  2  s. c  om*/
 * @param url
 * @return
 */
private static HttpMethod clone(HttpMethod src, URL url) {
    HttpMethod trg = HttpMethodCloner.clone(src);
    HostConfiguration trgConfig = trg.getHostConfiguration();
    trgConfig.setHost(url.getHost(), url.getPort(), url.getProtocol());
    trg.setPath(url.getPath());
    trg.setQueryString(url.getQuery());

    return trg;
}

From source file:fr.cls.atoll.motu.library.misc.cas.TestCASRest.java

public static Cookie[] validateFromCAS2(String username, String password) throws Exception {

    String url = casServerUrlPrefix + "/v1/tickets?";

    String s = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
    s += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

    HttpState initialState = new HttpState();
    // Initial set of cookies can be retrieved from persistent storage and
    // re-created, using a persistence mechanism of choice,
    // Cookie mycookie = new Cookie(".foobar.com", "mycookie", "stuff", "/", null, false);

    // Create an instance of HttpClient.
    // HttpClient client = new HttpClient();
    HttpClient client = new HttpClient();

    Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 8443);

    URI uri = new URI(url + s, true);
    // use relative url only
    PostMethod httpget = new PostMethod(url);
    httpget.addParameter("username", username);
    httpget.addParameter("password", password);

    HostConfiguration hc = new HostConfiguration();
    hc.setHost("atoll-dev.cls.fr", 8443, easyhttps);
    // client.executeMethod(hc, httpget);

    client.setState(initialState);/*  w  ww  .jav  a  2  s  . c  o  m*/

    // Create a method instance.
    System.out.println(url + s);

    GetMethod method = new GetMethod(url + s);
    // GetMethod method = new GetMethod(url );

    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setProxy("proxy.cls.fr", 8080);
    client.setHostConfiguration(hostConfiguration);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    // String username = "xxx";
    // String password = "xxx";
    // Credentials credentials = new UsernamePasswordCredentials(username, password);
    // AuthScope authScope = new AuthScope("proxy.cls.fr", 8080);
    //           
    // client.getState().setProxyCredentials(authScope, credentials);
    Cookie[] cookies = null;

    try {
        // Execute the method.
        // int statusCode = client.executeMethod(method);
        int statusCode = client.executeMethod(hc, httpget);

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

        for (Header header : method.getRequestHeaders()) {
            System.out.println(header.getName());
            System.out.println(header.getValue());
        }
        // 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));

        System.out.println("Response status code: " + statusCode);
        // Get all the cookies
        cookies = client.getState().getCookies();
        // Display the cookies
        System.out.println("Present cookies: ");
        for (int i = 0; i < cookies.length; i++) {
            System.out.println(" - " + cookies[i].toExternalForm());
        }

        Assertion assertion = AssertionHolder.getAssertion();
        if (assertion == null) {
            System.out.println("<p>Assertion is null</p>");
        }

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

    return cookies;

}

From source file:gov.loc.ndmso.proxyfilter.RequestProxy.java

/**
 * This method performs the proxying of the request to the target address.
 *
 * @param target     The target address. Has to be a fully qualified address. The request is send as-is to this address.
 * @param hsRequest  The request data which should be send to the
 * @param hsResponse The response data which will contain the data returned by the proxied request to target.
 * @throws java.io.IOException Passed on from the connection logic.
 *//*from www .  j a  v  a2  s.  co  m*/
public static void execute(final String target, final String collection, final HttpServletRequest hsRequest,
        final HttpServletResponse hsResponse, MultiThreadedHttpConnectionManager connManager)
        throws IOException {
    // log.info("execute, target is " + target);
    // log.info("response commit state: " + hsResponse.isCommitted());

    if (target == null || "".equals(target) || "".equals(target.trim())) {
        log.error("The target address is not given. Please provide a target address.");
        return;
    }

    // log.info("checking url");
    final URL url;
    try {
        url = new URL(target);
    } catch (MalformedURLException e) {
        // log.error("The provided target url is not valid.", e);
        return;
    }

    // log.info("setting up the host configuration");

    final HostConfiguration config = new HostConfiguration();

    ProxyHost proxyHost = getUseProxyServer((String) hsRequest.getAttribute("use-proxy"));
    if (proxyHost != null)
        config.setProxyHost(proxyHost);

    final int port = url.getPort() != -1 ? url.getPort() : url.getDefaultPort();
    config.setHost(url.getHost(), port, "http");

    // log.info("config is " + config.toString());

    final HttpMethod targetRequest = setupProxyRequest(hsRequest, url);
    if (targetRequest == null) {
        // log.error("Unsupported request method found: " + hsRequest.getMethod());
        return;
    }

    //perform the request to the target server
    final HttpClient client = new HttpClient(connManager);
    //if (log.isInfoEnabled()) {
    // log.info("client state" + client.getState());
    // log.info("client params" + client.getParams().toString());
    // log.info("executeMethod / fetching data ...");
    //}

    final int result = client.executeMethod(config, targetRequest);

    //copy the target response headers to our response
    setupResponseHeaders(targetRequest, hsResponse);

    String binRegex = ".*\\.(?i)(jpg|tif|png|gif|bmp|mp3|mpg)(.*$)*";
    String binRegexRedux = ".*(?i)(\\/thumb)(.*$)*";

    if (target.matches(binRegex) || target.matches(binRegexRedux)) {
        // log.info("binRegex matched: " + target);
        InputStream originalResponseStream = targetRequest.getResponseBodyAsStream();

        if (originalResponseStream != null) {

            if (targetRequest.getResponseHeaders().toString().matches("(?i).*content-type.*")) {
                PrintWriter responseStream = hsResponse.getWriter();
                copyStreamText(targetRequest.getResponseBodyAsString(), responseStream);
            } else {
                OutputStream responseStream = hsResponse.getOutputStream();
                copyStreamBinary(originalResponseStream, responseStream);
            }
        }

    } else {
        // log.info("binRegex NOT matched: " + target);
        String proxyResponseStr = targetRequest.getResponseBodyAsString();
        // the body might be null, i.e. for responses with cache-headers which leave out the body

        if (proxyResponseStr != null) {
            //proxyResponseStr = proxyResponseStr.replaceAll("xqy", "jsp");

            proxyResponseStr = proxyResponseStr.replaceAll("National Library Catalog",
                    "Library of Congress Data Service");
            proxyResponseStr = proxyResponseStr.replaceAll("Library of Congress collections",
                    "Library of Congress bibliographic data");
            proxyResponseStr = proxyResponseStr.replaceAll("Library of Congress Collections",
                    "Library of Congress Bibliographic Data");

            proxyResponseStr = proxyResponseStr.replaceAll("action=\"/", "action=\"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("href=\"/", "href=\"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("href=\"/diglib/loc\\.",
                    "href=\"/diglib/" + collection + "/loc.");
            proxyResponseStr = proxyResponseStr.replaceAll("src=\"/", "src=\"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("value=\"/", "value=\"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("url\\(/", "url\\(/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("url\\(\"/", "url\\(\"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("src'\\) == \"/", "src'\\) == \"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("src\", \"/", "src\", \"/diglib/");
            proxyResponseStr = proxyResponseStr.replaceAll("natlibcat@loc.gov", "ndmso@loc.gov");

            proxyResponseStr = proxyResponseStr.replaceAll("/nlc/", "/lcds/");
            proxyResponseStr = proxyResponseStr.replaceAll("/lcwa/", "/lcwanew/");
            //proxyResponseStr = proxyResponseStr.replaceAll("/tohap/", "/x-tohap/");

            proxyResponseStr = proxyResponseStr.replaceAll(".xqy", ".jsp");

            PrintWriter responseStream = hsResponse.getWriter();
            copyStreamText(proxyResponseStr, responseStream);
        }
    }

    // log.info("set up response, result code was " + result);
    targetRequest.releaseConnection();

    // SimpleHttpConnectionManager connManager = (SimpleHttpConnectionManager) client.getHttpConnectionManager();
    // connManager.closeIdleConnections(1000);

    // HttpConnection httpConn = connManager.getConnection(config);
    // httpConn.releaseConnection();

}

From source file:com.exalead.io.failover.MonitoredHttpConnectionManager.java

/**
 * Gets the host configuration for a connection.
 * @param conn the connection to get the configuration of
 * @return a new HostConfiguration//w  ww  .  j a va 2s.c  o m
 */
static HostConfiguration rebuildConfigurationFromConnection(HttpConnection conn) {
    HostConfiguration connectionConfiguration = new HostConfiguration();
    connectionConfiguration.setHost(conn.getHost(), conn.getPort(), conn.getProtocol());
    if (conn.getLocalAddress() != null) {
        connectionConfiguration.setLocalAddress(conn.getLocalAddress());
    }
    if (conn.getProxyHost() != null) {
        connectionConfiguration.setProxy(conn.getProxyHost(), conn.getProxyPort());
    }
    return connectionConfiguration;
}

From source file:com.navercorp.pinpoint.plugin.httpclient3.HttpClientIT.java

@Test
public void hostConfig() throws Exception {
    HttpClient client = new HttpClient();
    client.getParams().setConnectionManagerTimeout(CONNECTION_TIMEOUT);
    client.getParams().setSoTimeout(SO_TIMEOUT);

    HostConfiguration config = new HostConfiguration();
    config.setHost("weather.naver.com", 80, "http");
    GetMethod method = new GetMethod("/rgn/cityWetrMain.nhn");

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    method.setQueryString(new NameValuePair[] { new NameValuePair("key2", "value2") });

    try {//from  w  w w  . ja v a 2  s. co  m
        // Execute the method.
        client.executeMethod(config, method);
    } catch (Exception ignored) {
    } finally {
        method.releaseConnection();
    }

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
}

From source file:com.smartitengineering.util.rest.client.jersey.cache.CustomApacheHttpClientResponseResolver.java

/**
 * Determines the HttpClient's request method from the HTTPMethod enum.
 *
 * @param method     the HTTPCache enum that determines
 * @param requestURI the request URI.// w ww .  jav  a 2s  .  c  om
 * @return a new HttpMethod subclass.
 */
protected HttpMethod getMethod(HTTPMethod method, URI requestURI) {
    if (CONNECT.equals(method)) {
        HostConfiguration config = new HostConfiguration();
        config.setHost(requestURI.getHost(), requestURI.getPort(), requestURI.getScheme());
        return new ConnectMethod(config);
    } else if (DELETE.equals(method)) {
        return new CustomHttpMethod(HTTPMethod.DELETE.name(), requestURI.toString());
    } else if (GET.equals(method)) {
        return new GetMethod(requestURI.toString());
    } else if (HEAD.equals(method)) {
        return new HeadMethod(requestURI.toString());
    } else if (OPTIONS.equals(method)) {
        return new OptionsMethod(requestURI.toString());
    } else if (POST.equals(method)) {
        return new PostMethod(requestURI.toString());
    } else if (PUT.equals(method)) {
        return new PutMethod(requestURI.toString());
    } else if (TRACE.equals(method)) {
        return new TraceMethod(requestURI.toString());
    } else {
        return new CustomHttpMethod(method.name(), requestURI.toString());
    }
}

From source file:edu.usc.corral.api.Client.java

public Client(String host, int port) {
    Protocol httpg = new Protocol("httpg", new SocketFactory(), 9443);

    HostConfiguration hc = new HostConfiguration();
    hc.setHost(host, port, httpg);

    connmgr = new SimpleHttpConnectionManager();

    httpclient = new HttpClient();
    httpclient.setHostConfiguration(hc);
    httpclient.setHttpConnectionManager(connmgr);
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClientTest.java

@Test(expectedExceptions = HttpClientException.class)
public void testGetThrowsException() throws Exception {
    ApacheHttpClient31BackedHttpClient client = new ApacheHttpClient31BackedHttpClient(httpClient,
            new HashMap<String, String>());

    final String path = "/path/to/endpoint";

    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost("foobar.com", 3456, Protocol.getProtocol("http"));
    when(httpClient.getHostConfiguration()).thenReturn(hostConfiguration);
    when(httpClient.executeMethod(Matchers.<HttpMethod>any())).thenThrow(new IOException());

    client.get(path);/*from  w  w  w .  j  a v  a  2s. c om*/
}