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

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

Introduction

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

Prototype

public HostConfiguration() 

Source Link

Usage

From source file:com.eviware.soapui.impl.wsdl.panels.teststeps.amf.SoapUIAMFConnection.java

/**
 * Writes the output buffer and processes the HTTP response.
 *///w w  w  . j  av  a 2 s  .  c  o m
protected Object send(ByteArrayOutputStream outBuffer)
        throws ClassNotFoundException, IOException, ClientStatusException, ServerStatusException {
    // internalConnect.
    internalConnect();

    postMethod.setRequestEntity(new ByteArrayRequestEntity(outBuffer.toByteArray()));
    HostConfiguration hostConfiguration = new HostConfiguration();

    ProxyUtils.initProxySettings(
            context.getModelItem() == null ? SoapUI.getSettings() : context.getModelItem().getSettings(),
            httpState, hostConfiguration, url, context);

    HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, postMethod, httpState);

    context.setProperty(AMFResponse.AMF_POST_METHOD, postMethod);

    return processHttpResponse(responseBodyInputStream());
}

From source file:com.taobao.diamond.client.impl.DefaultDiamondPublisher.java

private void initHttpClient() {
    if (MockServer.isTestMode()) {
        return;//from   w w w  .  j  a  va  2s .  co m
    }
    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost(diamondConfigure.getDomainNameList().get(domainNamePos.get()),
            diamondConfigure.getPort());
    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.closeIdleConnections(60 * 1000);

    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setStaleCheckingEnabled(diamondConfigure.isConnectionStaleCheckingEnabled());
    params.setMaxConnectionsPerHost(hostConfiguration, diamondConfigure.getMaxHostConnections());
    params.setMaxTotalConnections(diamondConfigure.getMaxTotalConnections());
    params.setConnectionTimeout(diamondConfigure.getConnectionTimeout());
    params.setSoTimeout(requestTimeout);

    connectionManager.setParams(params);

    httpClient = new HttpClient(connectionManager);
    httpClient.setHostConfiguration(hostConfiguration);
}

From source file:com.polarion.alm.ws.client.internal.connection.CommonsHTTPSender.java

protected HostConfiguration getHostConfiguration(HttpClient client, MessageContext context, URL targetURL) {
    TransportClientProperties tcp = TransportClientPropertiesFactory.create(targetURL.getProtocol()); // http or https
    int port = targetURL.getPort();
    boolean hostInNonProxyList = isHostInNonProxyList(targetURL.getHost(), tcp.getNonProxyHosts());

    HostConfiguration config = new HostConfiguration();

    if (port == -1) {
        if (targetURL.getProtocol().equalsIgnoreCase("https")) {
            port = 443; // default port for https being 443
        } else { // it must be http
            port = 80; // default port for http being 80
        }//from   w ww  . j a  v a  2 s  . co m
    }

    if (hostInNonProxyList) {
        config.setHost(targetURL.getHost(), port, targetURL.getProtocol());
    } else {
        if (tcp.getProxyHost().length() == 0 || tcp.getProxyPort().length() == 0) {
            config.setHost(targetURL.getHost(), port, targetURL.getProtocol());
        } else {
            if (tcp.getProxyUser().length() != 0) {
                Credentials proxyCred = new UsernamePasswordCredentials(tcp.getProxyUser(),
                        tcp.getProxyPassword());
                // if the username is in the form "user\domain"
                // then use NTCredentials instead.
                int domainIndex = tcp.getProxyUser().indexOf("\\");
                if (domainIndex > 0) {
                    String domain = tcp.getProxyUser().substring(0, domainIndex);
                    if (tcp.getProxyUser().length() > domainIndex + 1) {
                        String user = tcp.getProxyUser().substring(domainIndex + 1);
                        proxyCred = new NTCredentials(user, tcp.getProxyPassword(), tcp.getProxyHost(), domain);
                    }
                }
                client.getState().setProxyCredentials(AuthScope.ANY, proxyCred);
            }
            int proxyPort = new Integer(tcp.getProxyPort()).intValue();
            config.setProxy(tcp.getProxyHost(), proxyPort);
        }
    }
    return config;
}

