Search in sources :

Example 91 with CloseableHttpClient

use of org.apache.http.impl.client.CloseableHttpClient in project wildfly by wildfly.

the class CookieUnitTestCase method testCookieSetCorrectly.

@Test
public void testCookieSetCorrectly() throws Exception {
    log.debug("testCookieSetCorrectly()");
    try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
        HttpResponse response = httpclient.execute(new HttpGet(cookieReadURL.toURI() + "CookieReadServlet"));
        if (response.getEntity() != null) {
            response.getEntity().getContent().close();
        }
        log.debug("Sending request with cookie");
        response = httpclient.execute(new HttpPost(cookieReadURL.toURI() + "CookieReadServlet"));
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) Test(org.junit.Test)

Example 92 with CloseableHttpClient

use of org.apache.http.impl.client.CloseableHttpClient in project wildfly by wildfly.

the class Utils method makeCallWithKerberosAuthn.

/**
     * Returns response body for the given URL request as a String. It also checks if the returned HTTP status code is the
     * expected one. If the server returns {@link HttpServletResponse#SC_UNAUTHORIZED} and an username is provided, then the
     * given user is authenticated against Kerberos and a new request is executed under the new subject.
     *
     * @param uri URI to which the request should be made
     * @param user Username
     * @param pass Password
     * @param expectedStatusCode expected status code returned from the requested server
     * @return HTTP response body
     * @throws IOException
     * @throws URISyntaxException
     * @throws PrivilegedActionException
     * @throws LoginException
     */
public static String makeCallWithKerberosAuthn(final URI uri, final String user, final String pass, final int expectedStatusCode) throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
    LOGGER.trace("Requesting URI: " + uri);
    Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new JBossNegotiateSchemeFactory(true)).build();
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullHCCredentials());
    final Krb5LoginConfiguration krb5Configuration = new Krb5LoginConfiguration(getLoginConfiguration());
    try (final CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credentialsProvider).build()) {
        final HttpGet httpGet = new HttpGet(uri);
        final HttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
            assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
            return EntityUtils.toString(response.getEntity());
        }
        final HttpEntity entity = response.getEntity();
        final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
        assertTrue("WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
        final Set<String> authnHeaderValues = new HashSet<String>();
        for (final Header header : authnHeaders) {
            authnHeaderValues.add(header.getValue());
        }
        assertTrue("WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
        }
        if (entity != null)
            EntityUtils.consume(entity);
        // Use our custom configuration to avoid reliance on external config
        Configuration.setConfiguration(krb5Configuration);
        // 1. Authenticate to Kerberos.
        final LoginContext lc = loginWithKerberos(krb5Configuration, user, pass);
        // 2. Perform the work as authenticated Subject.
        final String responseBody = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<String>() {

            public String run() throws Exception {
                final HttpResponse response = httpClient.execute(httpGet);
                int statusCode = response.getStatusLine().getStatusCode();
                assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode);
                return EntityUtils.toString(response.getEntity());
            }
        });
        lc.logout();
        return responseBody;
    } finally {
        krb5Configuration.resetConfiguration();
    }
}
Also used : JBossNegotiateSchemeFactory(org.jboss.as.test.integration.security.common.negotiation.JBossNegotiateSchemeFactory) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) LoginException(javax.security.auth.login.LoginException) ProtocolException(org.apache.http.ProtocolException) URISyntaxException(java.net.URISyntaxException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PrivilegedActionException(java.security.PrivilegedActionException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) LoginContext(javax.security.auth.login.LoginContext) Header(org.apache.http.Header) AuthScope(org.apache.http.auth.AuthScope) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider) HashSet(java.util.HashSet)

Example 93 with CloseableHttpClient

use of org.apache.http.impl.client.CloseableHttpClient in project wildfly by wildfly.

the class Utils method makeCall.

/**
     * Makes HTTP call without authentication. Returns response body as a String.
     *
     * @param uri requested URL
     * @param expectedStatusCode expected status code - it's checked after the request is executed
     * @throws Exception
     */
