small fixes and formatting work

This commit is contained in:
eugenp 2014-11-27 20:26:18 +02:00
parent 1c79503594
commit 84d3367a37
4 changed files with 237 additions and 247 deletions

View File

@ -11,6 +11,7 @@ import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
@ -93,17 +94,15 @@ public class HttpClientTimeoutLiveTest {
/**
* This simulates a timeout against a domain with multiple routes/IPs to it (not a single raw IP)
*/
@Test
public final void givenTimeoutIsConfigured_whenTimingOut_thenCorrect() throws ClientProtocolException, IOException {
@Test(expected = ConnectTimeoutException.class)
public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws ClientProtocolException, IOException {
final int timeout = 3;
final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
final HttpGet request = new HttpGet("http://www.google.com:81");
response = client.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.execute(request);
}
}

View File

@ -35,85 +35,77 @@ import org.junit.Test;
* */
public class HttpsClientSslLiveTest {
// "https://localhost:8443/spring-security-rest-basic-auth/api/bars/1" // local
// "https://mms.nw.ru/" // hosted
private static final String HOST_WITH_SSL = "https://mms.nw.ru/";
// "https://localhost:8443/spring-security-rest-basic-auth/api/bars/1" // local
// "https://mms.nw.ru/" // hosted
private static final String HOST_WITH_SSL = "https://mms.nw.ru/";
// tests
// tests
@Test(expected = SSLException.class)
public final void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException {
final CloseableHttpClient httpClient = HttpClientBuilder.create().build();
@Test(expected = SSLException.class)
public final void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException {
final CloseableHttpClient httpClient = HttpClientBuilder.create().build();
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
@SuppressWarnings("deprecation")
@Test
public final void givenHttpClientPre4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
@Override
public final boolean isTrusted(final X509Certificate[] certificate, final String authType) {
return true;
}
};
final SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
final SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", 443, sf));
final ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
@SuppressWarnings("deprecation")
@Test
public final void givenHttpClientPre4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
@Override
public final boolean isTrusted(final X509Certificate[] certificate, final String authType) {
return true;
}
};
final SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
final SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", 443, sf));
final ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
final CloseableHttpClient httpClient = new DefaultHttpClient(ccm);
final CloseableHttpClient httpClient = new DefaultHttpClient(ccm);
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
httpClient.close();
}
httpClient.close();
}
@Test
public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
@Override
public final boolean isTrusted(final X509Certificate[] certificate, final String authType) {
return true;
}
};
final SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy).build();
@Test
public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
@Override
public final boolean isTrusted(final X509Certificate[] certificate, final String authType) {
return true;
}
};
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
final CloseableHttpClient httpClient = HttpClients
.custom()
.setHostnameVerifier(
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
.setSSLSocketFactory(sslsf).build();
final CloseableHttpClient httpClient = HttpClients.custom().setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).setSSLSocketFactory(sslsf).build();
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
httpClient.close();
}
httpClient.close();
}
@Test
public final void givenHttpClientPost4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
final CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
@Test
public final void givenHttpClientPost4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
final CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
// new
// new
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
}

View File

