Example usage for org.apache.http.conn.params ConnRouteParams setDefaultProxy

List of usage examples for org.apache.http.conn.params ConnRouteParams setDefaultProxy

Introduction

In this page you can find the example usage for org.apache.http.conn.params ConnRouteParams setDefaultProxy.

Prototype

public static void setDefaultProxy(final HttpParams params, final HttpHost proxy) 

Source Link

Document

Sets the ConnRoutePNames#DEFAULT_PROXY DEFAULT_PROXY parameter value.

Usage

From source file:ch.cyberduck.core.http.HttpSession.java

protected AbstractHttpClient http(final String hostname) {
    if (!clients.containsKey(hostname)) {
        final HttpParams params = new BasicHttpParams();

        HttpProtocolParams.setVersion(params, org.apache.http.HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, getEncoding());
        HttpProtocolParams.setUserAgent(params, getUserAgent());

        AuthParams.setCredentialCharset(params, Preferences.instance().getProperty("http.credentials.charset"));

        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoTimeout(params, timeout());
        HttpConnectionParams.setConnectionTimeout(params, timeout());
        HttpConnectionParams.setSocketBufferSize(params,
                Preferences.instance().getInteger("http.socket.buffer"));
        HttpConnectionParams.setStaleCheckingEnabled(params, true);

        HttpClientParams.setRedirecting(params, true);
        HttpClientParams.setAuthenticating(params, true);
        HttpClientParams.setCookiePolicy(params, CookiePolicy.BEST_MATCH);

        // Sets the timeout in milliseconds used when retrieving a connection from the ClientConnectionManager
        HttpClientParams.setConnectionManagerTimeout(params,
                Preferences.instance().getLong("http.manager.timeout"));

        SchemeRegistry registry = new SchemeRegistry();
        // Always register HTTP for possible use with proxy
        registry.register(new Scheme(ch.cyberduck.core.Scheme.http.toString(), host.getPort(),
                PlainSocketFactory.getSocketFactory()));
        registry.register(new Scheme(ch.cyberduck.core.Scheme.https.toString(), host.getPort(),
                new SSLSocketFactory(
                        new CustomTrustSSLProtocolSocketFactory(this.getTrustManager()).getSSLContext(),
                        new X509HostnameVerifier() {
                            @Override
                            public void verify(String host, SSLSocket ssl) throws IOException {
                                log.warn("Hostname verification disabled for:" + host);
                            }//from   ww  w.  jav  a  2s.  c o m

                            @Override
                            public void verify(String host, X509Certificate cert) throws SSLException {
                                log.warn("Hostname verification disabled for:" + host);
                            }

                            @Override
                            public void verify(String host, String[] cns, String[] subjectAlts)
                                    throws SSLException {
                                log.warn("Hostname verification disabled for:" + host);
                            }

                            @Override
                            public boolean verify(String s, javax.net.ssl.SSLSession sslSession) {
                                log.warn("Hostname verification disabled for:" + s);
                                return true;
                            }
                        })));
        if (Preferences.instance().getBoolean("connection.proxy.enable")) {
            final Proxy proxy = ProxyFactory.get();
            if (ch.cyberduck.core.Scheme.https.equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPSProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host)));
                }
            }
            if (ch.cyberduck.core.Scheme.http.equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPProxyHost(host), proxy.getHTTPProxyPort(host)));
                }
            }
        }
        PoolingClientConnectionManager manager = new PoolingClientConnectionManager(registry);
        manager.setMaxTotal(Preferences.instance().getInteger("http.connections.total"));
        manager.setDefaultMaxPerRoute(Preferences.instance().getInteger("http.connections.route"));
        AbstractHttpClient http = new DefaultHttpClient(manager, params);
        this.configure(http);
        clients.put(hostname, http);
    }
    return clients.get(hostname);
}

From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.NaturalLanguageClassifier.java

/**
 * Sends data to create and train a classifier, and returns information about the new
 * classifier. The status has the value of `Training` when the operation is
 * successful, and might remain at this status for a while.
 * //from www . j a v a  2 s. c om
 * @param name
 *            the classifier name
 * @param language
 *            IETF primary language for the classifier
 * @param trainingData
 *            The set of questions and their "keys" used to adapt a system to a domain
 *            (the ground truth)
 * @return the classifier
 * @see Classifier
 */
