Example usage for org.apache.http.impl.conn.tsccm ThreadSafeClientConnManager ThreadSafeClientConnManager

List of usage examples for org.apache.http.impl.conn.tsccm ThreadSafeClientConnManager ThreadSafeClientConnManager

Introduction

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

Prototype

public ThreadSafeClientConnManager() 

Source Link

Usage

From source file:org.dataconservancy.ui.it.support.CreateIdApiRequestIT.java

/**
 * Generates {@link #countToGenerate} ids, and insures that they are all unique.  Uses multiple threads to
 * generate the ids./*from   w ww  .j a v  a 2  s.c  om*/
 *
 * @throws Exception
 */
@Test
public void testGenerateUniqueIdsMultipleThreads() throws Exception {
    long start = Calendar.getInstance().getTimeInMillis();
    // The threads used to generate ids
    Thread threads[] = new Thread[5];

    // HttpClient requires a ThreadSafeClientConnectionManager
    final ThreadSafeClientConnManager conman = new ThreadSafeClientConnManager();
    conman.setMaxTotal(50);
    conman.setDefaultMaxPerRoute(5);
    hc = new DefaultHttpClient(conman);

    assertEquals("The number of threads (" + threads.length
            + ") must evenly divide into thenumber of ids to be " + "generated (" + countToGenerate + ")", 0,
            countToGenerate % threads.length);
    final int generatePerThread = countToGenerate / threads.length;

    // Launch a thread, with each thread being responsible for generating a portion of the total ids
    for (int j = 0; j < threads.length; j++) {
        threads[j] = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < generatePerThread; i++) {
                    double seed = Math.random();
                    log.trace("Seed is {}", seed);
                    Types t = selectType(seed, Types.values());
                    log.trace("Selected type {} with seed value {}", t, seed);

                    if (log.isDebugEnabled()) {
                        idTypeDistribution.putIfAbsent(t, new AtomicInteger(0));
                        idTypeDistribution.get(t).getAndAdd(1);
                    }

                    try {
                        generatedIds.add(reqFactory.createIdApiRequest(t).execute(hc));
                    } catch (IOException e) {
                        fail(e.getMessage());
                    }
                }
            }
        }, "ID Generation Thread " + j);
        threads[j].start();
    }

    // Wait for threads to stop
    for (int j = 0; j < threads.length; j++) {
        threads[j].join();
    }

    if (log.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder("ID distribution:\n");
        int totalGenerated = 0;
        for (Types t : Types.values()) {
            final Integer typeTotal = idTypeDistribution.get(t).intValue();
            totalGenerated += typeTotal;
            sb.append("Type: ").append(t).append(" Count: ").append(typeTotal).append("\n");
        }
        sb.append("Total generated: ").append(totalGenerated).append("\n");
        sb.append("Unique generated: ").append(generatedIds.size()).append("\n");
        sb.append("Number of threads: ").append(threads.length).append("\n");
        sb.append("Execution time: ").append(Calendar.getInstance().getTimeInMillis() - start).append(" ms\n");
        log.debug(sb.toString());
    }

    // The number of generated IDs (stored in the Set) should equal 'countToGenerate'
    assertEquals("Expected " + countToGenerate + " to be generated, but the Set contained "
            + generatedIds.size() + ".  Some ids may not have been unique.", countToGenerate,
            generatedIds.size());

}

From source file:com.seer.datacruncher.load.LoadRunner.java

/**
 * Return HttpClient// w  w  w  . j a v a  2  s .c o  m
 * @return
 */
public static DefaultHttpClient createClient() {
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
    cm.setMaxTotal(100);
    DefaultHttpClient client = new DefaultHttpClient(cm);
    return client;
}

From source file:org.commonjava.web.json.test.WebFixture.java

@Override
protected void before() throws Exception {
    final ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager();
    ccm.setMaxTotal(20);// www  .ja va 2 s  . c  o m

    http = new DefaultHttpClient(ccm);
    http.setCredentialsProvider(new CredentialsProvider() {

        @Override
        public void setCredentials(final AuthScope authscope, final Credentials credentials) {
        }

        @Override
        public Credentials getCredentials(final AuthScope authscope) {
            if (user != null) {
                return new UsernamePasswordCredentials(user, pass);
            }

            return null;
        }

        @Override
        public void clear() {
        }
    });
}

From source file:com.cheddargetter.client.service.CheddarGetterPaymentService.java

public void afterPropertiesSet() throws Exception {
    context = newInstance(Customers.class, Plans.class, Error.class, Success.class);

    ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager();
    connManager.setMaxTotal(25);/* w w  w .jav a 2  s  .com*/
    DefaultHttpClient httpClient = new DefaultHttpClient(connManager);
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(getHost().getHostName(), getHost().getPort()),
            new UsernamePasswordCredentials(getUserName(), getPassword()));
    this.httpClient = httpClient;
}

From source file:org.opengeoportal.proxy.controllers.OldDynamicOgcController.java

/** Called from {@link #init(javax.servlet.ServletConfig)}. HttpClient offers many opportunities for customization.
* @param hcParams*//*from  w  w w  .ja v  a2 s  .  c  o m*/
@SuppressWarnings("deprecation")
protected HttpClient createHttpClient(HttpParams hcParams) {
    return new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams);
}

