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"));
}
}
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();
}
}
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());
}
}
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();
}
}
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;
}
Aggregations