Example usage for org.apache.http.impl.client CloseableHttpClient getConnectionManager

List of usage examples for org.apache.http.impl.client CloseableHttpClient getConnectionManager

Introduction

In this page you can find the example usage for org.apache.http.impl.client CloseableHttpClient getConnectionManager.

Prototype

@Deprecated
ClientConnectionManager getConnectionManager();

Source Link

Document

Obtains the connection manager used by this client.

Usage

From source file:simauthenticator.SimAuthenticator.java

/**
 * @param args the command line arguments
 *//*  w  ww.  ja v  a 2  s.c o  m*/
public static void main(String[] args) throws Exception {

    cliOpts = new Options();
    cliOpts.addOption("U", "url", true, "Connection URL");
    cliOpts.addOption("u", "user", true, "User name");
    cliOpts.addOption("p", "password", true, "User password");
    cliOpts.addOption("d", "domain", true, "Domain name");
    cliOpts.addOption("v", "verbose", false, "Verbose output");
    cliOpts.addOption("k", "keystore", true, "KeyStore path");
    cliOpts.addOption("K", "keystorepass", true, "KeyStore password");
    cliOpts.addOption("h", "help", false, "Print help info");

    CommandLineParser clip = new GnuParser();
    cmd = clip.parse(cliOpts, args);

    if (cmd.hasOption("help")) {
        help();
        return;
    } else {
        boolean valid = init(args);
        if (!valid) {
            return;
        }
    }

    HttpClientContext clientContext = HttpClientContext.create();

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    char[] keystorePassword = passwk.toCharArray();
    FileInputStream kfis = null;
    try {
        kfis = new FileInputStream(keyStorePath);
        ks.load(kfis, keystorePassword);
    } finally {
        if (kfis != null) {
            kfis.close();
        }
    }

    SSLContext sslContext = SSLContexts.custom().useSSL().loadTrustMaterial(ks).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setSslcontext(sslContext)
            .setSSLSocketFactory(sslsf).setUserAgent(userAgent);
    ;

    cookieStore = new BasicCookieStore();
    /* BasicClientCookie cookie = new BasicClientCookie("SIM authenticator", "Utility for getting event details");
     cookie.setVersion(0);
     cookie.setDomain(".astelit.ukr");
     cookie.setPath("/");
     cookieStore.addCookie(cookie);*/

    CloseableHttpClient client = httpClientBuilder.build();

    try {

        NTCredentials creds = new NTCredentials(usern, passwu, InetAddress.getLocalHost().getHostName(),
                domain);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, creds);
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        context.setCookieStore(cookieStore);
        HttpGet httpget = new HttpGet(eventUrl);
        if (verbose) {
            System.out.println("executing request " + httpget.getRequestLine());
        }
        HttpResponse response = client.execute(httpget, context);
        HttpEntity entity = response.getEntity();

        HttpPost httppost = new HttpPost(eventUrl);
        List<Cookie> cookies = cookieStore.getCookies();

        if (verbose) {
            System.out.println("----------------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.print("Initial set of cookies: ");
            if (cookies.isEmpty()) {
                System.out.println("none");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        }

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("usernameInput", usern));
        nvps.add(new BasicNameValuePair("passwordInput", passwu));
        nvps.add(new BasicNameValuePair("domainInput", domain));
        //nvps.add(new BasicNameValuePair("j_username", domain + "\\" + usern));
        //nvps.add(new BasicNameValuePair("j_password", ipAddr + ";" + passwu));
        if (entity != null && verbose) {
            System.out.println("Responce content length: " + entity.getContentLength());

        }

        //System.out.println(EntityUtils.toString(entity));

        httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        HttpResponse afterPostResponse = client.execute(httppost, context);
        HttpEntity afterPostEntity = afterPostResponse.getEntity();
        cookies = cookieStore.getCookies();
        if (entity != null && verbose) {
            System.out.println("----------------------------------------------");
            System.out.println(afterPostResponse.getStatusLine());
            System.out.println("Responce content length: " + afterPostEntity.getContentLength());
            System.out.print("After POST set of cookies: ");
            if (cookies.isEmpty()) {
                System.out.println("none");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        }

        System.out.println(EntityUtils.toString(afterPostEntity));
        EntityUtils.consume(entity);
        EntityUtils.consume(afterPostEntity);

    } finally {

        client.getConnectionManager().shutdown();
    }

}

From source file:utils.TestUtils.java

@SuppressWarnings("deprecation") // http api
public static CloseableHttpClient createHttpsClient() {
    try {/*from  w ww .ja  v  a2s . co  m*/
        TrustManager[] trustAllCerts = new TrustManager[] { new NonValidatingX509TrustManager() };
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[] {}, trustAllCerts, null);
        SSLSocketFactory socketFactory = new SSLSocketFactory(ctx,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sch = new Scheme("https", 443, socketFactory);
        CloseableHttpClient http = new DefaultHttpClient();
        http.getConnectionManager().getSchemeRegistry().register(sch);
        return http;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.solr.client.solrj.impl.HttpClientUtilTest.java

@Test
@SuppressWarnings("deprecation")
public void testSSLSystemProperties() throws IOException {
    CloseableHttpClient client = HttpClientUtil.createClient(null);
    try {//from ww w.  jav a2s. c  om
        SSLTestConfig.setSSLSystemProperties();
        assertNotNull("HTTPS scheme could not be created using the javax.net.ssl.* system properties.",
                client.getConnectionManager().getSchemeRegistry().get("https"));

        System.clearProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME);
        client.close();
        client = HttpClientUtil.createClient(null);
        assertEquals(BrowserCompatHostnameVerifier.class, getHostnameVerifier(client).getClass());

        System.setProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME, "true");
        client.close();
        client = HttpClientUtil.createClient(null);
        assertEquals(BrowserCompatHostnameVerifier.class, getHostnameVerifier(client).getClass());

        System.setProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME, "");
        client.close();
        client = HttpClientUtil.createClient(null);
        assertEquals(BrowserCompatHostnameVerifier.class, getHostnameVerifier(client).getClass());

        System.setProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME, "false");
        client.close();
        client = HttpClientUtil.createClient(null);
        assertEquals(AllowAllHostnameVerifier.class, getHostnameVerifier(client).getClass());
    } finally {
        SSLTestConfig.clearSSLSystemProperties();
        System.clearProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME);
        client.close();
    }
}

