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.SAMLServletAdapterTest.java

@Test
public void testEmptyKeyInfoElement() {
    log.debug("Log in using idp initiated login");
    SAMLDocumentHolder documentHolder = new SamlClientBuilder()
            .idpInitiatedLogin(getAuthServerSamlEndpoint(SAMLSERVLETDEMO), "sales-post-sig-email").build()
            .login().user(bburkeUser).build().getSamlResponse(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()));
        Assert.assertThat(response, statusCodeIsHC(Response.Status.FOUND));
        response.close();//  ww  w  . j  a v  a  2 s .c  o m

        HttpGet get = new HttpGet(salesPostSigEmailServletPage.toString());
        response = client.execute(get);
        Assert.assertThat(response, statusCodeIsHC(Response.Status.OK));
        Assert.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:net.www_eee.portal.channels.ProxyChannel.java

/**
 * {@linkplain #createProxyClient(Page.Request) Create} an {@link HttpClient} and use it to
 * {@linkplain HttpClient#execute(HttpUriRequest, HttpContext) execute} a
 * {@linkplain #createProxyRequest(Page.Request, Channel.Mode, CloseableHttpClient) proxy request} to retrieve the
 * content to be returned/rendered in response to the supplied <code>pageRequest</code>.
 * /*from   ww  w.  jav  a 2s  .  c o m*/
 * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed.
 * @param mode The {@link net.www_eee.portal.Channel.Mode Mode} of the request.
 * @return An {@link HttpClientContext} containing the {@linkplain ExecutionContext#HTTP_RESPONSE response} from the
 * proxied server.
 * @throws WWWEEEPortal.Exception If a problem occurred while determining the result.
 * @throws WebApplicationException If a problem occurred while determining the result.
 * @see #PROXY_RESPONSE_HOOK
 */
protected HttpClientContext doProxyRequest(final Page.Request pageRequest, final Mode mode)
        throws WWWEEEPortal.Exception, WebApplicationException {
    final HttpClientContext proxyContext = HttpClientContext.create();
    final CloseableHttpClient proxyClient = createProxyClient(pageRequest);
    proxyContext.setAttribute(HTTP_CLIENT_CONTEXT_ID, proxyClient);

    try {

        CloseableHttpResponse proxyResponse = null;

        while (proxyResponse == null) { // Keep trying again if a plugin filter null's out the previous response.

            final HttpRequestBase proxyRequest = createProxyRequest(pageRequest, mode, proxyClient);
            try {

                final Object[] context = new Object[] { mode, proxyContext, proxyClient, proxyRequest };
                proxyResponse = PROXY_RESPONSE_HOOK.value(plugins, context, pageRequest);

                if (proxyResponse == null) {
                    try {

                        proxyResponse = proxyClient.execute(proxyRequest, proxyContext);

                    } catch (UnknownHostException uhe) {
                        throw new ConfigManager.ConfigException(uhe);
                    } catch (IOException ioe) {
                        throw new WWWEEEPortal.OperationalException(ioe);
                    }
                }

                proxyResponse = PROXY_RESPONSE_HOOK.filter(plugins, context, pageRequest, proxyResponse);

            } catch (WWWEEEPortal.Exception wpe) {
                LogAnnotation.annotate(wpe, "ProxyRequest", proxyRequest, null, false);
                LogAnnotation.annotate(wpe, "ProxyResponse", proxyResponse, null, false);
                LogAnnotation.annotate(wpe, "ProxiedFileURL", proxyRequest.getURI(), null, false);
                throw wpe;
            }

        } // while (proxyResponse == null)

        return validateProxyResponse(proxyContext, pageRequest, mode);

    } catch (WWWEEEPortal.Exception wpe) {
        LogAnnotation.annotate(wpe, "ProxyContext", proxyContext, null, false);
        try {
            LogAnnotation.annotate(wpe, "ProxiedFileURL", HttpUtil.getRequestTargetURL(proxyContext), null,
                    false); // This wouldn't be necessary if any of the previous annotations could actually toString() themselves usefully.
        } catch (Exception e) {
        }
        throw wpe;
    }

}

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

private static int doPost(String hostname, String port, String url, String user, String password,
        HttpEntity entity, Map<String, String> elements, String referer) {
    String jsonElement = null;/*from  w  ww  .  j  a  v a2  s  .c o m*/

    if (hostname == null || port == null || url == null || user == null || password == null) {
        logger.error("Can't POST with requested parameters, one is null");
        return 500;
    }

    int returnCode = 404;

    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 = HttpClientBuilder.create().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 + " 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) {
                request.addHeader("Referer", referer);
            }

            // Sending the HTTP POST command
            CloseableHttpResponse response = httpClient.execute(target, request, localContext);
            try {
                returnCode = response.getStatusLine().getStatusCode();
                String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
                if (returnCode >= 500) {
                    logger.error("POST return code: " + returnCode);
                    logger.debug(responseString);
                    return returnCode;
                }
                if (returnCode >= 400) {
                    logger.warn("POST return code: " + returnCode);
                    logger.debug(responseString);
                    return returnCode;
                }
                if (elements == null)
                    return returnCode;
                Set<String> keys = elements.keySet();
                if (!isJSONValid(responseString) && keys.size() > 0) {
                    logger.warn(
                            "POST operation didn't return a JSON string, hence cannot extract requested value");
                    return returnCode;
                }
                for (String lookup : keys) {
                    if (lookup != null) {
                        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) {

                                    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) {

                                    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);
                        }
                    }
                    elements.put(lookup, 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 returnCode;
}

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

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

    String responseString = null;
    if (hostname == null || port == null || url == null || user == null || password == null) {
        logger.error("Can't POST with requested parameters, one is null");
        return responseString;
    }/*from   w w w. j av a  2 s .  c  om*/

    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 = HttpClientBuilder.create().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;

            // Preparing a standard POST HTTP command
            HttpPost request = new HttpPost(postUrl);

            // Sending the HTTP POST command
            CloseableHttpResponse response = httpClient.execute(target, request, localContext);
            try {
                int returnCode = response.getStatusLine().getStatusCode();
                responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
                if (returnCode >= 500) {
                    logger.fatal("Server error" + responseString);
                }

            } 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 responseString;
}

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

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

    try {//from  w  w  w.  ja  va2 s.c o  m

        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 = HttpClientBuilder.create().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 + " 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.demomachine.communities.Loader.java

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

    String rawResponse = null;/*  w w  w. j  a  v  a  2s .  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 = HttpClientBuilder.create().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("Getting request at " + uri.toString());
            HttpGet httpget = new HttpGet(uri);
            CloseableHttpResponse response = httpClient.execute(httpget, localContext);
            if (response.getStatusLine().getStatusCode() == 200) {
                try {
                    rawResponse = EntityUtils.toString(response.getEntity(), "UTF-8");
                } catch (Exception ex) {
                    logger.error(ex.getMessage());
                } finally {
                    response.close();
                }
            } else {
                logger.debug("GET return code: " + response.getStatusLine().getStatusCode());
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        } finally {
            httpClient.close();
        }

    } catch (IOException e) {

        e.printStackTrace();
    }

    return rawResponse;

}

From source file:org.apache.hadoop.hbase.rest.TestSecureRESTServer.java

private Pair<CloseableHttpClient, HttpClientContext> getClient() {
    HttpClientConnectionManager pool = new PoolingHttpClientConnectionManager();
    HttpHost host = new HttpHost("localhost", REST_TEST.getServletPort());
    Registry<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build();
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, EmptyCredentials.INSTANCE);
    AuthCache authCache = new BasicAuthCache();

    CloseableHttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry)
            .setConnectionManager(pool).build();

    HttpClientContext context = HttpClientContext.create();
    context.setTargetHost(host);//www . j ava 2s.com
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthSchemeRegistry(authRegistry);
    context.setAuthCache(authCache);

    return new Pair<>(client, context);
}

From source file:org.apache.http.impl.client.cache.CachingExec.java

public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request)
        throws IOException, HttpException {
    return execute(route, request, HttpClientContext.create(), null);
}

From source file:org.apache.http.impl.conn.TestPoolingHttpClientConnectionManager.java

@Test
public void testTargetConnect() throws Exception {
    final HttpHost target = new HttpHost("somehost", -1, "https");
    final InetAddress remote = InetAddress.getByAddress(new byte[] { 10, 0, 0, 1 });
    final InetAddress local = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 });
    final HttpRoute route = new HttpRoute(target, local, true);

    final CPoolEntry entry = new CPoolEntry(LogFactory.getLog(getClass()), "id", route, conn, -1,
            TimeUnit.MILLISECONDS);
    entry.markRouteComplete();/* w  ww.  j  a v  a 2 s  . c  om*/
    Mockito.when(future.isCancelled()).thenReturn(Boolean.FALSE);
    Mockito.when(conn.isOpen()).thenReturn(true);
    Mockito.when(future.isCancelled()).thenReturn(false);
    Mockito.when(future.get(1, TimeUnit.SECONDS)).thenReturn(entry);
    Mockito.when(pool.lease(route, null, null)).thenReturn(future);

    final ConnectionRequest connRequest1 = mgr.requestConnection(route, null);
    final HttpClientConnection conn1 = connRequest1.get(1, TimeUnit.SECONDS);
    Assert.assertNotNull(conn1);

    final HttpClientContext context = HttpClientContext.create();
    final SocketConfig sconfig = SocketConfig.custom().build();

    mgr.setDefaultSocketConfig(sconfig);

    Mockito.when(dnsResolver.resolve("somehost")).thenReturn(new InetAddress[] { remote });
    Mockito.when(schemePortResolver.resolve(target)).thenReturn(8443);
    Mockito.when(socketFactoryRegistry.lookup("https")).thenReturn(plainSocketFactory);
    Mockito.when(plainSocketFactory.createSocket(Mockito.<HttpContext>any())).thenReturn(socket);
    Mockito.when(plainSocketFactory.connectSocket(Mockito.anyInt(), Mockito.eq(socket), Mockito.<HttpHost>any(),
            Mockito.<InetSocketAddress>any(), Mockito.<InetSocketAddress>any(), Mockito.<HttpContext>any()))
            .thenReturn(socket);

    mgr.connect(conn1, route, 123, context);

    Mockito.verify(dnsResolver, Mockito.times(1)).resolve("somehost");
    Mockito.verify(schemePortResolver, Mockito.times(1)).resolve(target);
    Mockito.verify(plainSocketFactory, Mockito.times(1)).createSocket(context);
    Mockito.verify(plainSocketFactory, Mockito.times(1)).connectSocket(123, socket, target,
            new InetSocketAddress(remote, 8443), new InetSocketAddress(local, 0), context);

    mgr.routeComplete(conn1, route, context);
}

