Example usage for org.apache.commons.httpclient HttpClient getHostConfiguration

List of usage examples for org.apache.commons.httpclient HttpClient getHostConfiguration

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpClient getHostConfiguration.

Prototype

public HostConfiguration getHostConfiguration()

Source Link

Usage

From source file:com.cloud.utils.net.HTTPUtils.java

/**
 * @param proxy//  w  w w.  j  ava 2s. c o m
 * @param httpClient
 */
public static void setProxy(Proxy proxy, HttpClient httpClient) {
    if (proxy != null && httpClient != null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Setting proxy with host " + proxy.getHost() + " and port " + proxy.getPort()
                    + " for host " + httpClient.getHostConfiguration().getHost() + ":"
                    + httpClient.getHostConfiguration().getPort());
        }

        httpClient.getHostConfiguration().setProxy(proxy.getHost(), proxy.getPort());
        if (proxy.getUserName() != null && proxy.getPassword() != null) {
            httpClient.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxy.getUserName(), proxy.getPassword()));
        }
    }
}

From source file:com.sun.faban.harness.webclient.RunUploader.java

/**
 * Client call to upload the run back to the originating server.
 * This method does nothing if the run is local.
 * @param runId The id of the run//  ww  w  . jav a  2s.c om
 * @throws IOException If the upload fails
 */
public static void uploadIfOrigin(String runId) throws IOException {

    // 1. Check origin
    File originFile = new File(
            Config.OUT_DIR + File.separator + runId + File.separator + "META-INF" + File.separator + "origin");

    if (!originFile.isFile())
        return; // Is local run, do nothing.

    String originSpec = readStringFromFile(originFile);
    int idx = originSpec.lastIndexOf('.');
    if (idx == -1) { // This is wrong, we do not accept this.
        logger.severe("Bad origin spec.");
        return;
    }
    idx = originSpec.lastIndexOf('.', idx - 1);
    if (idx == -1) {
        logger.severe("Bad origin spec.");
        return;
    }

    String host = originSpec.substring(0, idx);
    String key = null;
    URL target = null;
    String proxyHost = null;
    int proxyPort = -1;

    // Search the poll hosts for this origin.
    for (int i = 0; i < Config.pollHosts.length; i++) {
        Config.HostInfo pollHost = Config.pollHosts[i];
        if (host.equals(pollHost.name)) {
            key = pollHost.key;
            target = new URL(pollHost.url, "upload");
            proxyHost = pollHost.proxyHost;
            proxyPort = pollHost.proxyPort;
            break;
        }
    }

    if (key == null) {
        logger.severe("Origin host/url/key not found!");
        return;
    }

    // 2. Jar up the run
    String[] files = new File(Config.OUT_DIR, runId).list();
    File jarFile = new File(Config.TMP_DIR, runId + ".jar");
    jar(Config.OUT_DIR + runId, files, jarFile.getAbsolutePath());

    // 3. Upload the run
    ArrayList<Part> params = new ArrayList<Part>();
    //MultipartPostMethod post = new MultipartPostMethod(target.toString());
    params.add(new StringPart("host", Config.FABAN_HOST));
    params.add(new StringPart("key", key));
    params.add(new StringPart("origin", "true"));
    params.add(new FilePart("jarfile", jarFile));
    Part[] parts = new Part[params.size()];
    parts = params.toArray(parts);
    PostMethod post = new PostMethod(target.toString());
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
    HttpClient client = new HttpClient();
    if (proxyHost != null)
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    int status = client.executeMethod(post);
    if (status == HttpStatus.SC_FORBIDDEN)
        logger.severe("Server " + host + " denied permission to upload run " + runId + '!');
    else if (status == HttpStatus.SC_NOT_ACCEPTABLE)
        logger.severe("Run " + runId + " origin error!");
    else if (status != HttpStatus.SC_CREATED)
        logger.severe(
                "Server responded with status code " + status + ". Status code 201 (SC_CREATED) expected.");
    jarFile.delete();
}

From source file:com.carrotsearch.util.httpclient.HttpClientFactory.java

/**
 * Configure HTTP proxy from system properties, if available.
 *//* w w w .  j  a v a2s . c om*/
private static void configureProxy(HttpClient httpClient) {
    final String proxyHost = System.getProperty(PROPERTY_NAME_PROXY_HOST);
    final String proxyPort = System.getProperty(PROPERTY_NAME_PROXY_PORT);

    if (!StringUtils.isEmpty(proxyHost) && !StringUtils.isEmpty(proxyPort)) {
        try {
            final int port = Integer.parseInt(proxyPort);
            httpClient.getHostConfiguration().setProxy(proxyHost, port);
        } catch (NumberFormatException e) {
            // Ignore.
        }
    }
}

