Example usage for org.apache.http.client.protocol HttpClientContext create

List of usage examples for org.apache.http.client.protocol HttpClientContext create

Introduction

In this page you can find the example usage for org.apache.http.client.protocol HttpClientContext create.

Prototype

public static HttpClientContext create() 

Source Link

Usage

From source file:org.keycloak.testsuite.adapter.servlet.AbstractSAMLServletsAdapterTest.java

@Test
public void testEmptyKeyInfoElement() {
    samlidpInitiatedLoginPage.setAuthRealm(SAMLSERVLETDEMO);
    samlidpInitiatedLoginPage.setUrlName("sales-post-sig-email");
    System.out.println(samlidpInitiatedLoginPage.toString());
    URI idpInitiatedLoginPage = URI.create(samlidpInitiatedLoginPage.toString());

    log.debug("Log in using idp initiated login");
    SAMLDocumentHolder documentHolder = idpInitiatedLogin(bburkeUser, idpInitiatedLoginPage,
            SamlClient.Binding.POST);

    log.debug("Removing KeyInfo from Keycloak response");
    Document responseDoc = documentHolder.getSamlDocument();
    IOUtil.removeElementFromDoc(responseDoc, "samlp:Response/dsig:Signature/dsig:KeyInfo");

    CloseableHttpResponse response = null;
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        HttpClientContext context = HttpClientContext.create();

        log.debug("Sending response to SP");
        HttpUriRequest post = SamlClient.Binding.POST.createSamlUnsignedResponse(
                getAppServerSamlEndpoint(salesPostSigEmailServletPage), null, responseDoc);
        response = client.execute(post, context);
        System.out.println(EntityUtils.toString(response.getEntity()));
        assertThat(response, statusCodeIsHC(Response.Status.FOUND));
        response.close();/*w ww .j a v a  2  s. c  om*/

        HttpGet get = new HttpGet(salesPostSigEmailServletPage.toString());
        response = client.execute(get);
        assertThat(response, statusCodeIsHC(Response.Status.OK));
        assertThat(response, bodyHC(containsString("principal=bburke")));
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
            try {
                response.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

/**
 * Http Post Request.//from  w w  w .  j  a v a  2 s  .  c om
 *
 * @param url         Target URL to POST to.
 * @param body        Body to be sent with the post.
 * @param credentials Credentials to use for basic auth.
 * @return Body of post returned.
 * @throws Exception
 */
String httpPost(String url, String body, UsernamePasswordCredentials credentials) throws Exception {
    logger.debug(format("httpPost %s, body:%s", url, body));

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    CredentialsProvider provider = null;
    if (credentials != null) {
        provider = new BasicCredentialsProvider();

        provider.setCredentials(AuthScope.ANY, credentials);
        httpClientBuilder.setDefaultCredentialsProvider(provider);
    }

    if (registry != null) {

        httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(registry));

    }

    HttpClient client = httpClientBuilder.build();

    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(getRequestConfig());

    AuthCache authCache = new BasicAuthCache();

    HttpHost targetHost = new HttpHost(httpPost.getURI().getHost(), httpPost.getURI().getPort());

    if (credentials != null) {
        authCache.put(targetHost, new

        BasicScheme());

    }

    final HttpClientContext context = HttpClientContext.create();

    if (null != provider) {
        context.setCredentialsProvider(provider);
    }

    if (credentials != null) {
        context.setAuthCache(authCache);
    }

    httpPost.setEntity(new StringEntity(body));
    if (credentials != null) {
        httpPost.addHeader(new

        BasicScheme().

                authenticate(credentials, httpPost, context));
    }

    HttpResponse response = client.execute(httpPost, context);
    int status = response.getStatusLine().getStatusCode();

    HttpEntity entity = response.getEntity();
    logger.trace(format("httpPost %s  sending...", url));
    String responseBody = entity != null ? EntityUtils.toString(entity) : null;
    logger.trace(format("httpPost %s  responseBody %s", url, responseBody));

    if (status >= 400) {

        Exception e = new Exception(format(
                "POST request to %s  with request body: %s, " + "failed with status code: %d. Response: %s",
                url, body, status, responseBody));
        logger.error(e.getMessage());
        throw e;
    }
    logger.debug(format("httpPost Status: %d returning: %s ", status, responseBody));

    return responseBody;
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

JsonObject post(String url, String body, String authHTTPCert) throws Exception {
    url = addCAToURL(url);//  w w w. ja  va2 s . co  m
    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(getRequestConfig());
    logger.debug(format("httpPost %s, body:%s, authHTTPCert: %s", url, body, authHTTPCert));

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    if (registry != null) {
        httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(registry));
    }
    HttpClient client = httpClientBuilder.build();

    final HttpClientContext context = HttpClientContext.create();
    httpPost.setEntity(new StringEntity(body));
    httpPost.addHeader("Authorization", authHTTPCert);

    HttpResponse response = client.execute(httpPost, context);

    return getResult(response, body, "POST");
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

JsonObject httpGet(String url, User registrar, Map<String, String> queryMap) throws Exception {
    String getURL = getURL(url, queryMap);
    String authHTTPCert = getHTTPAuthCertificate(registrar.getEnrollment(), "GET", getURL, "");
    HttpGet httpGet = new HttpGet(getURL);
    httpGet.setConfig(getRequestConfig());
    logger.debug(format("httpGet %s, authHTTPCert: %s", url, authHTTPCert));

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    if (registry != null) {
        httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(registry));
    }//w w w.  j a v  a  2  s  .  c  o m
    HttpClient client = httpClientBuilder.build();

    final HttpClientContext context = HttpClientContext.create();
    httpGet.addHeader("Authorization", authHTTPCert);

    HttpResponse response = client.execute(httpGet, context);

    return getResult(response, "", "GET");
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

JsonObject httpPut(String url, String body, User registrar) throws Exception {
    String authHTTPCert = getHTTPAuthCertificate(registrar.getEnrollment(), "PUT", url, body);
    String putURL = addCAToURL(url);
    HttpPut httpPut = new HttpPut(putURL);
    httpPut.setConfig(getRequestConfig());
    logger.debug(format("httpPutt %s, body:%s, authHTTPCert: %s", url, body, authHTTPCert));

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    if (registry != null) {
        httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(registry));
    }/*from w  w  w. j  a va 2s.  com*/
    HttpClient client = httpClientBuilder.build();

    final HttpClientContext context = HttpClientContext.create();
    httpPut.setEntity(new StringEntity(body));
    httpPut.addHeader("Authorization", authHTTPCert);

    HttpResponse response = client.execute(httpPut, context);

    return getResult(response, body, "PUT");
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

JsonObject httpDelete(String url, User registrar) throws Exception {
    String authHTTPCert = getHTTPAuthCertificate(registrar.getEnrollment(), "DELETE", url, "");
    String deleteURL = addCAToURL(url);
    HttpDelete httpDelete = new HttpDelete(deleteURL);
    httpDelete.setConfig(getRequestConfig());
    logger.debug(format("httpPut %s, authHTTPCert: %s", url, authHTTPCert));

    final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    if (registry != null) {
        httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(registry));
    }/*from  w w  w  . jav  a2  s . c o  m*/
    HttpClient client = httpClientBuilder.build();

    final HttpClientContext context = HttpClientContext.create();
    httpDelete.addHeader("Authorization", authHTTPCert);

    HttpResponse response = client.execute(httpDelete, context);

    return getResult(response, "", "DELETE");
}

From source file:com.adobe.aem.demo.communities.Loader.java

private static String doPost(String hostname, String port, String url, String user, String password,
        HttpEntity entity, String lookup, String referer) {

    String jsonElement = null;//from w w w  .ja  va2  s . c  o m

    try {

        HttpHost target = new HttpHost(hostname, Integer.parseInt(port), "http");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(user, password));
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .build();

        try {

            // Adding the Basic Authentication data to the context for this command
            AuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(target, basicAuth);
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authCache);

            // Composing the root URL for all subsequent requests
            String postUrl = "http://" + hostname + ":" + port + url;
            logger.debug("Posting request as " + user + " with password " + password + " to " + postUrl);

            // Preparing a standard POST HTTP command
            HttpPost request = new HttpPost(postUrl);
            request.setEntity(entity);
            if (!entity.getContentType().toString().contains("multipart")) {
                request.addHeader("content-type", "application/x-www-form-urlencoded");
            }
            request.addHeader("Accept", "application/json, text/javascript, */*; q=0.01");
            request.addHeader("Origin", postUrl);
            if (referer != null) {
                logger.debug("Referer header added to request: " + referer);
                request.addHeader("Referer", referer);
            }

            // Sending the HTTP POST command
            CloseableHttpResponse response = httpClient.execute(target, request, localContext);
            try {
                String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
                logger.debug("Got POST response:" + responseString);
                if (lookup != null) {
                    logger.debug("JSON lookup value: " + lookup);
                    int separatorIndex = lookup.indexOf("/");
                    if (separatorIndex > 0) {

                        // Grabbing element in a nested element
                        Object object = new JSONObject(responseString).get(lookup.substring(0, separatorIndex));
                        if (object != null) {

                            if (object instanceof JSONArray) {

                                logger.debug("JSON object is a JSONArray");
                                JSONArray jsonArray = (JSONArray) object;
                                if (jsonArray.length() == 1) {
                                    JSONObject jsonObject = jsonArray.getJSONObject(0);
                                    jsonElement = jsonObject.getString(lookup.substring(1 + separatorIndex));
                                    logger.debug("JSON value (jsonArray) returned is " + jsonElement);
                                }

                            } else if (object instanceof JSONObject) {

                                logger.debug("JSON object is a JSONObject");
                                JSONObject jsonobject = (JSONObject) object;
                                jsonElement = jsonobject.getString(lookup.substring(1 + separatorIndex));
                                logger.debug("JSON value (jsonObject) returned is " + jsonElement);

                            }
                        }

                    } else {
                        // Grabbing element at the top of the JSON response
                        jsonElement = new JSONObject(responseString).getString(lookup);
                        logger.debug("JSON (top) value returned is " + jsonElement);

                    }
                }

            } catch (Exception ex) {
                logger.error(ex.getMessage());
            } finally {
                response.close();
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage());
        } finally {
            httpClient.close();
        }

    } catch (IOException e) {
        logger.error(e.getMessage());
    }

    return jsonElement;

}

