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

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

Introduction

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

Prototype

public PoolingHttpClientConnectionManager() 

Source Link

Usage

From source file:jp.co.ctc_g.jse.core.rest.springmvc.client.ProxyClientHttpRequestFactory.java

/**
 * ???????HttpClient????????//from www  .ja v a2  s  .c  om
 * {@inheritDoc}
 */
@Override
public void afterPropertiesSet() throws Exception {

    Assert.notNull(proxyHost, "(proxyHost)???");
    Assert.notNull(proxyPort, "??(proxyPort)???");

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(maxTotal);
    connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);

    HttpClientBuilder builder = HttpClients.custom();
    builder.setConnectionManager(connectionManager);
    if (authentication) {
        Assert.notNull(username,
                "??true???????(username)???");
        Assert.notNull(password,
                "??true?????(password)???");
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(
                new HttpHost(proxyHost, Integer.parseInt(proxyPort)));
        builder.setRoutePlanner(routePlanner);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(proxyHost, Integer.parseInt(proxyPort)),
                new UsernamePasswordCredentials(username, password));
        builder.setDefaultCredentialsProvider(credsProvider);
    }
    builder.setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(readTimeout).build());
    CloseableHttpClient client = builder.build();
    setHttpClient(client);
}

From source file:org.wso2.carbon.mdm.mobileservices.windows.common.authenticator.OAuthTokenValidationStubFactory.java

/**
 * Creates an instance of PoolingHttpClientConnectionManager using HttpClient 4.x APIs
 *
 * @param properties Properties to configure PoolingHttpClientConnectionManager
 * @return An instance of properly configured PoolingHttpClientConnectionManager
 *///  w  w  w  .  j a  va2 s.  c om
private HttpClientConnectionManager createClientConnectionManager(Properties properties) {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    if (properties != null) {
        String maxConnectionsPerHostParam = properties
                .getProperty(PluginConstants.AuthenticatorProperties.MAX_CONNECTION_PER_HOST);
        if (maxConnectionsPerHostParam == null || maxConnectionsPerHostParam.isEmpty()) {
            if (log.isDebugEnabled()) {
                log.debug("MaxConnectionsPerHost parameter is not explicitly defined. Therefore, the default, "
                        + "which is 2, will be used");
            }
        } else {
            connectionManager.setDefaultMaxPerRoute(Integer.parseInt(maxConnectionsPerHostParam));
        }

        String maxTotalConnectionsParam = properties
                .getProperty(PluginConstants.AuthenticatorProperties.MAX_TOTAL_CONNECTIONS);
        if (maxTotalConnectionsParam == null || maxTotalConnectionsParam.isEmpty()) {
            if (log.isDebugEnabled()) {
                log.debug("MaxTotalConnections parameter is not explicitly defined. Therefore, the default, "
                        + "which is 10, will be used");
            }
        } else {
            connectionManager.setMaxTotal(Integer.parseInt(maxTotalConnectionsParam));
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Properties, i.e. MaxTotalConnections/MaxConnectionsPerHost, required to tune the "
                    + "HttpClient used in OAuth token validation service stub instances are not provided. "
                    + "Therefore, the defaults, 2/10 respectively, will be used");
        }
    }
    return connectionManager;
}

From source file:org.ambraproject.wombat.config.RootConfiguration.java

@Bean
public HttpClientConnectionManager httpClientConnectionManager(RuntimeConfiguration runtimeConfiguration) {
    PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();

    final RuntimeConfiguration.HttpConnectionPoolConfiguration httpConnectionPoolConfiguration = runtimeConfiguration
            .getHttpConnectionPoolConfiguration();
    Integer maxTotal = httpConnectionPoolConfiguration.getMaxTotal();
    if (maxTotal != null)
        manager.setMaxTotal(maxTotal);/*w w  w.j a v  a2 s  . c o m*/
    Integer defaultMaxPerRoute = httpConnectionPoolConfiguration.getDefaultMaxPerRoute();
    if (defaultMaxPerRoute != null)
        manager.setDefaultMaxPerRoute(defaultMaxPerRoute);

    return manager;
}

From source file:com.microsoft.cognitive.speakerrecognition.SpeakerIdentificationRestClient.java

/**
 * Initializes an instance of the service client
 *
 * @param subscriptionKey The subscription key to use
 *//*from  w  ww.  j  av a 2s. c  o m*/
public SpeakerIdentificationRestClient(String subscriptionKey) {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    // Increase max total connection to 200
    cm.setMaxTotal(200);
    // Increase default max connection per route to 20
    cm.setDefaultMaxPerRoute(20);

    CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
    defaultHttpClient = httpClient;//new DefaultHttpClient();
    gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:SS.SSS").create();
    clientHelper = new SpeakerRestClientHelper(subscriptionKey);
}

