Example usage for org.apache.http.impl.client DefaultHttpClient setRoutePlanner

List of usage examples for org.apache.http.impl.client DefaultHttpClient setRoutePlanner

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient setRoutePlanner.

Prototype

public synchronized void setRoutePlanner(final HttpRoutePlanner routePlanner) 

Source Link

Usage

From source file:org.jboss.tools.aerogear.hybrid.core.internal.util.HttpUtil.java

/**
 * Set the proxy settings from ProxyService.
 * This method sets a {@link HttpRoutePlanner} to the client
 * /*ww  w .  j a v a2  s  .c  o m*/
 * @param client
 */
public static void setupProxy(DefaultHttpClient client) {
    client.setRoutePlanner(new HttpRoutePlanner() {

        @Override
        public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context)
                throws HttpException {
            IProxyService proxy = HybridCore.getDefault().getProxyService();
            HttpHost host = null;
            try {
                IProxyData[] proxyDatas = proxy.select(new URI(target.toURI()));
                for (IProxyData data : proxyDatas) {
                    if (data.getType().equals(IProxyData.HTTP_PROXY_TYPE)) {
                        host = new HttpHost(data.getHost(), data.getPort());
                        break;
                    }
                }
            } catch (URISyntaxException e) {
                HybridCore.log(IStatus.ERROR, "Incorrect URI", e);
            }
            if (host == null) {
                return new HttpRoute(target);
            }
            return new HttpRoute(target, null, host, false);
        }
    });

}

From source file:org.eclipse.thym.core.internal.util.HttpUtil.java

/**
 * Set the proxy settings from ProxyService.
 * This method sets a {@link HttpRoutePlanner} to the client
 * //from   w  ww . ja  va 2s  .co  m
 * @param client
 */
public static void setupProxy(final DefaultHttpClient client) {
    client.setRoutePlanner(new HttpRoutePlanner() {

        @Override
        public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context)
                throws HttpException {

            //use forced route if one exists
            HttpRoute route = ConnRouteParams.getForcedRoute(request.getParams());
            if (route != null)
                return route;

            // if layered, is it secure?
            final Scheme scheme = client.getConnectionManager().getSchemeRegistry().getScheme(target);
            final boolean secure = scheme.isLayered();

            HttpHost host = null;
            try {
                IProxyData[] proxyDatas = getEclipseProxyData(new URI(target.toURI()));
                for (IProxyData data : proxyDatas) {
                    if (data.getType().equals(IProxyData.HTTP_PROXY_TYPE)) {
                        host = new HttpHost(data.getHost(), data.getPort());
                        break;
                    }
                }
            } catch (URISyntaxException e) {
                HybridCore.log(IStatus.ERROR, "Incorrect URI", e);
            }
            if (host == null) {
                return new HttpRoute(target, null, secure);
            }
            return new HttpRoute(target, null, host, secure);
        }
    });

}

From source file:org.jboss.tools.feedhenry.ui.model.HttpUtil.java

/**
 * Set the proxy settings from ProxyService.
 * This method sets a {@link HttpRoutePlanner} to the client
 * /*www. jav a  2  s . co m*/
 * @param client
 */
static void setupProxy(final DefaultHttpClient client) {
    client.setRoutePlanner(new HttpRoutePlanner() {

        /* (non-Javadoc)
         * @see org.apache.http.conn.routing.HttpRoutePlanner#determineRoute(org.apache.http.HttpHost, org.apache.http.HttpRequest, org.apache.http.protocol.HttpContext)
         */
        @Override
        public HttpRoute determineRoute(HttpHost target, HttpRequest request, HttpContext context)
                throws HttpException {

            //use forced route if one exists
            HttpRoute route = ConnRouteParams.getForcedRoute(request.getParams());
            if (route != null)
                return route;

            // if layered, is it secure?
            final Scheme scheme = client.getConnectionManager().getSchemeRegistry().getScheme(target);
            final boolean secure = scheme.isLayered();

            final IProxyService proxy = FHPlugin.getDefault().getProxyService();
            HttpHost host = null;
            if (proxy != null) {
                try {
                    IProxyData[] proxyDatas = proxy.select(new URI(target.toURI()));
                    for (IProxyData data : proxyDatas) {
                        if (data.getType().equals(IProxyData.HTTP_PROXY_TYPE)) {
                            host = new HttpHost(data.getHost(), data.getPort());
                            break;
                        }
                    }
                } catch (URISyntaxException e) {
                    FHPlugin.log(IStatus.ERROR, "Incorrect URI", e);
                }
            }
            if (host == null) {
                return new HttpRoute(target, null, secure);
            }
            return new HttpRoute(target, null, host, secure);
        }
    });

}

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;/*from   w  ww .  j  a v  a  2s.c o  m*/
    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:org.n52.oxf.util.web.ProxyAwareHttpClient.java