From source file:jp.go.nict.langrid.servicesupervisor.invocationprocessor.executor.ServiceInvoker.java

/**
 * //from   www  .  j ava2s.c  om
 * 
 */
public static int invoke(URL url, String userName, String password, Map<String, String> headers,
        InputStream input, HttpServletResponse output, OutputStream errorOut, int connectionTimeout,
        int soTimeout) throws IOException, SocketTimeoutException {
    HttpClient client = HttpClientUtil.createHttpClientWithHostConfig(url);
    SimpleHttpConnectionManager manager = new SimpleHttpConnectionManager(true);
    manager.getParams().setConnectionTimeout(connectionTimeout);
    manager.getParams().setSoTimeout(soTimeout);
    manager.getParams().setMaxConnectionsPerHost(client.getHostConfiguration(), 2);
    client.setHttpConnectionManager(manager);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(0, false));

    PostMethod method = new PostMethod(url.getFile());
    method.setRequestEntity(new InputStreamRequestEntity(input));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        method.addRequestHeader(e.getKey(), e.getValue());
    }
    if (!headers.containsKey("Content-Type"))
        method.addRequestHeader("Content-Type", "text/xml; charset=utf-8");
    if (!headers.containsKey("Accept"))
        method.addRequestHeader("Accept", "application/soap+xml, application/dime, multipart/related, text/*");
    if (!headers.containsKey("SOAPAction"))
        method.addRequestHeader("SOAPAction", "\"\"");
    if (!headers.containsKey("User-Agent"))
        method.addRequestHeader("User-Agent", "Langrid Service Invoker/1.0");
    if (userName != null) {
        int port = url.getPort();
        if (port == -1) {
            port = url.getDefaultPort();
            if (port == -1) {
                port = 80;
            }
        }
        if (password == null) {
            password = "";
        }
        client.getState().setCredentials(new AuthScope(url.getHost(), port, null),
                new UsernamePasswordCredentials(userName, password));
        client.getParams().setAuthenticationPreemptive(true);
        method.setDoAuthentication(true);
    }

    try {
        int status;
        try {
            status = client.executeMethod(method);
        } catch (SocketTimeoutException e) {
            status = HttpServletResponse.SC_REQUEST_TIMEOUT;
        }
        output.setStatus(status);
        if (status == 200) {
            for (Header h : method.getResponseHeaders()) {
                String name = h.getName();
                if (name.startsWith("X-Langrid") || (!throughHeaders.contains(name.toLowerCase())))
                    continue;
                String value = h.getValue();
                output.addHeader(name, value);
            }
            OutputStream os = output.getOutputStream();
            StreamUtil.transfer(method.getResponseBodyAsStream(), os);
            os.flush();
        } else if (status == HttpServletResponse.SC_REQUEST_TIMEOUT) {
        } else {
            StreamUtil.transfer(method.getResponseBodyAsStream(), errorOut);
        }
        return status;
    } finally {
        manager.shutdown();
    }
}

From source file:com.nokia.carbide.internal.bugreport.model.Communication.java

public static void setProxyData(HttpClient client, PostMethod postMethod) {
    URI uri = getURI(postMethod);
    if (uri == null) {
        return;/* www . j  a  v  a  2  s. c  o m*/
    }
    IProxyData proxyData = ProxyUtils.getProxyData(uri);
    if (proxyData == null) {
        return;
    }
    String host = proxyData.getHost();
    int port = proxyData.getPort();
    client.getHostConfiguration().setProxy(host, port);
    if (proxyData.isRequiresAuthentication()) {
        String userId = proxyData.getUserId();
        String password = proxyData.getPassword();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userId, password);
        AuthScope authScope = new AuthScope(host, port);
        client.getState().setCredentials(authScope, credentials);
        postMethod.setDoAuthentication(true);
    }
}

From source file:com.gs.jrpip.client.FastServletProxyFactory.java

public static HttpClient getHttpClient(AuthenticatedUrl url) {
    HttpClient httpClient = new HttpClient(HTTP_CONNECTION_MANAGER);
    httpClient.getHostConfiguration().setHost(url.getHost(), url.getPort());
    httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, NoRetryRetryHandler.getInstance());
    url.setCredentialsOnClient(httpClient);
    return httpClient;
}

From source file:es.uvigo.ei.sing.jarvest.core.HTTPUtils.java