public Classifier createClassifier(final String name, final String language,
        final List<TrainingData> trainingData) {
    if (trainingData == null || trainingData.isEmpty())
        throw new IllegalArgumentException("trainingData can not be null or empty");

    JsonObject contentJson = new JsonObject();

    contentJson.addProperty("language", language == null ? LANGUAGE_EN : language);

    if (name != null && !name.isEmpty()) {
        contentJson.addProperty("name", name);
    }

    try {

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("training_data",
                new StringBody(TrainingDataUtils.toCSV(trainingData.toArray(new TrainingData[0]))));
        reqEntity.addPart("training_metadata", new StringBody(contentJson.toString()));

        HttpRequestBase request = Request.Post("/v1/classifiers").withEntity(reqEntity).build();
        HttpHost proxy = new HttpHost("10.100.1.124", 3128);
        ConnRouteParams.setDefaultProxy(request.getParams(), proxy);
        HttpResponse response = execute(request);
        return ResponseUtil.getObject(response, Classifier.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.shindig.gadgets.http.BasicHttpFetcher.java

/**
 * Creates a new fetcher for fetching HTTP objects.  Not really suitable
 * for production use. Use of an HTTP proxy for security is also necessary
 * for production deployment./*from  w  ww .  j a  v a  2  s  . c  o m*/
 *
 * @param maxObjSize          Maximum size, in bytes, of the object we will fetch, 0 if no limit..
 * @param connectionTimeoutMs timeout, in milliseconds, for connecting to hosts.
 * @param readTimeoutMs       timeout, in millseconds, for unresponsive connections
 * @param basicHttpFetcherProxy The http proxy to use.
 */
public BasicHttpFetcher(int maxObjSize, int connectionTimeoutMs, int readTimeoutMs,
        String basicHttpFetcherProxy) {
    // Create and initialize HTTP parameters
    setMaxObjectSizeBytes(maxObjSize);
    setSlowResponseWarning(DEFAULT_SLOW_RESPONSE_WARNING);

    HttpParams params = new BasicHttpParams();

    ConnManagerParams.setTimeout(params, connectionTimeoutMs);

    // These are probably overkill for most sites.
    ConnManagerParams.setMaxTotalConnections(params, 1152);
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(256));

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(params, "Apache Shindig");
    HttpProtocolParams.setContentCharset(params, "UTF-8");

    HttpConnectionParams.setConnectionTimeout(params, connectionTimeoutMs);
    HttpConnectionParams.setSoTimeout(params, readTimeoutMs);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);

    HttpClientParams.setRedirecting(params, true);
    HttpClientParams.setAuthenticating(params, false);

    // Create and initialize scheme registry
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    DefaultHttpClient client = new DefaultHttpClient(cm, params);

    // Set proxy if set via guice.
    if (!StringUtils.isEmpty(basicHttpFetcherProxy)) {
        String[] splits = basicHttpFetcherProxy.split(":");
        ConnRouteParams.setDefaultProxy(client.getParams(),
                new HttpHost(splits[0], Integer.parseInt(splits[1]), "http"));
    }

    // try resending the request once
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(1, true));

    // Add hooks for gzip/deflate
    client.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(final org.apache.http.HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip, deflate");
            }
        }
    });
    client.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final org.apache.http.HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    for (HeaderElement codec : ceheader.getElements()) {
                        String codecname = codec.getName();
                        if ("gzip".equalsIgnoreCase(codecname)) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            return;
                        } else if ("deflate".equals(codecname)) {
                            response.setEntity(new DeflateDecompressingEntity(response.getEntity()));
                            return;
                        }
                    }
                }
            }
        }
    });
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler());

    // Disable automatic storage and sending of cookies (see SHINDIG-1382)
    client.removeRequestInterceptorByClass(RequestAddCookies.class);
    client.removeResponseInterceptorByClass(ResponseProcessCookies.class);

    // Use Java's built-in proxy logic in case no proxy set via guice.
    if (StringUtils.isEmpty(basicHttpFetcherProxy)) {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    FETCHER = client;
}

From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.NaturalLanguageClassifier.java

/**
 * Sends data to create and train a classifier, and returns information about the new
 * classifier. The status has the value of `Training` when the operation is
 * successful, and might remain at this status for a while.
 *
 * @param name            the classifier name
 * @param language            IETF primary language for the classifier
 * @param csvTrainingData the CSV training data
 * @return the classifier//from w w w .  j a  va2 s . c  om
 * @see Classifier
 */
