use of org.apache.http.client.protocol.HttpClientContext in project crate by crate.
the class BlobHttpIntegrationTest method getRedirectLocations.
public List<String> getRedirectLocations(CloseableHttpClient client, String uri, InetSocketAddress address) throws IOException {
CloseableHttpResponse response = null;
try {
HttpClientContext context = HttpClientContext.create();
HttpHead httpHead = new HttpHead(String.format(Locale.ENGLISH, "http://%s:%s/_blobs/%s", address.getHostName(), address.getPort(), uri));
response = client.execute(httpHead, context);
List<URI> redirectLocations = context.getRedirectLocations();
if (redirectLocations == null) {
// client might not follow redirects automatically
if (response.containsHeader("location")) {
List<String> redirects = new ArrayList<>(1);
for (Header location : response.getHeaders("location")) {
redirects.add(location.getValue());
}
return redirects;
}
return Collections.emptyList();
}
List<String> redirects = new ArrayList<>(1);
for (URI redirectLocation : redirectLocations) {
redirects.add(redirectLocation.toString());
}
return redirects;
} finally {
if (response != null) {
IOUtils.closeWhileHandlingException(response);
}
}
}
use of org.apache.http.client.protocol.HttpClientContext in project spring-security-oauth by spring-projects.
the class ServerRunning method createRestTemplate.
public RestOperations createRestTemplate() {
RestTemplate client = new RestTemplate();
client.setRequestFactory(new HttpComponentsClientHttpRequestFactory() {
@Override
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
HttpClientContext context = HttpClientContext.create();
Builder builder = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).setAuthenticationEnabled(false).setRedirectsEnabled(false);
context.setRequestConfig(builder.build());
return context;
}
});
client.setErrorHandler(new DefaultResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return false;
}
});
return client;
}
use of org.apache.http.client.protocol.HttpClientContext in project wildfly by wildfly.
the class Utils method makeCallWithBasicAuthn.
/**
* 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 username is provided, then a new
* request is created with the provided credentials (basic authentication).
*
* @param url URL to which the request should be made
* @param user Username (may be null)
* @param pass Password (may be null)
* @param expectedStatusCode expected status code returned from the requested server
* @return HTTP response body
* @throws IOException
* @throws URISyntaxException
*/
public static String makeCallWithBasicAuthn(URL url, String user, String pass, int expectedStatusCode) throws IOException, URISyntaxException {
LOGGER.trace("Requesting URL " + url);
try (final CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
final HttpGet httpGet = new HttpGet(url.toURI());
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());
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
}
HttpEntity entity = response.getEntity();
if (entity != null)
EntityUtils.consume(entity);
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, pass);
HttpClientContext hc = new HttpClientContext();
hc.setCredentialsProvider(new BasicCredentialsProvider());
hc.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), credentials);
//enable auth
response = httpClient.execute(httpGet, hc);
statusCode = response.getStatusLine().getStatusCode();
assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode);
return EntityUtils.toString(response.getEntity());
}
}
use of org.apache.http.client.protocol.HttpClientContext in project wildfly by wildfly.
the class JAASIdentityCachingTestCase method test.
/**
* Test how many times is called login() method of {@link CustomLoginModule} and if the response from HelloBean is the
* expected one.
*
* @param webAppURL
* @throws Exception
*/
@Test
public void test(@ArquillianResource URL webAppURL) throws Exception {
final URI greetingUri = new URI(webAppURL.toExternalForm() + HelloEJBCallServlet.SERVLET_PATH.substring(1) + "?" + HelloEJBCallServlet.PARAM_JNDI_NAME + "=" + URLEncoder.encode("java:app/" + JAR_BASE_NAME + "/" + HelloBean.class.getSimpleName(), "UTF-8"));
final URI counterUri = new URI(webAppURL.toExternalForm() + LMCounterServlet.SERVLET_PATH.substring(1));
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", CustomLoginModule.PASSWORD);
credentialsProvider.setCredentials(new AuthScope(greetingUri.getHost(), greetingUri.getPort()), credentials);
try (final CloseableHttpClient httpClient = HttpClients.createDefault()) {
final HttpGet getCounter = new HttpGet(counterUri);
final HttpGet getGreeting = new HttpGet(greetingUri);
HttpResponse response = httpClient.execute(getGreeting);
assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
EntityUtils.consume(response.getEntity());
//check if LoginModule #login() counter is initialized correctly
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credentialsProvider);
response = httpClient.execute(getCounter, context);
assertEquals("0", EntityUtils.toString(response.getEntity()));
//make 2 calls to the servlet
response = httpClient.execute(getGreeting, context);
assertEquals("Hello Caller!", EntityUtils.toString(response.getEntity()));
response = httpClient.execute(getGreeting, context);
assertEquals("Hello Caller!", EntityUtils.toString(response.getEntity()));
//There should be only one call to login() method
response = httpClient.execute(getCounter, context);
assertEquals("1", EntityUtils.toString(response.getEntity()));
}
}
use of org.apache.http.client.protocol.HttpClientContext in project wildfly by wildfly.
the class CookieUnitTestCase method testCookieRetrievedCorrectly.
@Test
public void testCookieRetrievedCorrectly() throws Exception {
log.trace("testCookieRetrievedCorrectly()");
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
HttpClientContext context = HttpClientContext.create();
HttpResponse response = httpclient.execute(new HttpGet(cookieURL.toURI() + "CookieServlet"), context);
// assert that we are able to hit servlet successfully
int postStatusCode = response.getStatusLine().getStatusCode();
Header[] postErrorHeaders = response.getHeaders("X-Exception");
assertTrue("Wrong response code: " + postStatusCode, postStatusCode == HttpURLConnection.HTTP_OK);
assertTrue("X-Exception(" + Arrays.toString(postErrorHeaders) + ") is null", postErrorHeaders.length == 0);
List<Cookie> cookies = context.getCookieStore().getCookies();
assertTrue("Sever did not set expired cookie on client", checkNoExpiredCookie(cookies));
for (Cookie cookie : cookies) {
log.trace("Cookie : " + cookie);
String cookieName = cookie.getName();
String cookieValue = cookie.getValue();
if (cookieName.equals("simpleCookie")) {
assertTrue("cookie value should be jboss", cookieValue.equals("jboss"));
assertEquals("cookie path", "/jbosstest-cookie", cookie.getPath());
assertEquals("cookie persistence", false, cookie.isPersistent());
} else if (cookieName.equals("withSpace")) {
assertEquals("should be no quote in cookie with space", cookieValue.indexOf("\""), -1);
} else if (cookieName.equals("comment")) {
log.trace("comment in cookie: " + cookie.getComment());
// RFC2109:Note that there is no Comment attribute in the Cookie request header
// corresponding to the one in the Set-Cookie response header. The user
// agent does not return the comment information to the origin server.
assertTrue(cookie.getComment() == null);
} else if (cookieName.equals("withComma")) {
assertTrue("should contain a comma", cookieValue.indexOf(",") != -1);
} else if (cookieName.equals("expireIn10Sec")) {
Date now = new Date();
log.trace("will sleep for 5 seconds to see if cookie expires");
assertTrue("cookies should not be expired by now", !cookie.isExpired(new Date(now.getTime() + fiveSeconds)));
log.trace("will sleep for 5 more secs and it should expire");
assertTrue("cookies should be expired by now", cookie.isExpired(new Date(now.getTime() + 2 * fiveSeconds)));
}
}
}
}
Aggregations