@ -25,132 +25,132 @@ import com.google.common.collect.Lists;
public class HttpClientUnshortenLiveTest {
private CloseableHttpClient client;
private CloseableHttpClient client;
// fixtures
// fixtures
@Before
public final void before() {
client = HttpClientBuilder.create().disableRedirectHandling().build();
}
@Before
public final void before() {
client = HttpClientBuilder.create().disableRedirectHandling().build();
}
// tests
// tests
@Test
public final void givenShortenedOnce_whenUrlIsUnshortened_thenCorrectResult() throws IOException {
final String expectedResult = "http://www.baeldung.com/rest-versioning";
final String actualResult = expandSingleLevel("http://bit.ly/13jEoS1");
assertThat(actualResult, equalTo(expectedResult));
}
@Test
public final void givenShortenedOnce_whenUrlIsUnshortened_thenCorrectResult() throws IOException {
final String expectedResult = "http://www.baeldung.com/rest-versioning";
final String actualResult = expandSingleLevel("http://bit.ly/13jEoS1");
assertThat(actualResult, equalTo(expectedResult));
}
@Test
public final void givenShortenedMultiple_whenUrlIsUnshortened_thenCorrectResult() throws IOException {
final String expectedResult = "http://www.baeldung.com/rest-versioning";
final String actualResult = expand("http://t.co/e4rDDbnzmk");
assertThat(actualResult, equalTo(expectedResult));
}
@Test
public final void givenShortenedMultiple_whenUrlIsUnshortened_thenCorrectResult() throws IOException {
final String expectedResult = "http://www.baeldung.com/rest-versioning";
final String actualResult = expand("http://t.co/e4rDDbnzmk");
assertThat(actualResult, equalTo(expectedResult));
}
// API
// API
final String expand(final String urlArg) throws IOException {
String originalUrl = urlArg;
String newUrl = expandSingleLevel(originalUrl);
while (!originalUrl.equals(newUrl)) {
originalUrl = newUrl;
newUrl = expandSingleLevel(originalUrl);
}
final String expand(final String urlArg) throws IOException {
String originalUrl = urlArg;
String newUrl = expandSingleLevel(originalUrl);
while (!originalUrl.equals(newUrl)) {
originalUrl = newUrl;
newUrl = expandSingleLevel(originalUrl);
}
return newUrl;
}
return newUrl;
}
final String expandSafe(final String urlArg) throws IOException {
String originalUrl = urlArg;
String newUrl = expandSingleLevelSafe(originalUrl).getRight();
final List<String> alreadyVisited = Lists.newArrayList(originalUrl, newUrl);
while (!originalUrl.equals(newUrl)) {
originalUrl = newUrl;
final Pair<Integer, String> statusAndUrl = expandSingleLevelSafe(originalUrl);
newUrl = statusAndUrl.getRight();
final boolean isRedirect = statusAndUrl.getLeft() == 301 || statusAndUrl.getLeft() == 302;
if (isRedirect && alreadyVisited.contains(newUrl)) {
throw new IllegalStateException("Likely a redirect loop");
}
alreadyVisited.add(newUrl);
}
final String expandSafe(final String urlArg) throws IOException {
String originalUrl = urlArg;
String newUrl = expandSingleLevelSafe(originalUrl).getRight();
final List<String> alreadyVisited = Lists.newArrayList(originalUrl, newUrl);
while (!originalUrl.equals(newUrl)) {
originalUrl = newUrl;
final Pair<Integer, String> statusAndUrl = expandSingleLevelSafe(originalUrl);
newUrl = statusAndUrl.getRight();
final boolean isRedirect = statusAndUrl.getLeft() == 301 || statusAndUrl.getLeft() == 302;
if (isRedirect && alreadyVisited.contains(newUrl)) {
throw new IllegalStateException("Likely a redirect loop");
}
alreadyVisited.add(newUrl);
}
return newUrl;
}
return newUrl;
}
final Pair<Integer, String> expandSingleLevelSafe(final String url) throws IOException {
HttpGet request = null;
HttpEntity httpEntity = null;
InputStream entityContentStream = null;
final Pair<Integer, String> expandSingleLevelSafe(final String url) throws IOException {
HttpGet request = null;
HttpEntity httpEntity = null;
InputStream entityContentStream = null;
try {
request = new HttpGet(url);
final HttpResponse httpResponse = client.execute(request);
try {
request = new HttpGet(url);
final HttpResponse httpResponse = client.execute(request);
httpEntity = httpResponse.getEntity();
entityContentStream = httpEntity.getContent();
httpEntity = httpResponse.getEntity();
entityContentStream = httpEntity.getContent();
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != 301 && statusCode != 302) {
return new ImmutablePair<Integer, String>(statusCode, url);
}
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
Preconditions.checkState(headers.length == 1);
final String newUrl = headers[0].getValue();
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != 301 && statusCode != 302) {
return new ImmutablePair<Integer, String>(statusCode, url);
}
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
Preconditions.checkState(headers.length == 1);
final String newUrl = headers[0].getValue();
return new ImmutablePair<Integer, String>(statusCode, newUrl);
} catch (final IllegalArgumentException uriEx) {
return new ImmutablePair<Integer, String>(500, url);
} finally {
if (request != null) {
request.releaseConnection();
}
if (entityContentStream != null) {
entityContentStream.close();
}
if (httpEntity != null) {
EntityUtils.consume(httpEntity);
}
}
}
return new ImmutablePair<Integer, String>(statusCode, newUrl);
} catch (final IllegalArgumentException uriEx) {
return new ImmutablePair<Integer, String>(500, url);
} finally {
if (request != null) {
request.releaseConnection();
}
if (entityContentStream != null) {
entityContentStream.close();
}
if (httpEntity != null) {
EntityUtils.consume(httpEntity);
}
}
}
final String expandSingleLevel(final String url) throws IOException {
HttpGet request = null;
HttpEntity httpEntity = null;
InputStream entityContentStream = null;
final String expandSingleLevel(final String url) throws IOException {
HttpGet request = null;
HttpEntity httpEntity = null;
InputStream entityContentStream = null;
try {
request = new HttpGet(url);
final HttpResponse httpResponse = client.execute(request);
try {
request = new HttpGet(url);
final HttpResponse httpResponse = client.execute(request);
httpEntity = httpResponse.getEntity();
entityContentStream = httpEntity.getContent();
httpEntity = httpResponse.getEntity();
entityContentStream = httpEntity.getContent();
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != 301 && statusCode != 302) {
return url;
}
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
Preconditions.checkState(headers.length == 1);
final String newUrl = headers[0].getValue();
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != 301 && statusCode != 302) {
return url;
}
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
Preconditions.checkState(headers.length == 1);
final String newUrl = headers[0].getValue();
return newUrl;
} catch (final IllegalArgumentException uriEx) {
return url;
} finally {
if (request != null) {
request.releaseConnection();
}
if (entityContentStream != null) {
entityContentStream.close();
}
if (httpEntity != null) {
EntityUtils.consume(httpEntity);
}
}
}
return newUrl;
} catch (final IllegalArgumentException uriEx) {
return url;
} finally {
if (request != null) {
request.releaseConnection();
}
if (entityContentStream != null) {
entityContentStream.close();
}
if (httpEntity != null) {
EntityUtils.consume(httpEntity);
}
}
}
}

