Example usage for org.apache.http.impl.conn ProxySelectorRoutePlanner ProxySelectorRoutePlanner

List of usage examples for org.apache.http.impl.conn ProxySelectorRoutePlanner ProxySelectorRoutePlanner

Introduction

In this page you can find the example usage for org.apache.http.impl.conn ProxySelectorRoutePlanner ProxySelectorRoutePlanner.

Prototype

public ProxySelectorRoutePlanner(final SchemeRegistry schreg, final ProxySelector prosel) 

Source Link

Document

Creates a new proxy selector route planner.

Usage

From source file:com.villemos.ispace.httpcrawler.HttpClientConfigurer.java

public static HttpClient setupClient(boolean ignoreAuthenticationFailure, String domain, Integer port,
        String proxyHost, Integer proxyPort, String authUser, String authPassword, CookieStore cookieStore)
        throws NoSuchAlgorithmException, KeyManagementException {

    DefaultHttpClient client = null;//from  w w  w.  java 2 s  . com

    /** Always ignore authentication protocol errors. */
    if (ignoreAuthenticationFailure) {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom());

        SchemeRegistry schemeRegistry = new SchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", sf, 443);
        schemeRegistry.register(httpsScheme);

        SocketFactory sfa = new PlainSocketFactory();
        Scheme httpScheme = new Scheme("http", sfa, 80);
        schemeRegistry.register(httpScheme);

        HttpParams params = new BasicHttpParams();
        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(cm, params);
    } else {
        client = new DefaultHttpClient();
    }

    if (proxyHost != null && proxyPort != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    /** The target location may demand authentication. We setup preemptive authentication. */
    if (authUser != null && authPassword != null) {
        client.getCredentialsProvider().setCredentials(new AuthScope(domain, port),
                new UsernamePasswordCredentials(authUser, authPassword));
    }

    /** Set default cookie policy and store. Can be overridden for a specific method using for example;
     *    method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); 
     */
    client.setCookieStore(cookieStore);
    // client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);      
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    return client;
}

From source file:com.geoxp.oss.client.OSSClient.java

/**
 * Get an HttpClient able to use a the Java configured proxyHost/Port if needed
 *
 * @returns HttpClient// w  w w. j  a  v  a 2  s.  com
 */
private static HttpClient newHttpClient() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpclient.setRoutePlanner(routePlanner);
    return httpclient;
}

From source file:org.hbird.business.celestrack.http.CelestrackReader.java

/**
 * Method to access the Celestrack website, download the TLE file ('elements'), extract the TLEs and
 * publish them to the system./*  www  .  j  av  a 2  s .c o  m*/
 * 
 * @return 0 (always)
 * @throws Exception
 */