From source file:org.apache.http.impl.conn.TestPoolingHttpClientConnectionManager.java

@Test
public void testProxyConnectAndUpgrade() throws Exception {
    final HttpHost target = new HttpHost("somehost", -1, "https");
    final HttpHost proxy = new HttpHost("someproxy", 8080);
    final InetAddress remote = InetAddress.getByAddress(new byte[] { 10, 0, 0, 1 });
    final InetAddress local = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 });
    final HttpRoute route = new HttpRoute(target, local, proxy, true);

    final CPoolEntry entry = new CPoolEntry(LogFactory.getLog(getClass()), "id", route, conn, -1,
            TimeUnit.MILLISECONDS);
    entry.markRouteComplete();// www.j  av a  2 s .c  o  m
    Mockito.when(future.isCancelled()).thenReturn(Boolean.FALSE);
    Mockito.when(conn.isOpen()).thenReturn(true);
    Mockito.when(future.isCancelled()).thenReturn(false);
    Mockito.when(future.get(1, TimeUnit.SECONDS)).thenReturn(entry);
    Mockito.when(pool.lease(route, null, null)).thenReturn(future);

    final ConnectionRequest connRequest1 = mgr.requestConnection(route, null);
    final HttpClientConnection conn1 = connRequest1.get(1, TimeUnit.SECONDS);
    Assert.assertNotNull(conn1);

    final ConnectionSocketFactory plainsf = Mockito.mock(ConnectionSocketFactory.class);
    final LayeredConnectionSocketFactory sslsf = Mockito.mock(LayeredConnectionSocketFactory.class);
    final Socket socket = Mockito.mock(Socket.class);
    final HttpClientContext context = HttpClientContext.create();
    final SocketConfig sconfig = SocketConfig.custom().build();
    final ConnectionConfig cconfig = ConnectionConfig.custom().build();

    mgr.setDefaultSocketConfig(sconfig);
    mgr.setDefaultConnectionConfig(cconfig);

    Mockito.when(dnsResolver.resolve("someproxy")).thenReturn(new InetAddress[] { remote });
    Mockito.when(schemePortResolver.resolve(proxy)).thenReturn(8080);
    Mockito.when(schemePortResolver.resolve(target)).thenReturn(8443);
    Mockito.when(socketFactoryRegistry.lookup("http")).thenReturn(plainsf);
    Mockito.when(socketFactoryRegistry.lookup("https")).thenReturn(sslsf);
    Mockito.when(plainsf.createSocket(Mockito.<HttpContext>any())).thenReturn(socket);
    Mockito.when(plainsf.connectSocket(Mockito.anyInt(), Mockito.eq(socket), Mockito.<HttpHost>any(),
            Mockito.<InetSocketAddress>any(), Mockito.<InetSocketAddress>any(), Mockito.<HttpContext>any()))
            .thenReturn(socket);

    mgr.connect(conn1, route, 123, context);

    Mockito.verify(dnsResolver, Mockito.times(1)).resolve("someproxy");
    Mockito.verify(schemePortResolver, Mockito.times(1)).resolve(proxy);
    Mockito.verify(plainsf, Mockito.times(1)).createSocket(context);
    Mockito.verify(plainsf, Mockito.times(1)).connectSocket(123, socket, proxy,
            new InetSocketAddress(remote, 8080), new InetSocketAddress(local, 0), context);

    Mockito.when(conn.getSocket()).thenReturn(socket);

    mgr.upgrade(conn1, route, context);

    Mockito.verify(schemePortResolver, Mockito.times(1)).resolve(target);
    Mockito.verify(sslsf, Mockito.times(1)).createLayeredSocket(socket, "somehost", 8443, context);

    mgr.routeComplete(conn1, route, context);
}