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(final Lookup<ConnectionSocketFactory> socketFactoryRegistry) 

Source Link

Usage

From source file:com.tremolosecurity.proxy.util.HttpClientUtils.java

public static HttpClient createSingleClient(ConfigManager cfg) {
    BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
            cfg.getHttpClientSocketRegistry());

    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(bhcm).build();

    return httpclient;
}

From source file:com.tremolosecurity.unison.proxy.auth.openidconnect.loadUser.LoadAttributesFromWS.java

public Map loadUserAttributesFromIdP(HttpServletRequest request, HttpServletResponse response,
        ConfigManager cfg, HashMap<String, Attribute> authParams, Map accessToken) throws Exception {
    String bearerTokenName = authParams.get("bearerTokenName").getValues().get(0);
    String url = authParams.get("restURL").getValues().get(0);

    BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
            GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry());
    RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
    CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultRequestConfig(rc)
            .build();//from  w w  w  . j ava  2  s  . com

    HttpGet get = new HttpGet(url);

    get.addHeader("Authorization", "Bearer " + request.getSession().getAttribute(bearerTokenName));

    CloseableHttpResponse httpResp = http.execute(get);

    BufferedReader in = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));

    StringBuffer token = new StringBuffer();

    String line = null;
    while ((line = in.readLine()) != null) {
        token.append(line);
    }

    httpResp.close();
    bhcm.close();

    Map jwtNVP = com.cedarsoftware.util.io.JsonReader.jsonToMaps(token.toString());

    return jwtNVP;

}

From source file:de.undercouch.gradle.tasks.download.internal.DefaultHttpClientFactory.java

@Override
public CloseableHttpClient createHttpClient(HttpHost httpHost, boolean acceptAnyCertificate) {
    HttpClientBuilder builder = HttpClientBuilder.create();

    //configure proxy from system environment
    builder.setRoutePlanner(new SystemDefaultRoutePlanner(null));

    //accept any certificate if necessary
    if ("https".equals(httpHost.getSchemeName()) && acceptAnyCertificate) {
        SSLConnectionSocketFactory icsf = getInsecureSSLSocketFactory();
        builder.setSSLSocketFactory(icsf);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", icsf).build();
        HttpClientConnectionManager cm = new BasicHttpClientConnectionManager(registry);
        builder.setConnectionManager(cm);
    }//from  ww w. ja  v  a  2  s .  c o  m

    //add an interceptor that replaces the invalid Content-Type
    //'none' by 'identity'
    builder.addInterceptorFirst(new ContentEncodingNoneInterceptor());

    CloseableHttpClient client = builder.build();
    return client;
}

From source file:com.mirth.connect.plugins.httpauth.oauth2.OAuth2Authenticator.java

@Override
public AuthenticationResult authenticate(RequestInfo request) throws Exception {
    OAuth2HttpAuthProperties properties = getReplacedProperties(request);

    CloseableHttpClient client = null;//from   ww  w.ja v  a 2 s .  c om
    CloseableHttpResponse response = null;

    try {
        // Create and configure the client and context 
        RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory());
        ConnectorPluginProperties pluginProperties = null;
        if (CollectionUtils.isNotEmpty(properties.getConnectorPluginProperties())) {
            pluginProperties = properties.getConnectorPluginProperties().iterator().next();
        }
        provider.getHttpConfiguration().configureSocketFactoryRegistry(pluginProperties, socketFactoryRegistry);
        BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                socketFactoryRegistry.build());
        httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(SOCKET_TIMEOUT).build());
        HttpClientBuilder clientBuilder = HttpClients.custom()
                .setConnectionManager(httpClientConnectionManager);
        HttpUtil.configureClientBuilder(clientBuilder);
        client = clientBuilder.build();

        HttpClientContext context = HttpClientContext.create();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(SOCKET_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT).setStaleConnectionCheckEnabled(true).build();
        context.setRequestConfig(requestConfig);

        URIBuilder uriBuilder = new URIBuilder(properties.getVerificationURL());

        // Add query parameters
        if (properties.getTokenLocation() == TokenLocation.QUERY) {
            List<String> paramList = request.getQueryParameters().get(properties.getLocationKey());
            if (CollectionUtils.isNotEmpty(paramList)) {
                for (String value : paramList) {
                    uriBuilder.addParameter(properties.getLocationKey(), value);
                }
            }
        }

        // Build the final URI and create a GET request
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // Add headers
        if (properties.getTokenLocation() == TokenLocation.HEADER) {
            List<String> headerList = request.getHeaders().get(properties.getLocationKey());
            if (CollectionUtils.isNotEmpty(headerList)) {
                for (String value : headerList) {
                    httpGet.addHeader(properties.getLocationKey(), value);
                }
            }
        }

        // Execute the request
        response = client.execute(httpGet, context);

        // Determine authentication from the status code 
        if (response.getStatusLine().getStatusCode() < 400) {
            return AuthenticationResult.Success();
        } else {
            return AuthenticationResult.Failure();
        }
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:io.fabric8.maven.docker.access.hc.http.HttpClientBuilder.java

