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

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

Introduction

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

Prototype

public void setProxyHost(ProxyHost paramProxyHost)

Source Link

Usage

From source file:de.mpg.imeji.presentation.util.ProxyHelper.java

/**
  * check if proxy has to get used for given url.
  * If yes, set ProxyHost in httpClient//from   w  w w  .j a  va  2 s.c om
  *
  * @param url url
  *
  * @throws Exception
  */
public static void setProxy(final HttpClient httpClient, final String url) {

    getProxyProperties();

    if (proxyHost != null) {

        org.apache.commons.httpclient.HostConfiguration hc = httpClient.getHostConfiguration();

        if (findUrlInNonProxyHosts(url)) {
            hc.setProxyHost(null);
        } else {
            hc.setProxy(proxyHost, Integer.valueOf(proxyPort));
        }
    }
}

From source file:de.mpg.escidoc.services.common.util.ProxyHelper.java

/**
  * check if proxy has to get used for given url.
  * If yes, set ProxyHost in httpClient//from w w w . java2s  .  co m
  *
  * @param url url
  *
  * @throws Exception
  */
public static void setProxy(final HttpClient httpClient, final String url) {

    getProxyProperties();

    if (proxyHost != null) {

        HostConfiguration hc = httpClient.getHostConfiguration();

        if (findUrlInNonProxyHosts(url)) {
            hc.setProxyHost(null);
        } else {
            hc.setProxy(proxyHost, Integer.valueOf(proxyPort));
        }
    }
}

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.
 *///w  w  w. ja v  a2  s.  c om
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.twinsoft.convertigo.engine.ProxyManager.java

public void disableProxy(HostConfiguration hostConfiguration) {
    hostConfiguration.setProxyHost(null);
}

From source file:com.orange.mmp.net.http.HttpConnectionManager.java

public Connection getConnection() throws MMPNetException {
    SimpleHttpConnectionManager shcm = new SimpleHttpConnectionManager();

    HttpClientParams defaultHttpParams = new HttpClientParams();
    defaultHttpParams.setParameter(HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    defaultHttpParams.setParameter(HttpConnectionParams.TCP_NODELAY, true);
    defaultHttpParams.setParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false);
    defaultHttpParams.setParameter(HttpConnectionParams.SO_LINGER, 0);
    defaultHttpParams.setParameter(HttpClientParams.MAX_REDIRECTS, 3);
    defaultHttpParams.setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, false);

    HttpClient httpClient2 = new HttpClient(defaultHttpParams, shcm);

    if (HttpConnectionManager.proxyHost != null) {
        defaultHttpParams.setParameter("http.route.default-proxy",
                new HttpHost(HttpConnectionManager.proxyHost, HttpConnectionManager.proxyPort)); // TODO Host configuration !
        if (HttpConnectionManager.proxyHost != null/* && this.useProxy*/) {
            HostConfiguration config = new HostConfiguration();
            config.setProxy(HttpConnectionManager.proxyHost, HttpConnectionManager.proxyPort);
            httpClient2.setHostConfiguration(config);
        } else {/*w ww.  j a v a  2 s. c o  m*/
            HostConfiguration config = new HostConfiguration();
            config.setProxyHost(null);
            httpClient2.setHostConfiguration(config);
        }
    }

    return new HttpConnection(httpClient2);
}

From source file:com.sun.jersey.client.apache.DefaultApacheHttpMethodExecutor.java

private HostConfiguration getHostConfiguration(HttpClient client, Map<String, Object> props) {
    Object proxy = props.get(ApacheHttpClientConfig.PROPERTY_PROXY_URI);
    if (proxy != null) {
        URI proxyUri = getProxyUri(proxy);

        String proxyHost = proxyUri.getHost();
        if (proxyHost == null) {
            proxyHost = "localhost";
        }/*  ww  w. j ava 2s .  co m*/

        int proxyPort = proxyUri.getPort();
        if (proxyPort == -1) {
            proxyPort = 8080;
        }

        HostConfiguration hostConfig = new HostConfiguration(client.getHostConfiguration());
        String setHost = hostConfig.getProxyHost();
        int setPort = hostConfig.getProxyPort();

        if ((setHost == null) || (!setHost.equals(proxyHost)) || (setPort == -1) || (setPort != proxyPort)) {
            hostConfig.setProxyHost(new ProxyHost(proxyHost, proxyPort));
        }
        return hostConfig;
    } else {
        return null;
    }
}

