Example usage for org.apache.http.conn HttpClientConnectionManager shutdown

List of usage examples for org.apache.http.conn HttpClientConnectionManager shutdown

Introduction

In this page you can find the example usage for org.apache.http.conn HttpClientConnectionManager shutdown.

Prototype

void shutdown();

Source Link

Document

Shuts down this connection manager and releases allocated resources.

Usage

From source file:net.community.chest.gitcloud.facade.frontend.git.HttpClientConnectionManagerFactoryBean.java

@Override
public void destroy() throws Exception {
    HttpClientConnectionManager mgr = getObject();
    logger.info("destroy()");
    mgr.shutdown();
}

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 a  2 s.c  o  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.web.security.idp.BaseIdpSessionFilter.java

@Nullable
protected IdpSession getIdpSession(String idpTicket) throws IdpActivationException {
    String idpBaseURL = webIdpConfig.getIdpBaseURL();
    if (!idpBaseURL.endsWith("/")) {
        idpBaseURL += "/";
    }//www. jav  a  2s .  c o  m
    String idpTicketActivateUrl = idpBaseURL + "service/activate";

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

    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
            Arrays.asList(new BasicNameValuePair("serviceProviderTicket", idpTicket), new BasicNameValuePair(
                    "trustedServicePassword", webIdpConfig.getIdpTrustedServicePassword())),
            StandardCharsets.UTF_8);

    httpPost.setEntity(formEntity);

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

    String idpResponse;
    try {
        HttpResponse httpResponse = client.execute(httpPost);

        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == 410) {
            // used old ticket
            return null;
        }

        if (statusCode != 200) {
            throw new IdpActivationException("Idp respond with status " + statusCode);
        }

        idpResponse = new BasicResponseHandler().handleResponse(httpResponse);
    } catch (IOException e) {
        throw new IdpActivationException(e);
    } finally {
        connectionManager.shutdown();
    }

    IdpSession session;
    try {
        session = new Gson().fromJson(idpResponse, IdpSession.class);
    } catch (JsonSyntaxException e) {
        throw new IdpActivationException("Unable to parse idp response", e);
    }

    return session;
}

From source file:com.haulmont.cuba.web.security.idp.IdpSessionPingConnector.java

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

    String idpBaseURL = webIdpConfig.getIdpBaseURL();
    if (!idpBaseURL.endsWith("/")) {
        idpBaseURL += "/";
    }/*from  ww w  .jav a  2s  . c om*/
    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", webIdpConfig.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 == 410) {
            // we have to logout user
            log.debug("IDP session is expired {}", idpSessionId);

            if (userSessionSource.checkCurrentUserSession()) {
                authenticationService.logout();

                UserSession userSession = userSessionSource.getUserSession();

                throw new NoUserSessionException(userSession.getId());
            }
        }
        if (statusCode != 200) {
            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();
    }
}

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

@Nullable
protected IdpSession getIdpSession(String idpTicket) throws InvalidGrantException {
    String idpBaseURL = this.idpBaseURL;
    if (!idpBaseURL.endsWith("/")) {
        idpBaseURL += "/";
    }// w  w  w.jav  a2s  . c om
    String idpTicketActivateUrl = idpBaseURL + "service/activate";

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

    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
            Arrays.asList(new BasicNameValuePair("serviceProviderTicket", idpTicket),
                    new BasicNameValuePair("trustedServicePassword", idpTrustedServicePassword)),
            StandardCharsets.UTF_8);

    httpPost.setEntity(formEntity);

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

    String idpResponse;
    try {
        HttpResponse httpResponse = client.execute(httpPost);

        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == 410) {
            // used old ticket
            return null;
        }

        if (statusCode != 200) {
            throw new RuntimeException("Idp respond with status " + statusCode);
        }

        idpResponse = new BasicResponseHandler().handleResponse(httpResponse);
    } catch (IOException e) {
        throw new RuntimeException("Unable to connect to IDP", e);
    } finally {
        connectionManager.shutdown();
    }

    IdpSession session;
    try {
        session = new Gson().fromJson(idpResponse, IdpSession.class);
    } catch (JsonSyntaxException e) {
        throw new RuntimeException("Unable to parse idp response", e);
    }

    return session;
}

From source file:org.glassfish.jersey.apache.connector.HelloWorldTest.java