private static HttpClient createClient() {
    @SuppressWarnings("deprecation")
    Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
    Protocol.registerProtocol("https", easyhttps);
    if (System.getProperty("httpclient.useragent") == null) {
        System.getProperties().setProperty("httpclient.useragent", DEFAULT_USER_AGENT);
    }/*from  w  w w . java  2 s  . c o  m*/
    HttpClient client = new HttpClient();
    if (System.getProperty("http.proxyHost") != null && System.getProperty("http.proxyPort") != null) {
        client.getHostConfiguration().setProxy(System.getProperty("http.proxyHost"),
                Integer.parseInt(System.getProperty("http.proxyPort")));
    }
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    client.getParams().setBooleanParameter("http.protocol.single-cookie-header", true);
    return client;
}

From source file:jp.go.nict.langrid.management.logic.service.HttpClientUtil.java

/**
 * /* w w  w  .  j a v a  2 s  .com*/
 * 
 */
public static HttpClient createHttpClientWithHostConfig(URL url) {
    HttpClient client = new HttpClient();
    int port = url.getPort();
    if (port == -1) {
        port = url.getDefaultPort();
        if (port == -1) {
            port = 80;
        }
    }
    if ((url.getProtocol().equalsIgnoreCase("https")) && (sslSocketFactory != null)) {
        Protocol https = new Protocol("https",
                (ProtocolSocketFactory) new SSLSocketFactorySSLProtocolSocketFactory(sslSocketFactory), port);
        client.getHostConfiguration().setHost(url.getHost(), url.getPort(), https);
    } else {
        Protocol http = new Protocol("http", new SocketFactoryProtocolSocketFactory(SocketFactory.getDefault()),
                port);
        client.getHostConfiguration().setHost(url.getHost(), url.getPort(), http);
    }
    try {
        List<Proxy> proxies = ProxySelector.getDefault().select(url.toURI());
        for (Proxy p : proxies) {
            if (p.equals(Proxy.NO_PROXY))
                continue;
            if (!p.type().equals(Proxy.Type.HTTP))
                continue;
            InetSocketAddress addr = (InetSocketAddress) p.address();
            client.getHostConfiguration().setProxy(addr.getHostName(), addr.getPort());
            break;
        }
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return client;
}

From source file:jp.go.nict.langrid.servicesupervisor.invocationprocessor.executor.intragrid.HttpClientUtil.java

/**
 * //  w  w  w.  ja  v a2 s .co  m
 * 
 */
public static HttpClient createHttpClientWithHostConfig(URL url) {
    HttpClient client = new HttpClient();
    int port = url.getPort();
    if (port == -1) {
        port = url.getDefaultPort();
        if (port == -1) {
            port = 80;
        }
    }
    if ((url.getProtocol().equalsIgnoreCase("https")) && (sslSocketFactory != null)) {
        Protocol https = new Protocol("https",
                (ProtocolSocketFactory) new SSLSocketFactorySSLProtocolSocketFactory(sslSocketFactory), port);
        client.getHostConfiguration().setHost(url.getHost(), url.getPort(), https);
    } else {
        Protocol http = new Protocol("http", new SocketFactoryProtocolSocketFactory(SocketFactory.getDefault()),
                port);
        client.getHostConfiguration().setHost(url.getHost(), url.getPort(), http);
    }
    try {
        List<Proxy> proxies = ProxySelector.getDefault().select(url.toURI());
        for (Proxy p : proxies) {
            if (p.equals(Proxy.NO_PROXY))
                continue;
            if (!p.type().equals(Proxy.Type.HTTP))
                continue;
            InetSocketAddress addr = (InetSocketAddress) p.address();
            client.getHostConfiguration().setProxy(addr.getHostName(), addr.getPort());
            client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials("", ""));
            break;
        }
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return client;
}

From source file:com.feilong.tools.net.httpclient3.HttpClientUtil.java

/**
 *  proxy./*from  w w  w  . j  a  v a  2s . c  o m*/
 * 
 * @param httpClientConfig
 *            the http client config
 * @param httpClient
 *            the http client
 */
// TODO
private static void setProxy(HttpClientConfig httpClientConfig, HttpClient httpClient) {
    // ?
    String hostName = httpClientConfig.getProxyAddress();
    if (Validator.isNotNullOrEmpty(hostName)) {
        int port = httpClientConfig.getProxyPort();
        HostConfiguration hostConfiguration = httpClient.getHostConfiguration();
        hostConfiguration.setProxy(hostName, port);
    }
}