From source file:com.releasequeue.server.ReleaseQueueServer.java

private void deleteRequest(URL url) throws IOException {
    HttpDelete request = new HttpDelete(url.toString());
    setAuthHeader(request);//from  w  w w.j  a  va  2s.  c o  m

    CloseableHttpClient httpClient = HttpClients.createDefault();

    try {
        HttpResponse response = httpClient.execute(request);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode >= 400) {
            throw new HttpException(statusLine.getReasonPhrase());
        }
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.releasequeue.server.ReleaseQueueServer.java

private Object getJsonRequest(URL url) throws IOException, HttpException {
    HttpGet request = new HttpGet(url.toString());
    setAuthHeader(request);/*from   w ww  .j  a  va2  s. c  om*/

    CloseableHttpClient httpClient = HttpClients.createDefault();

    try {
        HttpResponse response = httpClient.execute(request);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode >= 400) {
            throw new HttpException(statusLine.getReasonPhrase());
        }

        String json_string = EntityUtils.toString(response.getEntity());
        JSONParser parser = new JSONParser();
        return parser.parse(json_string);
    } catch (ParseException pe) {
        throw new RuntimeException("Failed to parse json responce", pe);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:com.releasequeue.server.ReleaseQueueServer.java

private Object postJsonRequest(URL url, JSONObject payload) throws IOException {
    HttpPost request = new HttpPost(url.toString());
    setAuthHeader(request);//from www.j  av a2  s . c  o  m

    CloseableHttpClient httpClient = HttpClients.createDefault();

    try {
        StringWriter data = new StringWriter();
        payload.writeJSONString(data);

        StringEntity params = new StringEntity(data.toString());
        request.addHeader("content-type", "application/json");
        request.setEntity(params);

        HttpResponse response = httpClient.execute(request);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode >= 400) {
            throw new HttpException(statusLine.getReasonPhrase());
        }

        String json_string = EntityUtils.toString(response.getEntity());
        JSONParser parser = new JSONParser();

        return parser.parse(json_string);
    } catch (ParseException pe) {
        throw new RuntimeException("Failed to parse json responce", pe);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

}

From source file:org.jenkinsci.plugins.GithubSecurityRealm.java

/**
 * This is where the user comes back to at the end of the OpenID redirect
 * ping-pong./*  w  ww.j a  va  2 s.  c  o  m*/
 */
public HttpResponse doFinishLogin(StaplerRequest request) throws IOException {
    String code = request.getParameter("code");

    if (code == null || code.trim().length() == 0) {
        Log.info("doFinishLogin: missing code.");
        return HttpResponses.redirectToContextRoot();
    }

    Log.info("test");

    HttpPost httpost = new HttpPost(githubWebUri + "/login/oauth/access_token?" + "client_id=" + clientID + "&"
            + "client_secret=" + clientSecret + "&" + "code=" + code);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpHost proxy = getProxy(httpost);
    if (proxy != null) {
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    org.apache.http.HttpResponse response = httpclient.execute(httpost);

    HttpEntity entity = response.getEntity();

    String content = EntityUtils.toString(entity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();

    String accessToken = extractToken(content);

    if (accessToken != null && accessToken.trim().length() > 0) {
        // only set the access token if it exists.
        GithubAuthenticationToken auth = new GithubAuthenticationToken(accessToken, getGithubApiUri());
        SecurityContextHolder.getContext().setAuthentication(auth);

        GHMyself self = auth.getMyself();
        User u = User.current();
        u.setFullName(self.getName());
        // Set email from github only if empty
        if (!u.getProperty(Mailer.UserProperty.class).hasExplicitlyConfiguredAddress()) {
            if (hasScope("user") || hasScope("user:email")) {
                String primary_email = null;
                for (GHEmail e : self.getEmails2()) {
                    if (e.isPrimary()) {
                        primary_email = e.getEmail();
                    }
                }
                if (primary_email != null) {
                    u.addProperty(new Mailer.UserProperty(primary_email));
                }
            } else {
                u.addProperty(new Mailer.UserProperty(auth.getGitHub().getMyself().getEmail()));
            }
        }

        fireAuthenticated(new GithubOAuthUserDetails(self, auth.getAuthorities()));
    } else {
        Log.info("Github did not return an access token.");
    }

    String referer = (String) request.getSession().getAttribute(REFERER_ATTRIBUTE);
    if (referer != null)
        return HttpResponses.redirectTo(referer);
    return HttpResponses.redirectToContextRoot(); // referer should be always there, but be defensive
}

From source file:portal.api.osm.client.OSMClient.java

public void createOnBoardNSDPackage(String packageURL, String packageID) {

    System.out.println("Sending HTTPS createOnBoardPackage towards: " + BASE_OPERATIONS_URL);

    CloseableHttpClient httpclient = returnHttpClient();
    HttpPost httppost = new HttpPost(BASE_OPERATIONS_URL + "/package-create");
    BasicHeader bh = new BasicHeader("Accept", "application/vnd.yang.collection+json");
    httppost.addHeader(bh);/*from   ww w  .ja  v  a  2  s  .c o m*/

    BasicHeader bh2 = new BasicHeader("Authorization",
            "Basic " + this.manoProvider.getAuthorizationBasicHeader()); // this is hardcoded admin/admin
    httppost.addHeader(bh2);
    BasicHeader bh3 = new BasicHeader("Content-Type", "application/vnd.yang.data+json");
    httppost.addHeader(bh3);

    HttpResponse response;
    try {
        StringEntity params = new StringEntity("{" + "\"input\":{" + "\"external-url\": \"" + packageURL + "\","
                + "\"package-type\":\"NSD\"," + "\"package-id\":\"" + packageID + "\"" + "}" + "}");
        httppost.setEntity(params);

        response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream inStream = (InputStream) entity.getContent();
        String s = IOUtils.toString(inStream);
        System.out.println("response = " + s);
        httpclient.getConnectionManager().shutdown();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}