public void _testConnectionPoolSharing(final boolean sharingEnabled) throws Exception {

    final HttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();

    final ClientConfig cc = new ClientConfig();
    cc.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
    cc.property(ApacheClientProperties.CONNECTION_MANAGER_SHARED, sharingEnabled);
    cc.connectorProvider(new ApacheConnectorProvider());

    final Client clientOne = ClientBuilder.newClient(cc);
    WebTarget target = clientOne.target(getBaseUri()).path(ROOT_PATH);
    target.request().get();//ww  w  .j  a  v  a 2 s  .  c o m
    clientOne.close();

    final boolean exceptionExpected = !sharingEnabled;

    final Client clientTwo = ClientBuilder.newClient(cc);
    target = clientTwo.target(getBaseUri()).path(ROOT_PATH);
    try {
        target.request().get();
        if (exceptionExpected) {
            Assert.fail("Exception expected");
        }
    } catch (Exception e) {
        if (!exceptionExpected) {
            Assert.fail("Exception not expected");
        }
    } finally {
        clientTwo.close();
    }

    if (sharingEnabled) {
        connectionManager.shutdown();
    }
}

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());
    }/*ww w  . ja  va 2s.c  o  m*/

    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.sonatype.nexus.ssl.plugin.internal.CertificateRetriever.java

/**
 * Retrieves certificate chain of specified host:port using https protocol.
 *
 * @param host to get certificate chain from (cannot be null)
 * @param port of host to connect to/*w  ww  .j av  a2 s  . c o m*/
 * @return certificate chain
 * @throws Exception Re-thrown from accessing the remote host
 */
public Certificate[] retrieveCertificatesFromHttpsServer(final String host, final int port) throws Exception {
    checkNotNull(host);

    log.info("Retrieving certificate from https://{}:{}", host, port);

    // setup custom connection manager so we can configure SSL to trust-all
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, new TrustManager[] { ACCEPT_ALL_TRUST_MANAGER }, null);
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sc,
            NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(HttpSchemes.HTTP, PlainConnectionSocketFactory.getSocketFactory())
            .register(HttpSchemes.HTTPS, sslSocketFactory).build();
    final HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(registry);

    try {
        final AtomicReference<Certificate[]> certificates = new AtomicReference<>();

        HttpClient httpClient = httpClientManager.create(new Customizer() {
            @Override
            public void customize(final HttpClientPlan plan) {
                // replace connection-manager with customized version needed to fetch SSL certificates
                plan.getClient().setConnectionManager(connectionManager);

                // add interceptor to grab peer-certificates
                plan.getClient().addInterceptorFirst(new HttpResponseInterceptor() {
                    @Override
                    public void process(final HttpResponse response, final HttpContext context)
                            throws HttpException, IOException {
                        ManagedHttpClientConnection connection = HttpCoreContext.adapt(context)
                                .getConnection(ManagedHttpClientConnection.class);

                        // grab the peer-certificates from the session
                        if (connection != null) {
                            SSLSession session = connection.getSSLSession();
                            if (session != null) {
                                certificates.set(session.getPeerCertificates());
                            }
                        }
                    }
                });
            }
        });

        httpClient.execute(new HttpGet("https://" + host + ":" + port));

        return certificates.get();
    } finally {
        // shutdown single-use connection manager
        connectionManager.shutdown();
    }
}

From source file:com.xebialabs.overthere.winrm.WinRmClient.java

/**
 * Internal sendRequest, performs the HTTP request and returns the result document.
 *///from w  ww.j a  va2  s  .  co  m
private Document doSendRequest(final Document requestDocument, final SoapAction soapAction) {
    final HttpClientBuilder client = HttpClientBuilder.create();
    HttpClientConnectionManager connectionManager = getHttpClientConnectionManager();
    try {
        configureHttpClient(client);
        try (CloseableHttpClient httpClient = client.build()) {
            final HttpContext context = new BasicHttpContext();
            final HttpPost request = new HttpPost(targetURL.toURI());

            if (soapAction != null) {
                request.setHeader("SOAPAction", soapAction.getValue());
            }

            final String requestBody = toString(requestDocument);
            logger.trace("Request:\nPOST {}\n{}", targetURL, requestBody);

            final HttpEntity entity = createEntity(requestBody);
            request.setEntity(entity);

            final HttpResponse response = httpClient.execute(request, context);

            logResponseHeaders(response);

            Document responseDocument = null;
            try {
                final String responseBody = handleResponse(response, context);
                responseDocument = DocumentHelper.parseText(responseBody);
                logDocument("Response body:", responseDocument);
            } catch (WinRmRuntimeIOException e) {
                if (response.getStatusLine().getStatusCode() == 200) {
                    throw e;
                }
            }

            if (response.getStatusLine().getStatusCode() != 200) {
                throw new WinRmRuntimeIOException(String.format("Unexpected HTTP response on %s:  %s (%s)",
                        targetURL, response.getStatusLine().getReasonPhrase(),
                        response.getStatusLine().getStatusCode()));
            }

            return responseDocument;
        } finally {
            connectionManager.shutdown();
        }
    } catch (WinRmRuntimeIOException exc) {
        throw exc;
    } catch (Exception exc) {
        throw new WinRmRuntimeIOException("Error when sending request to " + targetURL, requestDocument, null,
                exc);
    }
}