From source file:org.opentravel.schemacompiler.repository.impl.RemoteRepositoryClient.java

/**
 * Configures the 'Authorization' header on the given HTTP request using the current user ID and
 * encrypted password that is configured for this repository.
 *///  w  w  w  .ja va2  s .co  m
private HttpClientContext createHttpContext() {
    HttpClientContext context = HttpClientContext.create();

    if ((userId != null) && (encryptedPassword != null)) {
        AuthState target = new AuthState();
        target.update(new BasicScheme(),
                new UsernamePasswordCredentials(userId, PasswordHelper.decrypt(encryptedPassword)));
        context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, target);
    }
    return context;
}

From source file:com.adobe.aem.demo.communities.Loader.java

private static void doDelete(String hostname, String port, String url, String user, String password) {

    try {/*  w  w w  .j a  va  2  s . com*/

        HttpHost target = new HttpHost(hostname, Integer.parseInt(port), "http");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(user, password));
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .build();

        try {

            // Adding the Basic Authentication data to the context for this command
            AuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(target, basicAuth);
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authCache);

            // Composing the root URL for all subsequent requests
            String postUrl = "http://" + hostname + ":" + port + url;
            logger.debug("Deleting request as " + user + " with password " + password + " to " + postUrl);
            HttpDelete request = new HttpDelete(postUrl);
            httpClient.execute(target, request, localContext);

        } catch (Exception ex) {
            logger.error(ex.getMessage());
        } finally {
            httpClient.close();
        }

    } catch (IOException e) {
        logger.error(e.getMessage());
    }

}