private static HttpClientConnectionManager getBasicConnectionFactory(String certPath) throws IOException {
    return certPath != null ? new BasicHttpClientConnectionManager(getSslFactoryRegistry(certPath))
            : new BasicHttpClientConnectionManager();
}

From source file:org.jboss.as.test.http.util.TestHttpClientUtils.java

/**
 *@param credentialsProvider optional cred provider
 * @return client that doesn't verify https connections
 *///w  ww.  ja v  a  2  s .  c  om
public static CloseableHttpClient getHttpsClient(CredentialsProvider credentialsProvider) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);

        ctx.init(null, new TrustManager[] { tm }, null);

        SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(ctx,
                new NoopHostnameVerifier());

        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionFactory).build();
        HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
        HttpClientBuilder builder = HttpClientBuilder.create().setSSLSocketFactory(sslConnectionFactory)
                .setSSLHostnameVerifier(new NoopHostnameVerifier()).setConnectionManager(ccm);

        if (credentialsProvider != null) {
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }
        return builder.build();
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:RGSOplataRu.ClientConfiguretor.java

public CloseableHttpClient ConfigureSocketLayer() throws Exception {
    KeyStore keyStore = null;/* w  w  w  .  java 2  s .c o  m*/
    KeyStore trustStore = null;
    if (keyStoreResouce != null && keyStorePassword != null)
        keyStore = TrustStoreLoader.loadKeyStorePFX(keyStoreResouce, keyStorePassword);
    if (trustStoreResouce != null && trustStorePassword != null)
        trustStore = TrustStoreLoader.loadTrustStore(trustStoreResouce, trustStorePassword);

    SSLContext context = TrustStoreLoader.getTLSContext(keyStore, keyStorePassword, trustStore);
    //        SSLConnectionSocketFactory SSLsf = new SSLConnectionSocketFactory(context, new DefaultHostnameVerifier());
    SSLConnectionSocketFactory SSLsf = new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE);

    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", SSLsf).register("http", new PlainConnectionSocketFactory()).build();
    HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);

    return HttpClientBuilder.create().setConnectionManager(ccm)
            // !!! FOR TEST ONLY
            //.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
            .build();
}

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/*from w  w w.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.tremolosecurity.scalejs.register.ws.ScaleRegister.java

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain)
        throws Exception {
    Gson gson = new Gson();
    request.getServletRequest().setAttribute("com.tremolosecurity.unison.proxy.noRedirectOnError",
            "com.tremolosecurity.unison.proxy.noRedirectOnError");
    if (request.getRequestURI().endsWith("/register/config")) {
        response.setContentType("application/json");
        ScaleJSUtils.addCacheHeaders(response);
        response.getWriter().println(gson.toJson(scaleConfig).trim());

    } else if (request.getRequestURI().endsWith("/register/submit")) {
        ScaleError errors = new ScaleError();
        String json = new String((byte[]) request.getAttribute(ProxySys.MSG_BODY));
        NewUserRequest newUser = gson.fromJson(json, NewUserRequest.class);

        if (scaleConfig.isRequireReCaptcha()) {
            if (newUser.getReCaptchaCode() == null || newUser.getReCaptchaCode().isEmpty()) {
                errors.getErrors().add("Please verify you are not a robot");
            } else {
                BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(
                        GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry());
                RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
                CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm)
                        .setDefaultRequestConfig(rc).build();
                HttpPost httppost = new HttpPost("https://www.google.com/recaptcha/api/siteverify");

                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                formparams.add(new BasicNameValuePair("secret", scaleConfig.getRcSecretKey()));
                formparams.add(new BasicNameValuePair("response", newUser.getReCaptchaCode()));
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");

                httppost.setEntity(entity);

                CloseableHttpResponse resp = http.execute(httppost);

                ReCaptchaResponse res = gson.fromJson(EntityUtils.toString(resp.getEntity()),
                        ReCaptchaResponse.class);

                if (!res.isSuccess()) {
                    errors.getErrors().add("Human validation failed");
                }//from  w  ww . j  a  va  2s . c o m

                http.close();
                bhcm.close();

            }
        }

        if (scaleConfig.isRequireTermsAndConditions() && !newUser.isCheckedTermsAndConditions()) {
            errors.getErrors().add("You must accept the terms and conditions to register");
        }

        if (this.scaleConfig.isRequireReason()
                && (newUser.getReason() == null || newUser.getReason().isEmpty())) {
            errors.getErrors().add("Reason is required");
        }

        if (this.scaleConfig.isPreSetPassword()) {
            if (newUser.getPassword() == null || newUser.getPassword().isEmpty()) {
                errors.getErrors().add("Password is required");
            } else if (!newUser.getPassword().equals(newUser.getPassword2())) {
                errors.getErrors().add("Passwords must match");
            }
        }

        for (String attributeName : this.scaleConfig.getAttributes().keySet()) {
            String value = newUser.getAttributes().get(attributeName);

            if (this.scaleConfig.getAttributes().get(attributeName) == null) {
                errors.getErrors().add("Invalid attribute : '" + attributeName + "'");

            }

            if (this.scaleConfig.getAttributes().get(attributeName).isReadOnly()) {
                errors.getErrors().add("Attribute is read only : '"
                        + this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + "'");

            }

            if (this.scaleConfig.getAttributes().get(attributeName).isRequired()
                    && (value == null || value.length() == 0)) {
                errors.getErrors().add("Attribute is required : '"
                        + this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + "'");

            }

            if (this.scaleConfig.getAttributes().get(attributeName).getMinChars() > 0
                    && this.scaleConfig.getAttributes().get(attributeName).getMinChars() < value.length()) {
                errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName()
                        + " must have at least "
                        + this.scaleConfig.getAttributes().get(attributeName).getMinChars() + " characters");

            }

            if (this.scaleConfig.getAttributes().get(attributeName).getMaxChars() > 0
                    && this.scaleConfig.getAttributes().get(attributeName).getMaxChars() > value.length()) {
                errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName()
                        + " must have at most "
                        + this.scaleConfig.getAttributes().get(attributeName).getMaxChars() + " characters");

            }

            if (this.scaleConfig.getAttributes().get(attributeName).getType().equalsIgnoreCase("list")) {
                boolean found = false;
                for (NVP nvp : this.scaleConfig.getAttributes().get(attributeName).getValues()) {
                    if (nvp.getValue().equalsIgnoreCase(value)) {
                        found = true;
                    }
                }

                if (!found) {
                    errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName()
                            + " has an invalid value");
                }
            }

            if (this.scaleConfig.getAttributes().get(attributeName).getPattern() != null) {
                boolean ok = true;
                try {
                    Matcher m = this.scaleConfig.getAttributes().get(attributeName).getPattern().matcher(value);
                    if (m == null || !m.matches()) {
                        ok = false;
                    }
                } catch (Exception e) {
                    ok = false;
                }

                if (!ok) {
                    errors.getErrors().add("Attribute value not valid : '"
                            + this.scaleConfig.getAttributes().get(attributeName).getDisplayName() + "' - "
                            + this.scaleConfig.getAttributes().get(attributeName).getRegExFailedMsg());
                }
            }

            if (this.scaleConfig.getAttributes().get(attributeName).isUnique()) {
                String filter = equal(attributeName, value).toString();

                LDAPSearchResults res = GlobalEntries.getGlobalEntries().getConfigManager().getMyVD().search(
                        GlobalEntries.getGlobalEntries().getConfigManager().getCfg().getLdapRoot(), 2, filter,
                        new ArrayList<String>());
                if (res.hasMore()) {
                    errors.getErrors().add(this.scaleConfig.getAttributes().get(attributeName).getDisplayName()
                            + " is not available");
                }
                while (res.hasMore())
                    res.next();
            }
        }

        WFCall wfcall = null;
        String wfName = this.scaleConfig.getWorkflowName();
        if (errors.getErrors().isEmpty()) {
            if (scaleConfig.isUseCustomSubmission()) {

                AuthInfo userData = ((AuthController) request.getSession()
                        .getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();

                wfName = cru.createTremoloUser(newUser, errors.getErrors(), userData);
            }
        }

        if (errors.getErrors().isEmpty()) {
            TremoloUser user = new TremoloUser();

            AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL))
                    .getAuthInfo();

            if (this.scaleConfig.isSubmitLoggedInUser()) {
                user.setUid(
                        userData.getAttribs().get(this.scaleConfig.getUidAttributeName()).getValues().get(0));
                user.getAttributes().add(new Attribute(this.scaleConfig.getUidAttributeName(),
                        userData.getAttribs().get(this.scaleConfig.getUidAttributeName()).getValues().get(0)));
            } else {
                user.setUid(newUser.getAttributes().get(this.scaleConfig.getUidAttributeName()));
            }

            for (String attrName : newUser.getAttributes().keySet()) {
                user.getAttributes().add(new Attribute(attrName, newUser.getAttributes().get(attrName)));
            }

            if (this.scaleConfig.isPreSetPassword()) {
                user.setUserPassword(newUser.getPassword());

            }

            wfcall = new WFCall();
            wfcall.setUidAttributeName(this.scaleConfig.getUidAttributeName());
            wfcall.setReason(newUser.getReason());
            wfcall.setName(wfName);
            wfcall.setUser(user);

            HashMap<String, Object> params = new HashMap<String, Object>();
            wfcall.setRequestParams(params);

            if (userData.getAuthLevel() != 0 && !this.scaleConfig.isSubmitLoggedInUser()) {
                wfcall.setRequestor(
                        userData.getAttribs()
                                .get(GlobalEntries.getGlobalEntries().getConfigManager().getCfg()
                                        .getProvisioning().getApprovalDB().getUserIdAttribute())
                                .getValues().get(0));
                wfcall.getRequestParams().put(Approval.SEND_NOTIFICATION, "false");
                wfcall.getRequestParams().put(Approval.REASON, newUser.getReason());
                wfcall.getRequestParams().put(Approval.IMMEDIATE_ACTION, "true");
            }

            ExecuteWorkflow exec = new ExecuteWorkflow();

            try {
                exec.execute(wfcall, GlobalEntries.getGlobalEntries().getConfigManager());
            } catch (Exception e) {
                throw new ProvisioningException("Could not complete registration", e);
            }

            SubmitResponse res = new SubmitResponse();
            res.setAddNewUsers(userData.getAuthLevel() != 0);
            ScaleJSUtils.addCacheHeaders(response);
            response.getWriter().print(gson.toJson(res));
            response.getWriter().flush();

        } else {
            response.setStatus(500);
            ScaleJSUtils.addCacheHeaders(response);
            response.getWriter().print(gson.toJson(errors).trim());
            response.getWriter().flush();
        }

    } else {
        response.setStatus(500);
        ScaleJSUtils.addCacheHeaders(response);
        ScaleError error = new ScaleError();
        error.getErrors().add("Operation not supported");
        response.getWriter().print(gson.toJson(error).trim());
        response.getWriter().flush();
    }

}

From source file:mx.openpay.client.core.impl.DefaultHttpServiceClient.java

protected CloseableHttpClient initHttpClient(final boolean requirePoolManager, final int connectionTimeout,
        final int socketTimeout) {
    CloseableHttpClient httpClient;//from   w  w w  . jav a 2  s. co m
    HttpClientConnectionManager manager;

    SSLConnectionSocketFactory sslSocketFactory;
    SSLContext tlsContext;
    try {
        try {
            tlsContext = new SSLContextBuilder().useProtocol("TLSv1.2").build();
        } catch (GeneralSecurityException e) {
            log.warn("Could not force protocol TLSv1.2: {}", e.getMessage());
            tlsContext = new SSLContextBuilder().build();
        }
        sslSocketFactory = new SSLConnectionSocketFactory(tlsContext);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    if (requirePoolManager) {
        manager = new PoolingHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslSocketFactory).build());
    } else {
        manager = new BasicHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslSocketFactory).build());
    }

    this.requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeout)
            .setSocketTimeout(socketTimeout).build();
    ConnectionConfig connnectionConfig = ConnectionConfig.custom().setCharset(Charset.forName("UTF-8")).build();
    httpClient = HttpClientBuilder.create().setConnectionManager(manager)
            .setDefaultConnectionConfig(connnectionConfig).setDefaultRequestConfig(this.requestConfig).build();
    return httpClient;
}