From source file:com.dragoniade.deviantart.favorites.FavoritesDownloader.java

public void setProxy(ProxyCfg prx) {
    HostConfiguration hostConfiguration = client.getHostConfiguration();
    if (prx != null) {
        ProxyHost proxyHost = new ProxyHost(prx.getHost(), prx.getPort());
        hostConfiguration.setProxyHost(proxyHost);
        if (prx.getUsername() != null) {
            UsernamePasswordCredentials upCred = new UsernamePasswordCredentials(prx.getUsername(),
                    prx.getPassword());/* www  .j av  a2s . c om*/
            client.getState().setProxyCredentials(AuthScope.ANY, upCred);
        } else {
            client.getState().clearProxyCredentials();
        }
    } else {
        hostConfiguration.setProxyHost(null);
        client.getState().clearProxyCredentials();
    }
}

From source file:com.dragoniade.deviantart.ui.PreferencesDialog.java

private void setProxy(ProxyCfg prx) {
    HostConfiguration hostConfiguration = client.getHostConfiguration();
    if (prx != null) {
        ProxyHost proxyHost = new ProxyHost(prx.getHost(), prx.getPort());
        hostConfiguration.setProxyHost(proxyHost);
        if (prx.getUsername() != null) {
            UsernamePasswordCredentials upCred = new UsernamePasswordCredentials(prx.getUsername(),
                    prx.getPassword());/*from w w w . ja v  a  2s  .co  m*/
            client.getState().setProxyCredentials(AuthScope.ANY, upCred);
        } else {
            client.getState().clearProxyCredentials();
        }
    } else {
        hostConfiguration.setProxyHost(null);
        client.getState().clearProxyCredentials();
    }
}

From source file:com.orange.mmp.net.http.HttpConnection.java

/**
 * Inner method used to execute request/*ww  w  .  j a v a2 s  .  c om*/
 * 
 * @param dataStream The data stream to send in request (null for GET only)
 * @throws MMPNetException 
 */