From source file:com.lp.alm.lyo.client.oslc.OslcClient.java

/**
 * Initialize a new OslcClient using an Apache Http Components 4 Http client and configuration.
 * Use the provided TrustManagers and X509HostnameVerifiers instead of the defaults which do no verification;
 */// w  ww.ja  v  a 2  s. c  o  m
public OslcClient(TrustManager[] trustManagers, X509HostnameVerifier hostnameVerifier) {
    httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());
    httpClient.setRedirectStrategy(new RedirectStrategy() {
        @Override
        public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) {
            return null;
        }

        @Override
        public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
            return false;
        }
    });
    this.trustManagers = trustManagers;
    this.hostnameVerifier = hostnameVerifier;
    setupSSLSupport();
    clientPool = new OAuthHttpPool();
    clientConfig = new ApacheHttpClientConfig(httpClient);
    javax.ws.rs.core.Application app = new javax.ws.rs.core.Application() {
        @Override
        public Set<Class<?>> getClasses() {
            Set<Class<?>> classes = new HashSet<Class<?>>();
            classes.addAll(JenaProvidersRegistry.getProviders());
            classes.addAll(Json4JProvidersRegistry.getProviders());
            return classes;
        }
    };
    clientConfig = clientConfig.applications(app);

}

From source file:com.hp.mercury.ci.jenkins.plugins.OOBuildStep.java

private static void initializeHttpClient(DescriptorImpl descriptor) {

    final int maxConnectionsPerRoute = 100;
    final int maxConnectionsTotal = 100;

    ThreadSafeClientConnManager threadSafeClientConnManager = new ThreadSafeClientConnManager();
    threadSafeClientConnManager.setDefaultMaxPerRoute(maxConnectionsPerRoute);
    threadSafeClientConnManager.setMaxTotal(maxConnectionsTotal);

    httpClient = new DefaultHttpClient(threadSafeClientConnManager);
    if (descriptor.isIgnoreSsl()) {
        threadSafeClientConnManager.getSchemeRegistry()
                .register(new Scheme("https", 443, new FakeSocketFactory()));
    } else if (descriptor.getKeystorePath() != null) {
        try {//from ww  w . j av  a  2s.  co  m
            SSLSocketFactory sslSocketFactory = sslSocketFactoryFromCertificateFile(
                    descriptor.getKeystorePath(), decrypt(descriptor.getKeystorePassword()).toCharArray());
            sslSocketFactory.setHostnameVerifier(new BrowserCompatHostnameVerifier());
            // For less strict rules in dev mode you can try
            //sslSocketFactory.setHostnameVerifier(new AllowAllHostnameVerifier());
            threadSafeClientConnManager.getSchemeRegistry()
                    .register(new Scheme("https", 443, sslSocketFactory));
        } catch (NoSuchAlgorithmException e) {
            LOG.error("Could not register https scheme: ", e);
        } catch (KeyManagementException e) {
            LOG.error("Could not register https scheme: ", e);
        } catch (KeyStoreException e) {
            LOG.error("Could not register https scheme: ", e);
        } catch (UnrecoverableKeyException e) {
            LOG.error("Could not register https scheme: ", e);
        } catch (IOException e) {
            LOG.error("Could not load keystore file: ", e);
        } catch (CertificateException e) {
            LOG.error("Could not load keystore file: ", e);
        }
    }

    final HttpParams params = httpClient.getParams();
    final int timeoutInSeconds = descriptor.getTimeout() * 1000;
    HttpConnectionParams.setConnectionTimeout(params, timeoutInSeconds);
    HttpConnectionParams.setSoTimeout(params, timeoutInSeconds);
    HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), false);

    for (OOServer s : descriptor.getOoServers(true).values()) {

        URL url = null;
        try {
            url = new URL(s.getUrl());
        } catch (MalformedURLException mue) {
            //can't happen, we pre-validate the URLS during configuration and set active to false if bad.
        }

        //check why it doesn't use the credentials provider
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM, "basic"),
                new UsernamePasswordCredentials(s.getUsername(), decrypt(s.getPassword())));
    }

}

From source file:kornell.server.ProxyServlet.java

/** Called from {@link #init(javax.servlet.ServletConfig)}. HttpClient offers many opportunities
 * for customization. By default, SystemDefaultHttpClient is used available, otherwise it falls
 * back to://w w  w .  j a v  a  2s  .c om
 * <pre>new DefaultHttpClient(new ThreadSafeClientConnManager(),hcParams)</pre>*/
protected HttpClient createHttpClient(HttpParams hcParams) {
    try {
        //as of HttpComponents v4.2, this class is better since it uses System
        // Properties:
        Class clientClazz = Class.forName("org.apache.http.impl.client.SystemDefaultHttpClient");
        Constructor constructor = clientClazz.getConstructor(HttpParams.class);
        return (HttpClient) constructor.newInstance(hcParams);
    } catch (ClassNotFoundException e) {
        //no problem; use v4.1 below
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    //Fallback on using older client:
    return new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams);
}