View File

@ -24,95 +24,94 @@ import org.junit.Test;
public class HttpClientCookieLiveTest {
private CloseableHttpClient instance;
private CloseableHttpClient instance;
private CloseableHttpResponse response;
private CloseableHttpResponse response;
@Before
public final void before() {
instance = HttpClientBuilder.create().build();
}
@Before
public final void before() {
instance = HttpClientBuilder.create().build();
}
@After
public final void after() throws IllegalStateException, IOException {
if (response == null) {
return;
}
@After
public final void after() throws IllegalStateException, IOException {
if (response == null) {
return;
}
try {
final HttpEntity entity = response.getEntity();
if (entity != null) {
final InputStream instream = entity.getContent();
instream.close();
}
} finally {
response.close();
}
}
try {
final HttpEntity entity = response.getEntity();
if (entity != null) {
final InputStream instream = entity.getContent();
instream.close();
}
} finally {
response.close();
}
}
// tests
// tests
@Test
public final void whenSettingCookiesOnARequest_thenCorrect() throws ClientProtocolException, IOException {
instance = HttpClientBuilder.create().build();
final HttpGet request = new HttpGet("http://www.github.com");
request.setHeader("Cookie", "JSESSIONID=1234");
@Test
public final void whenSettingCookiesOnARequest_thenCorrect() throws ClientProtocolException, IOException {
instance = HttpClientBuilder.create().build();
final HttpGet request = new HttpGet("http://www.github.com");
request.setHeader("Cookie", "JSESSIONID=1234");
response = instance.execute(request);
response = instance.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws ClientProtocolException, IOException {
final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".github.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);
final HttpClient client = HttpClientBuilder.create()
.setDefaultCookieStore(cookieStore).build();
@Test
public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws ClientProtocolException, IOException {
final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".github.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);
final HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
final HttpGet request = new HttpGet("http://www.github.com");
final HttpGet request = new HttpGet("http://www.github.com");
response = (CloseableHttpResponse) client.execute(request);
response = (CloseableHttpResponse) client.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws ClientProtocolException, IOException {
final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".github.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);
instance = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
@Test
public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws ClientProtocolException, IOException {
final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".github.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);
instance = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
final HttpGet request = new HttpGet("http://www.github.com");
final HttpGet request = new HttpGet("http://www.github.com");
response = instance.execute(request);
response = instance.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws ClientProtocolException, IOException {
final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".github.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);
instance = HttpClientBuilder.create().build();
@Test
public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws ClientProtocolException, IOException {
final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".github.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);
instance = HttpClientBuilder.create().build();
final HttpGet request = new HttpGet("http://www.github.com");
final HttpGet request = new HttpGet("http://www.github.com");
final HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
// localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // before 4.3
response = instance.execute(request, localContext);
final HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
// localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // before 4.3
response = instance.execute(request, localContext);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
}