From source file:com.day.cq.wcm.foundation.impl.Rewriter.java

/**
 * Process a page.//from   w w  w .  j av a  2 s.  co  m
 */
public void rewrite(HttpServletRequest request, HttpServletResponse response) throws IOException {

    try {
        targetURL = new URI(target);
    } catch (URISyntaxException e) {
        IOException ioe = new IOException("Bad URI syntax: " + target);
        ioe.initCause(e);
        throw ioe;
    }
    setHostPrefix(targetURL);

    HttpClient httpClient = new HttpClient();
    HttpState httpState = new HttpState();
    HostConfiguration hostConfig = new HostConfiguration();
    HttpMethodBase httpMethod;

    // define host
    hostConfig.setHost(targetURL.getHost(), targetURL.getPort());

    // create http method
    String method = (String) request.getAttribute("cq.ext.app.method");
    if (method == null) {
        method = request.getMethod();
    }
    method = method.toUpperCase();
    boolean isPost = "POST".equals(method);
    String urlString = targetURL.getPath();
    StringBuffer query = new StringBuffer();
    if (targetURL.getQuery() != null) {
        query.append("?");
        query.append(targetURL.getQuery());
    }
    //------------ GET ---------------
    if ("GET".equals(method)) {
        // add internal props
        Iterator<String> iter = extraParams.keySet().iterator();
        while (iter.hasNext()) {
            String name = iter.next();
            String value = extraParams.get(name);
            if (query.length() == 0) {
                query.append("?");
            } else {
                query.append("&");
            }
            query.append(Text.escape(name));
            query.append("=");
            query.append(Text.escape(value));
        }
        if (passInput) {
            // add request params
            @SuppressWarnings("unchecked")
            Enumeration<String> e = request.getParameterNames();
            while (e.hasMoreElements()) {
                String name = e.nextElement();
                if (targetParamName.equals(name)) {
                    continue;
                }
                String[] values = request.getParameterValues(name);
                for (int i = 0; i < values.length; i++) {
                    if (query.length() == 0) {
                        query.append("?");
                    } else {
                        query.append("&");
                    }
                    query.append(Text.escape(name));
                    query.append("=");
                    query.append(Text.escape(values[i]));
                }
            }

        }
        httpMethod = new GetMethod(urlString + query);
        //------------ POST ---------------
    } else if ("POST".equals(method)) {
        PostMethod m = new PostMethod(urlString + query);
        httpMethod = m;
        String contentType = request.getContentType();
        boolean mp = contentType != null && contentType.toLowerCase().startsWith("multipart/");
        if (mp) {
            //------------ MULTPART POST ---------------
            List<Part> parts = new LinkedList<Part>();
            Iterator<String> iter = extraParams.keySet().iterator();
            while (iter.hasNext()) {
                String name = iter.next();
                String value = extraParams.get(name);
                parts.add(new StringPart(name, value));
            }
            if (passInput) {
                // add request params
                @SuppressWarnings("unchecked")
                Enumeration<String> e = request.getParameterNames();
                while (e.hasMoreElements()) {
                    String name = e.nextElement();
                    if (targetParamName.equals(name)) {
                        continue;
                    }
                    String[] values = request.getParameterValues(name);
                    for (int i = 0; i < values.length; i++) {
                        parts.add(new StringPart(name, values[i]));
                    }
                }
            }
            m.setRequestEntity(
                    new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), m.getParams()));
        } else {
            //------------ NORMAL POST ---------------
            // add internal props
            Iterator<String> iter = extraParams.keySet().iterator();
            while (iter.hasNext()) {
                String name = iter.next();
                String value = extraParams.get(name);
                m.addParameter(name, value);
            }
            if (passInput) {
                // add request params
                @SuppressWarnings("unchecked")
                Enumeration e = request.getParameterNames();
                while (e.hasMoreElements()) {
                    String name = (String) e.nextElement();
                    if (targetParamName.equals(name)) {
                        continue;
                    }
                    String[] values = request.getParameterValues(name);
                    for (int i = 0; i < values.length; i++) {
                        m.addParameter(name, values[i]);
                    }
                }
            }
        }
    } else {
        log.error("Unsupported method ''{0}''", method);
        throw new IOException("Unsupported http method " + method);
    }
    log.debug("created http connection for method {0} to {1}", method, urlString + query);

    // add some request headers
    httpMethod.addRequestHeader("User-Agent", request.getHeader("User-Agent"));
    httpMethod.setFollowRedirects(!isPost);
    httpMethod.getParams().setSoTimeout(soTimeout);
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);

    // send request
    httpClient.executeMethod(hostConfig, httpMethod, httpState);
    String contentType = httpMethod.getResponseHeader("Content-Type").getValue();

    log.debug("External app responded: {0}", httpMethod.getStatusLine());
    log.debug("External app contenttype: {0}", contentType);

    // check response code
    int statusCode = httpMethod.getStatusCode();
    if (statusCode >= HttpURLConnection.HTTP_BAD_REQUEST) {
        PrintWriter writer = response.getWriter();
        writer.println("External application returned status code: " + statusCode);
        return;
    } else if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP
            || statusCode == HttpURLConnection.HTTP_MOVED_PERM) {
        String location = httpMethod.getResponseHeader("Location").getValue();
        if (location == null) {
            response.sendError(HttpURLConnection.HTTP_NOT_FOUND);
            return;
        }
        response.sendRedirect(rewriteURL(location, false));
        return;
    }

    // open input stream
    InputStream in = httpMethod.getResponseBodyAsStream();

    // check content type
    if (contentType != null && contentType.startsWith("text/html")) {
        rewriteHtml(in, contentType, response);
    } else {
        // binary mode
        if (contentType != null) {
            response.setContentType(contentType);
        }
        OutputStream outs = response.getOutputStream();

        try {
            byte buf[] = new byte[8192];
            int len;

            while ((len = in.read(buf)) != -1) {
                outs.write(buf, 0, len);
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
}

From source file:gov.va.med.imaging.proxy.ImageXChangeHttpCommonsSender.java

protected HostConfiguration getHostConfiguration(HttpClient client, MessageContext context, URL targetURL) {
    TransportClientProperties tcp = TransportClientPropertiesFactory.create(targetURL.getProtocol()); // http
    // or//from w  w w .j a  va2  s  .co  m
    // https
    int port = targetURL.getPort();
    boolean hostInNonProxyList = isHostInNonProxyList(targetURL.getHost(), tcp.getNonProxyHosts());

    HostConfiguration config = new HostConfiguration();

    if (port == -1) {
        if (targetURL.getProtocol().equalsIgnoreCase("https")) {
            port = 443; // default port for https being 443
        } else { // it must be http
            port = 80; // default port for http being 80
        }
    }

    if (hostInNonProxyList) {
        config.setHost(targetURL.getHost(), port, targetURL.getProtocol());
    } else {
        if (tcp.getProxyHost().length() == 0 || tcp.getProxyPort().length() == 0) {
            config.setHost(targetURL.getHost(), port, targetURL.getProtocol());
        } else {
            if (tcp.getProxyUser().length() != 0) {
                Credentials proxyCred = new UsernamePasswordCredentials(tcp.getProxyUser(),
                        tcp.getProxyPassword());
                // if the username is in the form "user\domain"
                // then use NTCredentials instead.
                int domainIndex = tcp.getProxyUser().indexOf("\\");
                if (domainIndex > 0) {
                    String domain = tcp.getProxyUser().substring(0, domainIndex);
                    if (tcp.getProxyUser().length() > domainIndex + 1) {
                        String user = tcp.getProxyUser().substring(domainIndex + 1);
                        proxyCred = new NTCredentials(user, tcp.getProxyPassword(), tcp.getProxyHost(), domain);
                    }
                }
                client.getState().setProxyCredentials(AuthScope.ANY, proxyCred);
            }
            int proxyPort = new Integer(tcp.getProxyPort()).intValue();
            config.setProxy(tcp.getProxyHost(), proxyPort);
        }
    }
    return config;
}

From source file:flex.messaging.services.http.HTTPProxyAdapter.java

private void initHttpConnectionManagerParams(HTTPConnectionManagerSettings settings) {
    connectionParams = new HttpConnectionManagerParams();
    connectionParams.setMaxTotalConnections(settings.getMaxTotalConnections());
    connectionParams.setDefaultMaxConnectionsPerHost(settings.getDefaultMaxConnectionsPerHost());

    if (!settings.getCookiePolicy().equals(CookiePolicy.DEFAULT)) {
        HttpClientParams httpClientParams = (HttpClientParams) connectionParams.getDefaults();
        httpClientParams.setCookiePolicy(settings.getCookiePolicy());
    }/*from  w w w .  j  a va 2  s .c  o m*/

    if (settings.getConnectionTimeout() >= 0)
        connectionParams.setConnectionTimeout(settings.getConnectionTimeout());

    if (settings.getSocketTimeout() >= 0)
        connectionParams.setSoTimeout(settings.getSocketTimeout());

    connectionParams.setStaleCheckingEnabled(settings.isStaleCheckingEnabled());

    if (settings.getSendBufferSize() > 0)
        connectionParams.setSendBufferSize(settings.getSendBufferSize());

    if (settings.getReceiveBufferSize() > 0)
        connectionParams.setReceiveBufferSize(settings.getReceiveBufferSize());

    connectionParams.setTcpNoDelay(settings.isTcpNoDelay());
    connectionParams.setLinger(settings.getLinger());

    if (settings.getMaxConnectionsPerHost() != null) {
        Iterator it = settings.getMaxConnectionsPerHost().iterator();
        while (it.hasNext()) {
            HostConfigurationSettings hcs = (HostConfigurationSettings) it.next();
            HostConfiguration hostConfig = new HostConfiguration();

            if (hcs.getProtocol() != null) {
                Protocol protocol = Protocol.getProtocol(hcs.getProtocol());
                hostConfig.setHost(hcs.getHost(), hcs.getPort(), protocol);
            } else if (hcs.getProtocolFactory() != null) {
                Protocol protocol = hcs.getProtocolFactory().getProtocol();
                if (hcs.getPort() > 0)
                    hostConfig.setHost(hcs.getHost(), hcs.getPort(), protocol);
                else
                    hostConfig.setHost(hcs.getHost(), protocol.getDefaultPort(), protocol);
            } else {
                if (hcs.getPort() > 0)
                    hostConfig.setHost(hcs.getHost(), hcs.getPort());
                else
                    hostConfig.setHost(hcs.getHost());
            }

            if (hcs.getVirtualHost() != null) {
                HostParams params = hostConfig.getParams();
                if (params != null)
                    params.setVirtualHost(hcs.getVirtualHost());
            }

            if (hcs.getProxyHost() != null) {
                hostConfig.setProxy(hcs.getProxyHost(), hcs.getProxyPort());
            }

            try {
                InetAddress addr = InetAddress.getByName(hcs.getLocalAddress());
                hostConfig.setLocalAddress(addr);
            } catch (UnknownHostException ex) {
            }
            connectionParams.setMaxConnectionsPerHost(hostConfig, hcs.getMaximumConnections());
        }
    }
}

From source file:edu.internet2.middleware.shibboleth.idp.profile.saml2.SLOProfileHandler.java

/**
 * Creates Http connection.// w  ww . j av a 2  s.  c o  m
 *
 * @param serviceLogoutInfo
 * @param endpoint
 * @return
 * @throws URIException
 * @throws GeneralSecurityException
 * @throws IOException
 */
private HttpConnection createHttpConnection(LogoutInformation serviceLogoutInfo, Endpoint endpoint)
        throws URIException, GeneralSecurityException, IOException {

    HttpClientBuilder httpClientBuilder = new HttpClientBuilder();
    httpClientBuilder.setContentCharSet("UTF-8");
    SecureProtocolSocketFactory sf = new EasySSLProtocolSocketFactory();
    httpClientBuilder.setHttpsProtocolSocketFactory(sf);

    //build http connection
    HttpClient httpClient = httpClientBuilder.buildClient();

    HostConfiguration hostConfig = new HostConfiguration();
    URI location = new URI(endpoint.getLocation());
    hostConfig.setHost(location);

    LogoutRequestConfiguration config = (LogoutRequestConfiguration) getProfileConfiguration(
            serviceLogoutInfo.getEntityID(), getProfileId());
    if (log.isDebugEnabled()) {
        log.debug("Creating new HTTP connection with the following timeouts:");
        log.debug("Maximum waiting time for the connection pool is {}",
                config.getBackChannelConnectionPoolTimeout());
        log.debug("Timeout for connection establishment is {}", config.getBackChannelConnectionTimeout());
        log.debug("Timeout for soap response is {}", config.getBackChannelResponseTimeout());
    }
    HttpConnection httpConn = null;
    try {
        httpConn = httpClient.getHttpConnectionManager().getConnectionWithTimeout(hostConfig,
                config.getBackChannelConnectionPoolTimeout());
    } catch (ConnectionPoolTimeoutException e) {
        return null;
    }

    HttpConnectionParams params = new HttpConnectionParams();
    params.setConnectionTimeout(config.getBackChannelConnectionTimeout());
    params.setSoTimeout(config.getBackChannelResponseTimeout());
    httpConn.setParams(params);

    return httpConn;
}

From source file:com.amazonaws.a2s.AmazonA2SClient.java

/**
 * Configure HttpClient with set of defaults as well as configuration
 * from AmazonA2SConfig instance/*from w ww. ja  v a 2 s .c o  m*/
 *
 */
private HttpClient configureHttpClient() {

    /* Set http client parameters */
    HttpClientParams httpClientParams = new HttpClientParams();
    httpClientParams.setParameter(HttpMethodParams.USER_AGENT, config.getUserAgent());
    httpClientParams.setParameter(HttpClientParams.RETRY_HANDLER, new HttpMethodRetryHandler() {
        public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) {
            if (executionCount > 3) {
                log.debug("Maximum Number of Retry attempts reached, will not retry");
                return false;
            }
            log.debug("Retrying request. Attempt " + executionCount);
            if (exception instanceof NoHttpResponseException) {
                log.debug("Retrying on NoHttpResponseException");
                return true;
            }
            if (!method.isRequestSent()) {
                log.debug("Retrying on failed sent request");
                return true;
            }
            return false;
        }
    });

    /* Set host configuration */
    HostConfiguration hostConfiguration = new HostConfiguration();

    /* Set connection manager parameters */
    HttpConnectionManagerParams connectionManagerParams = new HttpConnectionManagerParams();
    connectionManagerParams.setConnectionTimeout(50000);
    connectionManagerParams.setSoTimeout(50000);
    connectionManagerParams.setStaleCheckingEnabled(true);
    connectionManagerParams.setTcpNoDelay(true);
    connectionManagerParams.setMaxTotalConnections(3);
    connectionManagerParams.setMaxConnectionsPerHost(hostConfiguration, 3);

    /* Set connection manager */
    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.setParams(connectionManagerParams);

    /* Set http client */
    httpClient = new HttpClient(httpClientParams, connectionManager);

    /* Set proxy if configured */
    if (config.isSetProxyHost() && config.isSetProxyPort()) {
        log.info("Configuring Proxy. Proxy Host: " + config.getProxyHost() + "Proxy Port: "
                + config.getProxyPort());
        hostConfiguration.setProxy(config.getProxyHost(), config.getProxyPort());

    }

    httpClient.setHostConfiguration(hostConfiguration);
    return httpClient;
}

From source file:com.twinsoft.convertigo.beans.connectors.SiteClipperConnector.java

private synchronized HostConfiguration getHostConfiguration(Shuttle shuttle)
        throws EngineException, MalformedURLException {
    if (hostConfiguration != null) {
        String host = hostConfiguration.getHost();
        if (isCompatibleConfiguration(host != null && host.equals(shuttle.getRequest(QueryPart.host)))) {
            if (isCompatibleConfiguration(hostConfiguration.getPort() == shuttle.getRequestPort())) {
                Protocol protocol = hostConfiguration.getProtocol();
                String scheme = (protocol == null) ? "" : protocol.getScheme();
                if (isCompatibleConfiguration(
                        scheme != null && scheme.equals(shuttle.getRequest(QueryPart.scheme)))) {
                    if (Engine.theApp.proxyManager.isEnabled()) {
                        String proxyHost = hostConfiguration.getProxyHost();
                        if (proxyHost == null) {
                            proxyHost = "";
                        }//  www  . jav  a2 s.  c  o  m
                        if (isCompatibleConfiguration(
                                proxyHost.equals(Engine.theApp.proxyManager.getProxyServer()))) {
                            //don't test the proxy port if the proxy host is null
                            if (isCompatibleConfiguration(hostConfiguration
                                    .getProxyPort() == Engine.theApp.proxyManager.getProxyPort())) {
                                isCompatibleConfiguration(
                                        hostConfiguration.getParams().getParameter("hostConfId")
                                                .equals(Engine.theApp.proxyManager.getHostConfId()));
                            }
                        }
                    }
                }
            }
        }
    }

    if (hostConfiguration == null) {
        Engine.logSiteClipper.debug("(SiteClipperConnector) create a new HostConfiguration");
        hostConfiguration = new HostConfiguration();
        String host = shuttle.getRequest(QueryPart.host);
        if (shuttle.getRequestScheme() == Scheme.https) {
            Engine.logSiteClipper.debug("(SiteClipperConnector) Setting up SSL properties");

            certificateManager.collectStoreInformation(context);

            Engine.logSiteClipper.debug(
                    "(SiteClipperConnector) CertificateManager has changed: " + certificateManager.hasChanged);
            Engine.logSiteClipper
                    .debug("(SiteClipperConnector) Using MySSLSocketFactory for creating the SSL socket");
            Protocol myhttps = new Protocol("https",
                    MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore,
                            certificateManager.keyStorePassword, certificateManager.trustStore,
                            certificateManager.trustStorePassword, trustAllServerCertificates),
                    shuttle.getRequestPort());

            hostConfiguration.setHost(host, shuttle.getRequestPort(), myhttps);
        } else {
            hostConfiguration.setHost(host, shuttle.getRequestPort());
        }

        URL requestUrl = new URL(shuttle.getRequestUrl());

        Engine.theApp.proxyManager.setProxy(hostConfiguration, context.httpState, requestUrl);
    }
    return hostConfiguration;
}

From source file:nz.net.kallisti.emusicj.network.http.proxy.HttpClientProvider.java

public HttpClient getHttpClient() {
    HttpState state = getState();//w  w  w.  j a  v  a2 s  .co  m
    HttpClient client = new HttpClient();
    client.setState(state);
    if (!prefs.getProxyHost().equals("") && prefs.usingProxy()) {
        HostConfiguration hostConf = new HostConfiguration();
        hostConf.setProxy(prefs.getProxyHost(), prefs.getProxyPort());
        client.setHostConfiguration(hostConf);
        client.getParams().setParameter(CredentialsProvider.PROVIDER, proxyCredsProvider);
    }
    return client;
}