@SuppressWarnings("unchecked")
protected void doExecute(InputStream dataStream) throws MMPNetException {
    try {
        this.currentHttpClient = HttpConnectionManager.httpClientPool.take();
    } catch (InterruptedException ie) {
        throw new MMPNetException("Corrupted HTTP client pool", ie);
    }

    if (this.httpConnectionProperties.containsKey(HttpConnectionParameters.PARAM_IN_CREDENTIALS_USER)) {
        this.currentHttpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                (String) this.httpConnectionProperties.get(HttpConnectionParameters.PARAM_IN_CREDENTIALS_USER),
                (String) this.httpConnectionProperties
                        .get(HttpConnectionParameters.PARAM_IN_CREDENTIALS_PASSWORD)));
        this.currentHttpClient.getParams().setAuthenticationPreemptive(true);
    }

    // Config
    HostConfiguration config = new HostConfiguration();
    if (this.timeout > 0)
        this.currentHttpClient.getParams().setParameter(HttpConnectionParameters.PARAM_IN_HTTP_SOCKET_TIMEOUT,
                this.timeout);
    if (HttpConnectionManager.proxyHost != null
            && (this.httpConnectionProperties.get(HttpConnectionParameters.PARAM_IN_HTTP_USE_PROXY) != null
                    && this.httpConnectionProperties.get(HttpConnectionParameters.PARAM_IN_HTTP_USE_PROXY)
                            .toString().equals("true"))
            || (this.httpConnectionProperties.get(HttpConnectionParameters.PARAM_IN_HTTP_USE_PROXY) == null
                    && this.useProxy)) {
        config.setProxy(HttpConnectionManager.proxyHost, HttpConnectionManager.proxyPort);
    } else {
        config.setProxyHost(null);
    }
    this.currentHttpClient.setHostConfiguration(config);
    this.currentHttpClient.getHostConfiguration().setHost(new HttpHost(this.endPointUrl.getHost()));

    String methodStr = (String) this.httpConnectionProperties
            .get(HttpConnectionParameters.PARAM_IN_HTTP_METHOD);

    if (methodStr == null || methodStr.equals(HttpConnectionParameters.HTTP_METHOD_GET)) {
        this.method = new GetMethod(endPointUrl.toString().replace(" ", "+"));
    } else if (methodStr.equals(HttpConnectionParameters.HTTP_METHOD_POST)) {
        this.method = new PostMethod((this.endPointUrl.getQuery() == null) ? this.endPointUrl.getPath()
                : this.endPointUrl.getPath() + "?" + endPointUrl.getQuery());
        if (dataStream != null) {
            InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(dataStream);
            ((PostMethod) this.method).setRequestEntity(inputStreamRequestEntity);
        }
    } else if (methodStr.equals(HttpConnectionParameters.HTTP_METHOD_PUT)) {
        this.method = new PutMethod((this.endPointUrl.getQuery() == null) ? this.endPointUrl.getPath()
                : this.endPointUrl.getPath() + "?" + endPointUrl.getQuery());
        if (dataStream != null) {
            InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(dataStream);
            ((PutMethod) this.method).setRequestEntity(inputStreamRequestEntity);
        }
    } else if (methodStr.equals(HttpConnectionParameters.HTTP_METHOD_DEL)) {
        this.method = new DeleteMethod((this.endPointUrl.getQuery() == null) ? this.endPointUrl.getPath()
                : this.endPointUrl.getPath() + "?" + endPointUrl.getQuery());
    } else
        throw new MMPNetException("HTTP method not supported");

    //Add headers
    if (this.httpConnectionProperties != null) {
        for (Object headerName : this.httpConnectionProperties.keySet()) {
            if (!((String) headerName).startsWith("http.")) {
                this.method.addRequestHeader((String) headerName,
                        this.httpConnectionProperties.get(headerName).toString());
            }
        }
    }
    // Set Connection/Proxy-Connection close to avoid TIME_WAIT sockets
    this.method.addRequestHeader("Connection", "close");
    this.method.addRequestHeader("Proxy-Connection", "close");

    try {
        int httpCode = this.currentHttpClient.executeMethod(config, method);
        this.currentStatusCode = httpCode;

        for (org.apache.commons.httpclient.Header responseHeader : method.getResponseHeaders()) {
            this.httpConnectionProperties.put(responseHeader.getName(), responseHeader.getValue());
        }

        if (this.currentStatusCode >= 400) {
            throw new MMPNetException("HTTP " + this.currentStatusCode + " on '" + endPointUrl + "'");
        } else {
            this.inDataStream = this.method.getResponseBodyAsStream();
        }
    } catch (IOException ioe) {
        throw new MMPNetException("I/O error on " + this.endPointUrl + " : " + ioe.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.twinsoft.convertigo.engine.proxy.translated.HttpClient.java

private byte[] getData(HttpConnector connector, String resourceUrl, ParameterShuttle infoShuttle)
        throws IOException, EngineException {
    byte[] result = null;

    try {// ww  w.  ja  v  a  2 s  .  c  o  m
        Context context = infoShuttle.context;

        String proxyServer = Engine.theApp.proxyManager.getProxyServer();
        String proxyUser = Engine.theApp.proxyManager.getProxyUser();
        String proxyPassword = Engine.theApp.proxyManager.getProxyPassword();
        int proxyPort = Engine.theApp.proxyManager.getProxyPort();

        HostConfiguration hostConfiguration = connector.hostConfiguration;

        boolean trustAllServerCertificates = connector.isTrustAllServerCertificates();

        // Retrieving httpState
        getHttpState(connector, infoShuttle);

        Engine.logEngine.trace("(HttpClient) Retrieving data as a bytes array...");
        Engine.logEngine.debug("(HttpClient) Connecting to: " + resourceUrl);

        // Proxy configuration
        if (!proxyServer.equals("")) {
            hostConfiguration.setProxy(proxyServer, proxyPort);
            Engine.logEngine.debug("(HttpClient) Using proxy: " + proxyServer + ":" + proxyPort);
        } else {
            // Remove old proxy configuration
            hostConfiguration.setProxyHost(null);
        }

        Engine.logEngine.debug("(HttpClient) Https: " + connector.isHttps());
        CertificateManager certificateManager = connector.certificateManager;

        URL url = null;
        String host = "";
        int port = -1;
        if (resourceUrl.toLowerCase().startsWith("https:")) {
            Engine.logEngine.debug("(HttpClient) Setting up SSL properties");
            certificateManager.collectStoreInformation(context);

            url = new URL(resourceUrl);
            host = url.getHost();
            port = url.getPort();
            if (port == -1)
                port = 443;

            Engine.logEngine.debug("(HttpClient) Host: " + host + ":" + port);

            Engine.logEngine
                    .debug("(HttpClient) CertificateManager has changed: " + certificateManager.hasChanged);
            if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost()))
                    || (hostConfiguration.getPort() != port)) {
                Engine.logEngine.debug("(HttpClient) Using MySSLSocketFactory for creating the SSL socket");
                Protocol myhttps = new Protocol("https",
                        MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore,
                                certificateManager.keyStorePassword, certificateManager.trustStore,
                                certificateManager.trustStorePassword, trustAllServerCertificates),
                        port);

                hostConfiguration.setHost(host, port, myhttps);
            }

            resourceUrl = url.getFile();
            Engine.logEngine.debug("(HttpClient) Updated URL for SSL purposes: " + resourceUrl);
        } else {
            url = new URL(resourceUrl);
            host = url.getHost();
            port = url.getPort();

            Engine.logEngine.debug("(HttpClient) Host: " + host + ":" + port);
            hostConfiguration.setHost(host, port);
        }

        Engine.logEngine.debug("(HttpClient) Building method on: " + resourceUrl);
        Engine.logEngine.debug("(HttpClient) postFromUser=" + infoShuttle.postFromUser);
        Engine.logEngine.debug("(HttpClient) postToSite=" + infoShuttle.postToSite);
        if (infoShuttle.postFromUser && infoShuttle.postToSite) {
            method = new PostMethod(resourceUrl);
            ((PostMethod) method).setRequestEntity(
                    new StringRequestEntity(infoShuttle.userPostData, infoShuttle.userContentType,
                            infoShuttle.context.httpServletRequest.getCharacterEncoding()));
        } else {
            method = new GetMethod(resourceUrl);
        }

        HttpMethodParams httpMethodParams = method.getParams();

        // Cookie configuration
        if (handleCookie) {
            Engine.logEngine.debug("(HttpClient) Setting cookie policy.");
            httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        }

        String basicUser = connector.getAuthUser();
        String basicPassword = connector.getAuthPassword();
        String givenBasicUser = connector.getGivenAuthUser();
        String givenBasicPassword = connector.getGivenAuthPassword();

        // Basic authentication configuration
        String realm = null;
        if (!basicUser.equals("") || (basicUser.equals("") && (givenBasicUser != null))) {
            String userName = ((givenBasicUser == null) ? basicUser : givenBasicUser);
            String userPassword = ((givenBasicPassword == null) ? basicPassword : givenBasicPassword);
            httpState.setCredentials(new AuthScope(host, port, realm),
                    new UsernamePasswordCredentials(userName, userPassword));
            Engine.logEngine.debug("(HttpClient) Credentials: " + userName + ":******");
        }

        // Setting basic authentication for proxy
        if (!proxyServer.equals("") && !proxyUser.equals("")) {
            httpState.setProxyCredentials(new AuthScope(proxyServer, proxyPort),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
            Engine.logEngine.debug("(HttpClient) Proxy credentials: " + proxyUser + ":******");
        }

        // Setting HTTP headers
        Engine.logEngine.debug("(HttpClient) Incoming HTTP headers:");
        String headerName, headerValue;
        for (int k = 0, kSize = infoShuttle.userHeaderNames.size(); k < kSize; k++) {
            headerName = (String) infoShuttle.userHeaderNames.get(k);
            // Cookies are handled by HttpClient, so we do not have to proxy Cookie header
            // See #986 (Multiples cookies don't work with some proxies)
            if (headerName.toLowerCase().equals("cookie")) {
                Engine.logEngine.debug("Cookie header ignored");
            } else {
                headerValue = (String) infoShuttle.userHeaderValues.get(k);
                method.setRequestHeader(headerName, headerValue);
                Engine.logEngine.debug(headerName + "=" + headerValue);
            }
        }

        // Getting the result
        executeMethod(method, connector, resourceUrl, infoShuttle);
        result = method.getResponseBody();

    } finally {
        if (method != null)
            method.releaseConnection();
    }

    return result;
}