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

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

Introduction

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

Prototype

public BasicHttpClientConnectionManager() 

Source Link

Usage

From source file:org.apache.lucene.replicator.http.HttpReplicatorTest.java

@Test
public void testServerErrors() throws Exception {
    // tests the behaviour of the client when the server sends an error
    // must use BasicClientConnectionManager to test whether the client is closed correctly
    BasicHttpClientConnectionManager conMgr = new BasicHttpClientConnectionManager();
    Replicator replicator = new HttpReplicator(host, port, ReplicationService.REPLICATION_CONTEXT + "/s1",
            conMgr);/*  w  w w .java2  s  .c o  m*/
    ReplicationClient client = new ReplicationClient(replicator,
            new IndexReplicationHandler(handlerIndexDir, null), new PerSessionDirectoryFactory(clientWorkDir));

    try {
        publishRevision(5);

        try {
            replicationServlet.setRespondWithError(true);
            client.updateNow();
            fail("expected exception");
        } catch (Throwable t) {
            // expected
        }

        replicationServlet.setRespondWithError(false);
        client.updateNow(); // now it should work
        reopenReader();
        assertEquals(5, Integer.parseInt(reader.getIndexCommit().getUserData().get("ID"), 16));

        client.close();
    } finally {
        replicationServlet.setRespondWithError(false);
    }
}

From source file:org.whispersystems.mmsmonster.mms.MmsConnection.java

protected CloseableHttpClient constructHttpClient() throws IOException {
    RequestConfig config = RequestConfig.custom().setConnectTimeout(20 * 1000)
            .setConnectionRequestTimeout(20 * 1000).setSocketTimeout(20 * 1000).setMaxRedirects(20).build();

    URL mmsc = new URL(apn.getMmsc());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    if (apn.hasAuthentication()) {
        credsProvider.setCredentials(/*from   w  ww.ja v a 2s .com*/
                new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
                new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
    }

    return HttpClients.custom().setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
            .setRedirectStrategy(new LaxRedirectStrategy()).setUserAgent("Android-Mms/2.0")
            .setConnectionManager(new BasicHttpClientConnectionManager()).setDefaultRequestConfig(config)
            .setDefaultCredentialsProvider(credsProvider).build();
}

From source file:com.haulmont.cuba.client.sys.FileLoaderClientImpl.java

protected void saveStreamWithServlet(FileDescriptor fd, Supplier<InputStream> inputStreamSupplier,
        @Nullable StreamingProgressListener streamingListener)
        throws FileStorageException, InterruptedException {

    Object context = serverSelector.initContext();
    String selectedUrl = serverSelector.getUrl(context);
    if (selectedUrl == null) {
        throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName());
    }/*  w w  w.  ja  v a2  s. c om*/

    ClientConfig clientConfig = configuration.getConfig(ClientConfig.class);
    String fileUploadContext = clientConfig.getFileUploadContext();

    while (true) {
        String url = selectedUrl + fileUploadContext + "?s=" + userSessionSource.getUserSession().getId()
                + "&f=" + fd.toUrlParam();

        try (InputStream inputStream = inputStreamSupplier.get()) {
            InputStreamProgressEntity.UploadProgressListener progressListener = null;
            if (streamingListener != null) {
                progressListener = streamingListener::onStreamingProgressChanged;
            }

            HttpPost method = new HttpPost(url);
            method.setEntity(new InputStreamProgressEntity(inputStream, ContentType.APPLICATION_OCTET_STREAM,
                    progressListener));

            HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
            HttpClient client = HttpClientBuilder.create().setConnectionManager(connectionManager).build();
            try {
                HttpResponse response = client.execute(method);

                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    break;
                } else {
                    log.debug("Unable to upload file to {}\n{}", url, response.getStatusLine());
                    selectedUrl = failAndGetNextUrl(context);
                    if (selectedUrl == null) {
                        throw new FileStorageException(FileStorageException.Type.fromHttpStatus(statusCode),
                                fd.getName());
                    }
                }
            } catch (InterruptedIOException e) {
                log.trace("Uploading has been interrupted");
                throw new InterruptedException("File uploading is interrupted");
            } catch (IOException e) {
                log.debug("Unable to upload file to {}\n{}", url, e);
                selectedUrl = failAndGetNextUrl(context);
                if (selectedUrl == null) {
                    throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName(), e);
                }
            } finally {
                connectionManager.shutdown();
            }
        } catch (IOException | RetryUnsupportedException e) {
            throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName(), e);
        }
    }
}

From source file:com.floragunn.searchguard.HeaderAwareJestClientFactory.java

protected HttpClientConnectionManager createConnectionManager() {
    if (httpClientConfig.isMultiThreaded()) {
        log.debug("Multi-threaded http connection manager created");
        final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        final Integer maxTotal = httpClientConfig.getMaxTotalConnection();
        if (maxTotal != null) {
            cm.setMaxTotal(maxTotal);/*from  ww w . jav a2s  . com*/
        }
        final Integer defaultMaxPerRoute = httpClientConfig.getDefaultMaxTotalConnectionPerRoute();
        if (defaultMaxPerRoute != null) {
            cm.setDefaultMaxPerRoute(defaultMaxPerRoute);
        }
        final Map<HttpRoute, Integer> maxPerRoute = httpClientConfig.getMaxTotalConnectionPerRoute();
        for (final HttpRoute route : maxPerRoute.keySet()) {
            cm.setMaxPerRoute(route, maxPerRoute.get(route));
        }
        return cm;
    }
    log.debug("Default http connection is created without multi threaded option");
    return new BasicHttpClientConnectionManager();
}