@Handler
public int read() throws Exception {

    if (part.getProxyHost() != null) {
        HttpHost proxy = new HttpHost(part.getProxyHost(), part.getProxyPort());
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    long now = System.currentTimeMillis();

    for (String uri : part.getElements().split(":")) {
        HttpResponse response = client
                .execute(new HttpGet("http://www.celestrak.com/NORAD/elements/" + uri + ".txt"));

        if (response.getStatusLine().getStatusCode() == 200) {
            String text = readFully(response.getEntity().getContent());
            String elements[] = text.split("\n");

            for (int index = 0; index < elements.length; index += 3) {
                Satellite satellite = null;
                String name = elements[index].trim();
                Object object = catalogue.getSatelliteByName(name);
                if (object == null) {
                    /* Satellite unknown. Create placeholder object. */
                    // TODO - 18.05.2013, kimmell - create proper entity ID here
                    String entityID = name;
                    satellite = new Satellite(entityID, name);
                    publisher.publish(satellite);
                } else {
                    satellite = (Satellite) object;
                }

                TleOrbitalParameters parameters = new TleOrbitalParameters(satellite.getID() + "/TLE",
                        TleOrbitalParameters.class.getSimpleName());
                parameters.setSatelliteId(satellite.getID());
                parameters.setTleLine1(elements[index + 1].trim());
                parameters.setTleLine2(elements[index + 2].trim());
                publisher.publish(parameters);
            }
        }
    }

    return 0;
}

From source file:org.gradle.api.internal.artifacts.repositories.transport.http.HttpClientConfigurer.java

private void configureProxy(DefaultHttpClient httpClient, HttpProxySettings proxySettings) {
    // Use standard JVM proxy settings
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    HttpProxySettings.HttpProxy proxy = proxySettings.getProxy();
    if (proxy != null && proxy.credentials != null) {
        useCredentials(httpClient, proxy.credentials, proxy.host, proxy.port);
    }//w  w w  . j  a va2  s.com
}

From source file:org.apache.chemistry.opencmis.client.bindings.spi.http.ApacheClientHttpInvoker.java

@Override
protected DefaultHttpClient createHttpClient(UrlBuilder url, BindingSession session) {
    // set params
    HttpParams params = createDefaultHttpParams(session);
    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);

    // set up scheme registry and connection manager
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    registry.register(new Scheme("https", 443, getSSLSocketFactory(url, session)));

    // set up connection manager
    PoolingClientConnectionManager connManager = new PoolingClientConnectionManager(registry);

    // set max connection a
    String keepAliveStr = System.getProperty("http.keepAlive", "true");
    if ("true".equalsIgnoreCase(keepAliveStr)) {
        String maxConnStr = System.getProperty("http.maxConnections", "5");
        int maxConn = 5;
        try {// w w  w .  j  a  v a2 s . co  m
            maxConn = Integer.parseInt(maxConnStr);
        } catch (NumberFormatException nfe) {
            // ignore
        }
        connManager.setDefaultMaxPerRoute(maxConn);
        connManager.setMaxTotal(4 * maxConn);
    }

    // set up proxy
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(registry, null);

    // set up client
    DefaultHttpClient httpclient = new DefaultHttpClient(connManager, params);
    httpclient.setRoutePlanner(routePlanner);

    return httpclient;
}

From source file:org.openqa.selenium.remote.internal.HttpClientFactory.java

public HttpRoutePlanner getRoutePlanner(SchemeRegistry registry) {
    return new ProxySelectorRoutePlanner(registry, ProxySelector.getDefault());
}

From source file:com.gallery.GalleryRemote.GalleryComm.java

protected GalleryComm(Gallery g, StatusUpdate su) {
    if (g == null) {
        throw new IllegalArgumentException("Must supply a non-null gallery.");
    }/*from  w w  w .  j a v  a  2 s  .  co m*/

    this.g = g;
    this.su = su;

    SingleClientConnManager cm = null;

    // Set all-trusting SSL manager, if necessary
    if (g.getUrl().getProtocol().equals("https")) {
        try {
            SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"),
                    SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("https", sf, 443));
            cm = new SingleClientConnManager(schemeRegistry);
        } catch (NoSuchAlgorithmException e) {
            Log.logException(Log.LEVEL_CRITICAL, MODULE, e);
        }
    }

    httpclient = new DefaultHttpClient(cm);

    // Use default proxy (as defined by the JVM)
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpclient.setRoutePlanner(routePlanner);

    // use GR User-Agent
    httpclient.removeRequestInterceptorByClass(RequestUserAgent.class);
    final String ua = g.getUserAgent();
    httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            request.setHeader(HTTP.USER_AGENT, ua);
        }
    });
}

From source file:com.android.sdklib.internal.repository.UrlOpener.java