private void decorateProxyAwareness() {
    DefaultHttpClient clientToDecorate = getHttpClientToDecorate();
    clientToDecorate.setRoutePlanner(createProxyPlanner());
}

From source file:org.github.oauth2.AccessTokenClient.java

/**
 * Execute request and return response/*  w  w w.ja  v  a2  s  .  co  m*/
 * 
 * @param target
 * @param request
 * @return response
 * @throws IOException
 */
protected HttpResponse execute(HttpHost target, HttpRequest request) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRoutePlanner(new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(),
            ProxySelector.getDefault()));
    return client.execute(target, request);
}

From source file:org.sonatype.nexus.error.reporting.NexusPRConnector.java

private static void configureProxy(final DefaultHttpClient httpClient, final RemoteStorageContext ctx) {
    final RemoteProxySettings rps = ctx.getRemoteProxySettings();

    if (rps.isEnabled()) {
        final HttpHost proxy = new HttpHost(rps.getHostname(), rps.getPort());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        // check if we have non-proxy hosts
        if (rps.getNonProxyHosts() != null && !rps.getNonProxyHosts().isEmpty()) {
            final Set<Pattern> nonProxyHostPatterns = new HashSet<Pattern>(rps.getNonProxyHosts().size());
            for (String nonProxyHostRegex : rps.getNonProxyHosts()) {
                try {
                    nonProxyHostPatterns.add(Pattern.compile(nonProxyHostRegex, Pattern.CASE_INSENSITIVE));
                } catch (PatternSyntaxException e) {
                    logger.warn("Invalid non proxy host regex: {}", nonProxyHostRegex, e);
                }//from  w  w  w  .j a  v a 2 s.c  o  m
            }
            httpClient.setRoutePlanner(new NonProxyHostsAwareHttpRoutePlanner(
                    httpClient.getConnectionManager().getSchemeRegistry(), nonProxyHostPatterns));
        }

        configureAuthentication(httpClient, rps.getHostname(), rps.getPort(), rps.getProxyAuthentication());
    }
}

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 {//from w w  w. ja v a 2s . com
            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:com.android.tools.idea.sdk.remote.internal.UrlOpener.java

@NonNull
private static Pair<InputStream, HttpResponse> openWithHttpClient(@NonNull String url,
        @NonNull ITaskMonitor monitor, Header[] inHeaders) throws IOException, CanceledByUserException {
    UserCredentials result = null;//from w  w  w  .  j  a va  2  s .  co  m
    String realm = null;

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, sConnectionTimeoutMs);
    HttpConnectionParams.setSoTimeout(params, sSocketTimeoutMs);

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

    // create local execution context
    HttpContext localContext = new BasicHttpContext();
    final HttpGet httpGet = new HttpGet(url);
    if (inHeaders != null) {
        for (Header header : inHeaders) {
            httpGet.addHeader(header);
        }
    }

    // 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);

    if (DEBUG) {
        try {
            URI uri = new URI(url);
            ProxySelector sel = routePlanner.getProxySelector();
            if (sel != null && uri.getScheme().startsWith("httP")) { //$NON-NLS-1$
                List<Proxy> list = sel.select(uri);
                System.out.printf("SdkLib.UrlOpener:\n  Connect to: %s\n  Proxy List: %s\n", //$NON-NLS-1$
                        url, list == null ? "(null)" : Arrays.toString(list.toArray()));//$NON-NLS-1$
            }
        } catch (Exception e) {
            System.out.printf("SdkLib.UrlOpener: Failed to get proxy info for %s: %s\n", //$NON-NLS-1$
                    url, e.toString());
        }
    }

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

        if (DEBUG) {
            System.out.printf("  Status: %d\n", statusCode); //$NON-NLS-1$
        }

        // 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 || statusCode == HttpStatus.SC_NOT_MODIFIED) {
            // 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.
                InputStream is = new FilterInputStream(entity.getContent()) {
                    @Override
                    public void close() throws IOException {
                        // Since Http Client is no longer needed, close it.

                        // Bug #21167: we need to tell http client to shutdown
                        // first, otherwise the super.close() would continue
                        // downloading and not return till complete.

                        httpClient.getConnectionManager().shutdown();
                        super.close();
                    }
                };

                HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine());
                outResponse.setHeaders(response.getAllHeaders());
                outResponse.setLocale(response.getLocale());

                return Pair.of(is, outResponse);
            }
        } else if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
            // It's ok to not have an entity (e.g. nothing to download) for a 304
            HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine());
            outResponse.setHeaders(response.getAllHeaders());
            outResponse.setLocale(response.getLocale());

            return Pair.of(null, outResponse);
        }
    }

    // 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  .ja va  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;
}