From source file:com.adobe.aem.demo.communities.Loader.java

private static String doGet(String hostname, String port, String url, String user, String password,
        List<NameValuePair> params) {

    String rawResponse = null;//from  w w  w . java2  s. c o  m

    try {

        HttpHost target = new HttpHost(hostname, Integer.parseInt(port), "http");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(user, password));
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .build();

        try {

            // Adding the Basic Authentication data to the context for this command
            AuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(target, basicAuth);
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authCache);

            // Composing the root URL for all subsequent requests
            URIBuilder uribuilder = new URIBuilder();
            uribuilder.setScheme("http").setHost(hostname).setPort(Integer.parseInt(port)).setPath(url);

            // Adding the params
            if (params != null)
                for (NameValuePair nvp : params) {
                    uribuilder.setParameter(nvp.getName(), nvp.getValue());
                }

            URI uri = uribuilder.build();
            logger.debug("URI built as " + uri.toString());
            HttpGet httpget = new HttpGet(uri);
            CloseableHttpResponse response = httpClient.execute(httpget, localContext);
            try {
                rawResponse = EntityUtils.toString(response.getEntity(), "UTF-8");
            } catch (Exception ex) {
                logger.error(ex.getMessage());
            } finally {
                response.close();
            }

        } catch (Exception ex) {
            logger.error(ex.getMessage());
        } finally {
            httpClient.close();
        }

    } catch (IOException e) {

        e.printStackTrace();
    }

    return rawResponse;

}