public static String makeCall(URI uri, int expectedStatusCode) throws Exception {
    try (final CloseableHttpClient httpClient = HttpClients.createDefault()) {
        final HttpGet httpget = new HttpGet(uri);
        final HttpResponse response = httpClient.execute(httpget);
        int statusCode = response.getStatusLine().getStatusCode();
        assertEquals("Unexpected status code in HTTP response.", expectedStatusCode, statusCode);
        return EntityUtils.toString(response.getEntity());
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse)

Example 94 with CloseableHttpClient

use of org.apache.http.impl.client.CloseableHttpClient in project wildfly by wildfly.

the class Utils method makeHttpCallWithFallback.

/**
     * Creates request against SPNEGO protected web-app with FORM fallback. It tries to login using SPNEGO first - if it fails,
     * FORM is used.
     *
     * @param contextUrl
     * @param page
     * @param user
     * @param pass
     * @param expectedStatusCode
     * @return
     * @throws IOException
     * @throws URISyntaxException
     * @throws PrivilegedActionException
     * @throws LoginException
     */
public static String makeHttpCallWithFallback(final String contextUrl, final String page, final String user, final String pass, final int expectedStatusCode) throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
    final String strippedContextUrl = StringUtils.stripEnd(contextUrl, "/");
    final String url = strippedContextUrl + page;
    LOGGER.trace("Requesting URL: " + url);
    String unauthorizedPageBody = null;
    final Krb5LoginConfiguration krb5Configuration = new Krb5LoginConfiguration(getLoginConfiguration());
    Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new JBossNegotiateSchemeFactory(true)).build();
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullHCCredentials());
    final CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credentialsProvider).setRedirectStrategy(REDIRECT_STRATEGY).setConnectionManager(new BasicHttpClientConnectionManager()).build();
    try {
        final HttpGet httpGet = new HttpGet(url);
        final HttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
            assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
            return EntityUtils.toString(response.getEntity());
        }
        final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
        assertTrue("WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
        final Set<String> authnHeaderValues = new HashSet<String>();
        for (final Header header : authnHeaders) {
            authnHeaderValues.add(header.getValue());
        }
        assertTrue("WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));
        LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
        unauthorizedPageBody = EntityUtils.toString(response.getEntity());
        // Use our custom configuration to avoid reliance on external config
        Configuration.setConfiguration(krb5Configuration);
        // 1. Authenticate to Kerberos.
        final LoginContext lc = loginWithKerberos(krb5Configuration, user, pass);
        // 2. Perform the work as authenticated Subject.
        final String responseBody = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<String>() {

            public String run() throws Exception {
                final HttpResponse response = httpClient.execute(httpGet);
                int statusCode = response.getStatusLine().getStatusCode();
                assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode);
                return EntityUtils.toString(response.getEntity());
            }
        });
        lc.logout();
        return responseBody;
    } catch (LoginException e) {
        assertNotNull(unauthorizedPageBody);
        assertTrue(unauthorizedPageBody.contains("j_security_check"));
        HttpPost httpPost = new HttpPost(strippedContextUrl + "/j_security_check");
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("j_username", user));
        nameValuePairs.add(new BasicNameValuePair("j_password", pass));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        final HttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode);
        return EntityUtils.toString(response.getEntity());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpClient.close();
        // reset login configuration
        krb5Configuration.resetConfiguration();
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpGet(org.apache.http.client.methods.HttpGet) LoginContext(javax.security.auth.login.LoginContext) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) List(java.util.List) ArrayList(java.util.ArrayList) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) HashSet(java.util.HashSet) JBossNegotiateSchemeFactory(org.jboss.as.test.integration.security.common.negotiation.JBossNegotiateSchemeFactory) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpResponse(org.apache.http.HttpResponse) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) LoginException(javax.security.auth.login.LoginException) ProtocolException(org.apache.http.ProtocolException) URISyntaxException(java.net.URISyntaxException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PrivilegedActionException(java.security.PrivilegedActionException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) Header(org.apache.http.Header) AuthScope(org.apache.http.auth.AuthScope) LoginException(javax.security.auth.login.LoginException) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider)

Example 95 with CloseableHttpClient

use of org.apache.http.impl.client.CloseableHttpClient in project asterixdb by apache.

the class HyracksConnection method deployBinary.

@Override
public DeploymentId deployBinary(List<String> jars) throws Exception {
    /** generate a deployment id */
    DeploymentId deploymentId = new DeploymentId(UUID.randomUUID().toString());
    List<URL> binaryURLs = new ArrayList<>();
    if (jars != null && !jars.isEmpty()) {
        CloseableHttpClient hc = new DefaultHttpClient();
        try {
            /** upload jars through a http client one-by-one to the CC server */
            for (String jar : jars) {
                int slashIndex = jar.lastIndexOf('/');
                String fileName = jar.substring(slashIndex + 1);
                String url = "http://" + ccHost + ":" + ccInfo.getWebPort() + "/applications/" + deploymentId.toString() + "&" + fileName;
                HttpPut put = new HttpPut(url);
                put.setEntity(new FileEntity(new File(jar), "application/octet-stream"));
                HttpResponse response = hc.execute(put);
                response.getEntity().consumeContent();
                if (response.getStatusLine().getStatusCode() != 200) {
                    hci.unDeployBinary(deploymentId);
                    throw new HyracksException(response.getStatusLine().toString());
                }
                /** add the uploaded URL address into the URLs of jars to be deployed at NCs */
                binaryURLs.add(new URL(url));
            }
        } finally {
            hc.close();
        }
    }
    /** deploy the URLs to the CC and NCs */
    hci.deployBinary(binaryURLs, deploymentId);
    return deploymentId;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) DeploymentId(org.apache.hyracks.api.deployment.DeploymentId) FileEntity(org.apache.http.entity.FileEntity) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) HyracksException(org.apache.hyracks.api.exceptions.HyracksException) URL(java.net.URL) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpPut(org.apache.http.client.methods.HttpPut) File(java.io.File)

Aggregations

CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)430 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)238 HttpGet (org.apache.http.client.methods.HttpGet)212 Test (org.junit.Test)206 HttpResponse (org.apache.http.HttpResponse)108 HttpEntity (org.apache.http.HttpEntity)92 IOException (java.io.IOException)90 HttpPost (org.apache.http.client.methods.HttpPost)85 StringEntity (org.apache.http.entity.StringEntity)67 InputStream (java.io.InputStream)57 StatusLine (org.apache.http.StatusLine)41 HttpHost (org.apache.http.HttpHost)36 URI (java.net.URI)35 RequestConfig (org.apache.http.client.config.RequestConfig)32 Header (org.apache.http.Header)24 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)24 File (java.io.File)22 HttpPut (org.apache.http.client.methods.HttpPut)22 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)20 ByteArrayInputStream (java.io.ByteArrayInputStream)19