private static InputStream openWithHttpClient(String url, ITaskMonitor monitor)
        throws IOException, ClientProtocolException, CanceledByUserException {
    UserCredentials result = null;//  w  w w. ja va 2 s.  c om
    String realm = null;

    // use the simple one
    final DefaultHttpClient httpClient = new DefaultHttpClient();

    // create local execution context
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpget = new HttpGet(url);

    // retrieve local java configured network in case there is the need to
    // authenticate a proxy
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    // Set preference order for authentication options.
    // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in
    // servers that support both, as it is more secure. However, we don't seem to handle it
    // very well, so we leave it off the list.
    // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for
    // more info.
    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);
    authpref.add(AuthPolicy.DIGEST);
    authpref.add(AuthPolicy.NTLM);
    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);

    boolean trying = true;
    // loop while the response is being fetched
    while (trying) {
        // connect and get status code
        HttpResponse response = httpClient.execute(httpget, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        // check whether any authentication is required
        AuthState authenticationState = null;
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            // Target host authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            // Proxy authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_OK) {
            // in case the status is OK and there is a realm and result,
            // cache it
            if (realm != null && result != null) {
                sRealmCache.put(realm, result);
            }
        }

        // there is the need for authentication
        if (authenticationState != null) {

            // get scope and realm
            AuthScope authScope = authenticationState.getAuthScope();

            // If the current realm is different from the last one it means
            // a pass was performed successfully to the last URL, therefore
            // cache the last realm
            if (realm != null && !realm.equals(authScope.getRealm())) {
                sRealmCache.put(realm, result);
            }

            realm = authScope.getRealm();

            // in case there is cache for this Realm, use it to authenticate
            if (sRealmCache.containsKey(realm)) {
                result = sRealmCache.get(realm);
            } else {
                // since there is no cache, request for login and password
                result = monitor.displayLoginCredentialsPrompt("Site Authentication",
                        "Please login to the following domain: " + realm
                                + "\n\nServer requiring authentication:\n" + authScope.getHost());
                if (result == null) {
                    throw new CanceledByUserException("User canceled login dialog.");
                }
            }

            // retrieve authentication data
            String user = result.getUserName();
            String password = result.getPassword();
            String workstation = result.getWorkstation();
            String domain = result.getDomain();

            // proceed in case there is indeed a user
            if (user != null && user.length() > 0) {
                Credentials credentials = new NTCredentials(user, password, workstation, domain);
                httpClient.getCredentialsProvider().setCredentials(authScope, credentials);
                trying = true;
            } else {
                trying = false;
            }
        } else {
            trying = false;
        }

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (trying) {
                // in case another pass to the Http Client will be performed, close the entity.
                entity.getContent().close();
            } else {
                // since no pass to the Http Client is needed, retrieve the
                // entity's content.

                // Note: don't use something like a BufferedHttpEntity since it would consume
                // all content and store it in memory, resulting in an OutOfMemory exception
                // on a large download.

                return new FilterInputStream(entity.getContent()) {
                    @Override
                    public void close() throws IOException {
                        super.close();

                        // since Http Client is no longer needed, close it
                        httpClient.getConnectionManager().shutdown();
                    }
                };
            }
        }
    }

    // We get here if we did not succeed. Callers do not expect a null result.
    httpClient.getConnectionManager().shutdown();
    throw new FileNotFoundException(url);
}

From source file:jetbrains.teamcilty.github.api.impl.HttpClientWrapperImpl.java

public HttpClientWrapperImpl()
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    final String serverVersion = ServerVersionHolder.getVersion().getDisplayVersion();

    final HttpParams ps = new BasicHttpParams();

    DefaultHttpClient.setDefaultHttpParams(ps);
    final int timeout = TeamCityProperties.getInteger("teamcity.github.http.timeout", 300 * 1000);
    HttpConnectionParams.setConnectionTimeout(ps, timeout);
    HttpConnectionParams.setSoTimeout(ps, timeout);
    HttpProtocolParams.setUserAgent(ps, "JetBrains TeamCity " + serverVersion);

    final SchemeRegistry schemaRegistry = SchemeRegistryFactory.createDefault();
    final SSLSocketFactory sslSocketFactory = new SSLSocketFactory(new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return !TeamCityProperties.getBoolean("teamcity.github.verify.ssl.certificate");
        }//from ww w  . j  av  a 2 s  .c o m
    });
    schemaRegistry.register(new Scheme("https", 443, sslSocketFactory));

    final DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(schemaRegistry),
            ps);

    setupProxy(httpclient);

    httpclient.setRoutePlanner(new ProxySelectorRoutePlanner(
            httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()));
    httpclient.addRequestInterceptor(new RequestAcceptEncoding());
    httpclient.addResponseInterceptor(new ResponseContentEncoding());
    httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

    myClient = httpclient;
}