public Classifier createClassifier(final String name, final String language, final File csvTrainingData) {
    if (csvTrainingData == null || !csvTrainingData.exists())
        throw new IllegalArgumentException("csvTrainingData can not be null or not be found");

    JsonObject contentJson = new JsonObject();

    contentJson.addProperty("language", language == null ? LANGUAGE_EN : language);

    if (name != null && !name.isEmpty()) {
        contentJson.addProperty("name", name);
    }

    try {

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("training_data", new FileBody(csvTrainingData));
        reqEntity.addPart("training_metadata", new StringBody(contentJson.toString()));

        HttpRequestBase request = Request.Post("/v1/classifiers").withEntity(reqEntity).build();
        HttpHost proxy = new HttpHost("10.100.1.124", 3128);
        ConnRouteParams.setDefaultProxy(request.getParams(), proxy);
        HttpResponse response = execute(request);
        return ResponseUtil.getObject(response, Classifier.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.github.diogochbittencourt.googleplaydownloader.downloader.impl.DownloadThread.java

/**
 * Executes the download in a separate thread
 *//*  www.j  a v a 2 s.  c o m*/
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo, mService);
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;

    try {
        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
        wakeLock.acquire();

        if (Constants.LOGV) {
            Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
            Log.v(Constants.TAG, "  at " + mInfo.mUri);
        }

        client = AndroidHttpClient.newInstance(userAgent(), mContext);

        boolean finished = false;
        while (!finished) {
            if (Constants.LOGV) {
                Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
                Log.v(Constants.TAG, "  at " + mInfo.mUri);
            }
            // Set or unset proxy, which may have changed since last GET
            // request.
            // setDefaultProxy() supports null as proxy parameter.
            ConnRouteParams.setDefaultProxy(client.getParams(),
                    getPreferredHttpHost(mContext, state.mRequestUri));
            HttpGet request = new HttpGet(state.mRequestUri);
            try {
                executeDownload(state, client, request);
                finished = true;
            } catch (RetryDownload exc) {
                // fall through
            } finally {
                request.abort();
                request = null;
            }
        }

        if (Constants.LOGV) {
            Log.v(Constants.TAG, "download completed for " + mInfo.mFileName);
            Log.v(Constants.TAG, "  at " + mInfo.mUri);
        }
        finalizeDestinationFile(state);
        finalStatus = DownloaderService.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Log.w(Constants.TAG, "Aborting request for download " + mInfo.mFileName + ": " + error.getMessage());
        error.printStackTrace();
        finalStatus = error.mFinalStatus;
        // fall through to finally block
    } catch (Throwable ex) { // sometimes the socket code throws unchecked
        // exceptions
        Log.w(Constants.TAG, "Exception for " + mInfo.mFileName + ": " + ex);
        finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;
        // falls through to the code that reports an error
    } finally {
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        if (client != null) {
            client.close();
            client = null;
        }
        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mRedirectCount,
                state.mGotData, state.mFilename);
    }
}

From source file:com.google.android.vending.expansion.downloader.impl.DownloadThread.java

/**
 * Executes the download in a separate thread
 *//*from w w w.  j a v  a 2  s . c  o m*/
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo, mService);
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;

    try {
        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
        wakeLock.acquire();

        if (Constants.LOGV) {
            Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
            Log.v(Constants.TAG, "  at " + mInfo.mUri);
        }

        client = AndroidHttpClient.newInstance(userAgent(), mContext);

        boolean finished = false;
        while (!finished) {
            if (Constants.LOGV) {
                Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
                Log.v(Constants.TAG, "  at " + mInfo.mUri);
            }
            // Set or unset proxy, which may have changed since last GET
            // request.
            // setDefaultProxy() supports null as proxy parameter.
            ConnRouteParams.setDefaultProxy(client.getParams(),
                    getPreferredHttpHost(mContext, state.mRequestUri));
            HttpGet request = new HttpGet(state.mRequestUri);
            try {
                executeDownload(state, client, request);
                finished = true;
            } catch (RetryDownload exc) {
                // fall through
            } finally {
                request.abort();
                request = null;
            }
        }

        if (Constants.LOGV) {
            Log.v(Constants.TAG, "download completed for " + mInfo.mFileName);
            Log.v(Constants.TAG, "  at " + mInfo.mUri);
        }
        finalizeDestinationFile(state);
        finalStatus = DownloaderService.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Log.w(Constants.TAG, "Aborting request for download " + mInfo.mFileName + ": " + error.getMessage());
        error.printStackTrace();
        finalStatus = error.mFinalStatus;
        // fall through to finally block
    } catch (Throwable ex) { // sometimes the socket code throws unchecked
                             // exceptions
        Log.w(Constants.TAG, "Exception for " + mInfo.mFileName + ": " + ex);
        finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;
        // falls through to the code that reports an error
    } finally {
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        if (client != null) {
            client.close();
            client = null;
        }
        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mRedirectCount,
                state.mGotData, state.mFilename);
    }
}