From source file:it.tidalwave.bluemarine2.downloader.impl.DefaultDownloader.java

/*******************************************************************************************************************
 *
 *
 *
 ******************************************************************************************************************/
@PostConstruct/* ww  w  .  j av a  2s.  c om*/
/* VisibleForTesting */ void initialize() {
    connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(200);
    connectionManager.setDefaultMaxPerRoute(20);

    cacheConfig = CacheConfig.custom().setAllow303Caching(true).setMaxCacheEntries(Integer.MAX_VALUE)
            .setMaxObjectSize(Integer.MAX_VALUE).setSharedCache(false).setHeuristicCachingEnabled(true).build();
    httpClient = CachingHttpClients.custom().setHttpCacheStorage(cacheStorage).setCacheConfig(cacheConfig)
            .setRedirectStrategy(dontFollowRedirect).setUserAgent("blueMarine (fabrizio.giudici@tidalwave.it)")
            .setDefaultHeaders(Arrays.asList(new BasicHeader("Accept", "application/n3")))
            .setConnectionManager(connectionManager).addInterceptorFirst(killCacheHeaders) // FIXME: only if  explicitly configured
            .build();
}

From source file:org.muhia.app.psi.integ.config.ke.shared.SharedWsClientConfiguration.java

@Bean(name = "sharedSecureHttpClient")
public CloseableHttpClient secureHttpClient() {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    try {/*from w ww .ja  v a2  s  . c  o m*/
        /*
        TODO: Modify to accept only specific certificates, test implementation is as below,
        TODO: need to find a way of determining if server url is https or not
        TODO: Whether we have imported the certificate or not
        */
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        Resource resource = loaderService.getResource(properties.getSharedKeystorePath());
        keyStore.load(resource.getInputStream(),
                hasher.getDecryptedValue(properties.getSharedKeystorePassword()).toCharArray());
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
                .loadKeyMaterial(keyStore,
                        hasher.getDecryptedValue(properties.getSharedKeystorePassword()).toCharArray())
                .build();
        //            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();

        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(properties.getSharedTransportConnectionTimeout())
                .setConnectionRequestTimeout(properties.getSharedTransportConnectionRequestTimeout())
                .setSocketTimeout(properties.getSharedTransportReadTimeout()).build();
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                sharedDataDTO.getTransportUsername(), sharedDataDTO.getTransportPassword());
        provider.setCredentials(AuthScope.ANY, credentials);

        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
        connManager.setMaxTotal(properties.getSharedPoolMaxHost());
        connManager.setDefaultMaxPerRoute(properties.getSharedPoolDefaultmaxPerhost());
        connManager.setValidateAfterInactivity(properties.getSharedPoolValidateAfterInactivity());
        httpClient = HttpClientBuilder.create().setSSLContext(sslContext)
                .setSSLHostnameVerifier(new NoopHostnameVerifier()).setDefaultRequestConfig(config)
                .setDefaultCredentialsProvider(provider).setConnectionManager(connManager)
                .evictExpiredConnections().addInterceptorFirst(new RemoveHttpHeadersInterceptor()).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | CertificateException
            | IOException | UnrecoverableKeyException e) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, e.getMessage(), e);
    }
    return httpClient;

}

From source file:ac.simons.tests.oembed.ExampleTest.java

@Test
public void dailyfratzeThroughCache() throws OembedException {
    final CacheManager cacheManager = CacheManager.create();
    final Oembed oembed = new OembedBuilder(HttpClients.createMinimal(new PoolingHttpClientConnectionManager()))
            .withCacheManager(cacheManager).withAutodiscovery(true).withConsumer("dailyfratze.de")
            .withProviders(new OembedProviderBuilder().withName("flickr").withFormat("xml")
                    .withEndpoint("http://www.flickr.com/services/oembed")
                    .withUrlSchemes("http://www\\.flickr\\.(com|de)/photos/.*").build())
            .build();/* w  ww  . jav  a2  s.  c o m*/

    OembedResponse response = oembed.transformUrl("http://dailyfratze.de/eller82/2013/5/1");
    System.out.println(response);

    response = oembed.transformUrl("http://dailyfratze.de/eller82/2013/5/1");
    System.out.println(response);

    // 404 etc. is not called twice      
    response = oembed.transformUrl("http://www.flickr.com/photos/idontexists/123456/");
    Assert.assertNull(response);

    response = oembed.transformUrl("http://www.flickr.com/photos/idontexists/123456/");
    Assert.assertNull(response);
}