From source file:com.tingtingapps.securesms.mms.LegacyMmsConnection.java

protected CloseableHttpClient constructHttpClient() throws IOException {
    RequestConfig config = RequestConfig.custom().setConnectTimeout(20 * 1000)
            .setConnectionRequestTimeout(20 * 1000).setSocketTimeout(20 * 1000).setMaxRedirects(20).build();

    URL mmsc = new URL(apn.getMmsc());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    if (apn.hasAuthentication()) {
        credsProvider.setCredentials(/*from w  ww  .j  a v a 2 s.  c  o  m*/
                new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
                new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
    }

    return HttpClients.custom().setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
            .setRedirectStrategy(new LaxRedirectStrategy())
            .setUserAgent(TextSecurePreferences.getMmsUserAgent(context, USER_AGENT))
            .setConnectionManager(new BasicHttpClientConnectionManager()).setDefaultRequestConfig(config)
            .setDefaultCredentialsProvider(credsProvider).build();
}

From source file:org.smssecure.smssecure.mms.LegacyMmsConnection.java

protected CloseableHttpClient constructHttpClient() throws IOException {
    RequestConfig config = RequestConfig.custom().setConnectTimeout(20 * 1000)
            .setConnectionRequestTimeout(20 * 1000).setSocketTimeout(20 * 1000).setMaxRedirects(20).build();

    URL mmsc = new URL(apn.getMmsc());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    if (apn.hasAuthentication()) {
        credsProvider.setCredentials(//from www  .j a  va2  s  .c  o  m
                new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
                new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
    }

    return HttpClients.custom().setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
            .setRedirectStrategy(new LaxRedirectStrategy())
            .setUserAgent(SilencePreferences.getMmsUserAgent(context, USER_AGENT))
            .setConnectionManager(new BasicHttpClientConnectionManager()).setDefaultRequestConfig(config)
            .setDefaultCredentialsProvider(credsProvider).build();
}

From source file:com.haulmont.restapi.idp.IdpAuthLifecycleManager.java

protected IdpSessionStatus pingIdpSessionServer(String idpSessionId) {
    log.debug("Ping IDP session {}", idpSessionId);

    String idpBaseURL = idpConfig.getIdpBaseURL();
    if (!idpBaseURL.endsWith("/")) {
        idpBaseURL += "/";
    }/*from   www .j a v  a2s. co  m*/
    String idpSessionPingUrl = idpBaseURL + "service/ping";

    HttpPost httpPost = new HttpPost(idpSessionPingUrl);
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());

    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
            Arrays.asList(new BasicNameValuePair("idpSessionId", idpSessionId),
                    new BasicNameValuePair("trustedServicePassword", idpConfig.getIdpTrustedServicePassword())),
            StandardCharsets.UTF_8);

    httpPost.setEntity(formEntity);

    HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
    HttpClient client = HttpClientBuilder.create().setConnectionManager(connectionManager).build();

    try {
        HttpResponse httpResponse = client.execute(httpPost);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.GONE.value()) {
            log.debug("IDP session expired {}", idpSessionId);

            return IdpSessionStatus.EXPIRED;
        }
        if (statusCode != HttpStatus.OK.value()) {
            log.warn("IDP respond status {} on session ping", statusCode);
        }
    } catch (IOException e) {
        log.warn("Unable to ping IDP {} session {}", idpSessionPingUrl, idpSessionId, e);
    } finally {
        connectionManager.shutdown();
    }

    return IdpSessionStatus.ALIVE;
}

From source file:com.haulmont.cuba.client.sys.FileLoaderClientImpl.java

protected InputStream openStreamWithServlet(FileDescriptor fd) throws FileStorageException {
    ClientConfig clientConfig = configuration.getConfig(ClientConfig.class);
    String fileDownloadContext = clientConfig.getFileDownloadContext();

    Object context = serverSelector.initContext();
    String selectedUrl = serverSelector.getUrl(context);
    if (selectedUrl == null) {
        throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName());
    }/*from   ww  w.  jav  a 2 s.  c o m*/
    while (true) {
        String url = selectedUrl + fileDownloadContext + "?s=" + userSessionSource.getUserSession().getId()
                + "&f=" + fd.getId().toString();

        HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
        HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager).build();

        HttpGet httpGet = new HttpGet(url);

        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int httpStatus = httpResponse.getStatusLine().getStatusCode();
            if (httpStatus == HttpStatus.SC_OK) {
                HttpEntity httpEntity = httpResponse.getEntity();
                if (httpEntity != null) {
                    return httpEntity.getContent();
                } else {
                    log.debug("Unable to download file from {}\nHttpEntity is null", url);
                    selectedUrl = failAndGetNextUrl(context);
                    if (selectedUrl == null) {
                        throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName());
                    }
                }
            } else {
                log.debug("Unable to download file from {}\n{}", url, httpResponse.getStatusLine());
                selectedUrl = failAndGetNextUrl(context);
                if (selectedUrl == null) {
                    throw new FileStorageException(FileStorageException.Type.fromHttpStatus(httpStatus),
                            fd.getName());
                }
            }
        } catch (InterruptedIOException e) {
            log.trace("Downloading has been interrupted");
            throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName(), e);
        } catch (IOException ex) {
            log.debug("Unable to download file from {}\n{}", url, ex);
            selectedUrl = failAndGetNextUrl(context);
            if (selectedUrl == null) {
                throw new FileStorageException(FileStorageException.Type.IO_EXCEPTION, fd.getName(), ex);
            }
        }
    }
}