From source file:code.google.restclient.core.Hitter.java

private HttpClient getHttpClient()
        throws KeyManagementException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException {
    // Early exit: already configured. Want all the gets to be fast so not synchronizing it
    if (client != null)
        return client;

    synchronized (lock) {
        HttpParams params = new SyncBasicHttpParams();

        // Set proxy
        if (isProxyConfigured()) {
            if (DEBUG_ENABLED)
                LOG.debug("CONFIGURING PROXY TO => " + proxyHost + ":" + proxyPort);
            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            ConnRouteParams.setDefaultProxy(params, proxy);
        }//from   w  ww .j a va 2s.c  om

        // http params apply at client level so shared by all request. They can be overridden by params set at request level.
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, RCConstants.DEFAULT_CHARSET);
        HttpProtocolParams.setUserAgent(params, RCConstants.APP_DISPLAY_NAME);
        HttpClientParams.setRedirecting(params, true);

        /*
         HttpConnectionParams.setTcpNoDelay(params, true);
         HttpConnectionParams.setLinger(params, 30);
         HttpConnectionParams.setConnectionTimeout(params, 30000);
         HttpConnectionParams.setSoTimeout(params, 30000);
         HttpProtocolParams.setUseExpectContinue(params, false);
         HttpClientParams.setCookiePolicy(params,
         CookiePolicy.BROWSER_COMPATIBILITY);
         */

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(getPlainScheme());
        registry.register(getSSLScheme(isDisabledCertVerifier(), isDisabledHostVerifier()));

        if (conman == null)
            conman = new ThreadSafeClientConnManager(registry);

        if (client == null) {
            client = new DefaultHttpClient(conman);
            ((DefaultHttpClient) client).setParams(params);
            ((DefaultHttpClient) client).setKeepAliveStrategy(new CustomKeepAliveStrategy());
            /*
            // set custom request retry handler which doesn't allow retry for POST request
            HttpRequestRetryHandler retryHandler = new CustomRetryHandler();
            ((DefaultHttpClient) client).setHttpRequestRetryHandler(retryHandler);
            client.getParams().setParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE, 10000); // 10 seconds
            */

        }

        return client;
    }
}

From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.NaturalLanguageClassifier.java

/**
 * Deletes a classifier./*from  w ww. jav a 2  s  . c  o  m*/
 * 
 * @param classifierId
 *            the classifier ID
 * @throws UnsupportedEncodingException 
 * @see Classifier
 */
public void deleteClassifier(String classifierId) throws UnsupportedEncodingException {
    if (classifierId == null || classifierId.isEmpty())
        throw new IllegalArgumentException("classifierId can not be null or empty");

    HttpRequestBase request = Request.Delete("/v1/classifiers/" + classifierId).build();
    HttpHost proxy = new HttpHost("10.100.1.124", 3128);
    ConnRouteParams.setDefaultProxy(request.getParams(), proxy);
    executeWithoutResponse(request);
}

From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.NaturalLanguageClassifier.java

/**
 * Retrieves a classifier.// w ww.  j  ava 2 s. c  o  m
 * 
 * @param classifierId
 *            the classifier ID
 * @return the classifier list
 * @throws UnsupportedEncodingException 
 * @see Classifier
 */
public Classifier getClassifier(String classifierId) throws UnsupportedEncodingException {
    if (classifierId == null || classifierId.isEmpty())
        throw new IllegalArgumentException("classifierId can not be null or empty");

    HttpRequestBase request = Request.Get("/v1/classifiers/" + classifierId).build();
    HttpHost proxy = new HttpHost("10.100.1.124", 3128);
    ConnRouteParams.setDefaultProxy(request.getParams(), proxy);
    try {
        HttpResponse response = execute(request);
        return ResponseUtil.getObject(response, Classifier.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.NaturalLanguageClassifier.java

/**
 * Retrieves the list of classifiers for the user.
 * /*from  ww w . j  a va2s .  c o m*/
 * @return the classifier list
 * @throws UnsupportedEncodingException 
 * @see Classifier
 */
public Classifiers getClassifiers() throws UnsupportedEncodingException {
    HttpRequestBase request = Request.Get("/v1/classifiers").build();
    HttpHost proxy = new HttpHost("10.100.1.124", 3128);
    ConnRouteParams.setDefaultProxy(request.getParams(), proxy);
    try {
        HttpResponse response = execute(request);
        return ResponseUtil.getObject(response, Classifiers.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}