From source file:org.openbaton.sdk.api.util.RestRequest.java

/**
 * Create a request with a given url path
 *//*from w ww  . ja  v  a2s.  co  m*/
public RestRequest(String username, String password, String projectId, boolean sslEnabled, final String nfvoIp,
        String nfvoPort, String path, String version) {
    if (sslEnabled) {
        this.baseUrl = "https://" + nfvoIp + ":" + nfvoPort + "/api/v" + version + path;
        this.provider = "https://" + nfvoIp + ":" + nfvoPort + "/oauth/token";
    } else {
        this.baseUrl = "http://" + nfvoIp + ":" + nfvoPort + "/api/v" + version + path;
        this.provider = "http://" + nfvoIp + ":" + nfvoPort + "/oauth/token";
    }
    this.username = username;
    this.password = password;
    this.projectId = projectId;

    GsonBuilder builder = new GsonBuilder();
    /*builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    return new Date(json.getAsJsonPrimitive().getAsLong());
        }
    });*/
    this.mapper = builder.setPrettyPrinting().create();

    if (sslEnabled)
        this.httpClient = getHttpClientForSsl();
    else
        this.httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config)
                .setConnectionManager(new PoolingHttpClientConnectionManager()).build();
}

From source file:de.rwth.dbis.acis.activitytracker.service.ActivityTrackerService.java

@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)/*from w  ww .ja  va2 s  .  co  m*/
@ApiOperation(value = "This method returns a list of activities", notes = "Default the latest ten activities will be returned")
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of activities"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") })
//TODO add filter
public HttpResponse getActivities(
        @ApiParam(value = "Before cursor pagination", required = false) @DefaultValue("-1") @QueryParam("before") int before,
        @ApiParam(value = "After cursor pagination", required = false) @DefaultValue("-1") @QueryParam("after") int after,
        @ApiParam(value = "Limit of elements of components", required = false) @DefaultValue("10") @QueryParam("limit") int limit,
        @ApiParam(value = "User authorization token", required = false) @DefaultValue("") @HeaderParam("authorization") String authorizationToken) {

    DALFacade dalFacade = null;
    try {
        if (before != -1 && after != -1) {
            ExceptionHandler.getInstance().throwException(ExceptionLocation.ACTIVITIESERVICE,
                    ErrorCode.WRONG_PARAMETER, "both: before and after parameter not possible");
        }
        int cursor = before != -1 ? before : after;
        Pageable.SortDirection sortDirection = after != -1 ? Pageable.SortDirection.ASC
                : Pageable.SortDirection.DESC;

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(20);
        CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();

        dalFacade = getDBConnection();
        Gson gson = new Gson();
        ExecutorService executor = Executors.newCachedThreadPool();

        int getObjectCount = 0;
        PaginationResult<Activity> activities;
        List<ActivityEx> activitiesEx = new ArrayList<>();
        Pageable pageInfo = new PageInfo(cursor, limit, "", sortDirection);
        while (activitiesEx.size() < limit && getObjectCount < 5) {
            pageInfo = new PageInfo(cursor, limit, "", sortDirection);
            activities = dalFacade.findActivities(pageInfo);
            getObjectCount++;
            cursor = sortDirection == Pageable.SortDirection.ASC ? cursor + limit : cursor - limit;
            if (cursor < 0) {
                cursor = 0;
            }
            activitiesEx.addAll(
                    getObjectBodies(httpclient, executor, authorizationToken, activities.getElements()));
        }

        executor.shutdown();
        if (activitiesEx.size() > limit) {
            activitiesEx = activitiesEx.subList(0, limit);
        }
        PaginationResult<ActivityEx> activitiesExResult = new PaginationResult<>(pageInfo, activitiesEx);

        HttpResponse response = new HttpResponse(gson.toJson(activitiesExResult.getElements()),
                HttpURLConnection.HTTP_OK);
        Map<String, String> parameter = new HashMap<>();
        parameter.put("limit", String.valueOf(limit));
        response = this.addPaginationToHtppResponse(activitiesExResult, "", parameter, response);

        return response;

    } catch (ActivityTrackerException atException) {
        return new HttpResponse(ExceptionHandler.getInstance().toJSON(atException),
                HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (Exception ex) {
        ActivityTrackerException atException = ExceptionHandler.getInstance().convert(ex,
                ExceptionLocation.ACTIVITIESERVICE, ErrorCode.UNKNOWN, ex.getMessage());
        return new HttpResponse(ExceptionHandler.getInstance().toJSON(atException),
                HttpURLConnection.HTTP_INTERNAL_ERROR);
    } finally {
        closeDBConnection(dalFacade);
    }
}