Merge pull request #8125 from eugenp/revert-8119-BAEL-3275-2

Revert "BAEL-3275: Using blocking queue for pub-sub"
This commit is contained in:
Eric Martin
2019-10-31 20:43:47 -05:00
committed by GitHub
parent db85c8f275
commit 3225470df5
20543 changed files with 1642750 additions and 0 deletions
@@ -0,0 +1,47 @@
package com.baeldung.client;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import com.baeldung.client.spring.ClientConfig;
import com.baeldung.web.dto.Foo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ClientConfig.class }, loader = AnnotationConfigContextLoader.class)
public class ClientLiveTest {
@Autowired
private RestTemplate secureRestTemplate;
// tests
@Test
public final void whenContextIsBootstrapped_thenNoExceptions() {
//
}
@Test
public final void whenSecuredRestApiIsConsumed_then200OK() {
final ResponseEntity<Foo> responseEntity = secureRestTemplate.exchange("http://localhost:8082/httpclient-simple/api/foos/1", HttpMethod.GET, null, Foo.class);
assertThat(responseEntity.getStatusCode().value(), is(200));
}
@Test(expected = ResourceAccessException.class)
public final void whenHttpsUrlIsConsumed_thenException() {
final String urlOverHttps = "https://localhost:8443/httpclient-simple/api/bars/1";
final ResponseEntity<String> response = new RestTemplate().exchange(urlOverHttps, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}
}
@@ -0,0 +1,112 @@
package com.baeldung.client;
import static org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.security.GeneralSecurityException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLPeerUnverifiedException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
/**
* This test requires a localhost server over HTTPS <br>
* It should only be manually run, not part of the automated build
* */
public class RestClientLiveManualTest {
final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1";
// tests
// old httpClient will throw UnsupportedOperationException
@Ignore
@Test
public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk() throws GeneralSecurityException {
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
final CloseableHttpClient httpClient = (CloseableHttpClient) requestFactory.getHttpClient();
final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
final SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, ALLOW_ALL_HOSTNAME_VERIFIER);
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 8443, sf));
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}
// new httpClient : 4.4 and above
@Test
public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("https", sslsf)
.register("http", new PlainConnectionSocketFactory())
.build();
final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setConnectionManager(connectionManager)
.build();
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}
@Test
public final void givenAcceptingAllCertificatesUsing4_4_whenHttpsUrlIsConsumed_thenCorrect() throws ClientProtocolException, IOException {
final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
final HttpGet getMethod = new HttpGet(urlOverHttps);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
public final void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect() throws ClientProtocolException, IOException {
final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
final ResponseEntity<String> response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class);
assertThat(response.getStatusCode().value(), equalTo(200));
}
@Test(expected = SSLPeerUnverifiedException.class)
public void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
String urlOverHttps = "https://localhost:8082/httpclient-simple";
HttpGet getMethod = new HttpGet(urlOverHttps);
HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
}
@@ -0,0 +1,100 @@
package com.baeldung.httpclient;
import com.google.common.collect.Lists;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
public class HttpClientHeadersLiveTest {
private static final String SAMPLE_URL = "http://www.github.com";
private CloseableHttpClient client;
private CloseableHttpResponse response;
@Before
public final void before() {
client = HttpClientBuilder.create().build();
}
@After
public final void after() throws IllegalStateException, IOException {
ResponseUtil.closeResponse(response);
}
// tests - headers - deprecated
@Test
public final void givenNewApi_whenClientUsesCustomUserAgent_thenCorrect() throws ClientProtocolException, IOException {
client = HttpClients.custom().setUserAgent("Mozilla/5.0 Firefox/26.0").build();
final HttpGet request = new HttpGet(SAMPLE_URL);
response = client.execute(request);
}
// tests - headers - user agent
@Test
public final void givenConfigOnRequest_whenRequestHasCustomUserAgent_thenCorrect() throws ClientProtocolException, IOException {
client = HttpClients.custom().build();
final HttpGet request = new HttpGet(SAMPLE_URL);
request.setHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 Firefox/26.0");
response = client.execute(request);
}
@Test
public final void givenConfigOnClient_whenRequestHasCustomUserAgent_thenCorrect() throws ClientProtocolException, IOException {
client = HttpClients.custom().setUserAgent("Mozilla/5.0 Firefox/26.0").build();
response = client.execute(new HttpGet(SAMPLE_URL));
}
// tests - headers - content type
@Test
public final void givenUsingNewApi_whenRequestHasCustomContentType_thenCorrect() throws ClientProtocolException, IOException {
client = HttpClients.custom().build();
final HttpGet request = new HttpGet(SAMPLE_URL);
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
response = client.execute(request);
}
@Test
public final void givenRequestBuildWithBuilderWithNewApi_whenRequestHasCustomContentType_thenCorrect() throws ClientProtocolException, IOException {
final CloseableHttpClient client2 = HttpClients.custom().build();
final HttpGet request = new HttpGet(SAMPLE_URL);
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
response = client2.execute(request);
}
@Test
public final void givenRequestBuildWithBuilder_whenRequestHasCustomContentType_thenCorrect() throws ClientProtocolException, IOException {
client = HttpClients.custom().build();
final HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).setHeader(HttpHeaders.CONTENT_TYPE, "application/json").build();
response = client.execute(request);
}
@Test
public final void givenConfigOnClient_whenRequestHasCustomContentType_thenCorrect() throws ClientProtocolException, IOException {
final Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
final List<Header> headers = Lists.newArrayList(header);
client = HttpClients.custom().setDefaultHeaders(headers).build();
final HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).build();
response = client.execute(request);
}
}
@@ -0,0 +1,144 @@
package com.baeldung.httpclient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
/*
* NOTE : Need module spring-rest to be running
*/
public class HttpClientPostingLiveTest {
private static final String SAMPLE_URL = "http://www.example.com";
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";
private static final String DEFAULT_USER = "test";
private static final String DEFAULT_PASS = "test";
@Test
public void whenSendPostRequestUsingHttpClient_thenCorrect() throws IOException {
final CloseableHttpClient client = HttpClients.createDefault();
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
final List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", DEFAULT_USER));
params.add(new BasicNameValuePair("password", DEFAULT_PASS));
httpPost.setEntity(new UrlEncodedFormEntity(params));
final CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
@Test
public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException, AuthenticationException {
final CloseableHttpClient client = HttpClients.createDefault();
final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
httpPost.setEntity(new StringEntity("test post"));
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));
final CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
@Test
public void whenPostJsonUsingHttpClient_thenCorrect() throws IOException {
final CloseableHttpClient client = HttpClients.createDefault();
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
final String json = "{\"id\":1,\"name\":\"John\"}";
final StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
final CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
@Test
public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws IOException {
final HttpResponse response = Request.Post(SAMPLE_URL).bodyForm(Form.form().add("username", DEFAULT_USER).add("password", DEFAULT_PASS).build()).execute().returnResponse();
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws IOException {
final CloseableHttpClient client = HttpClients.createDefault();
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("username", DEFAULT_USER);
builder.addTextBody("password", DEFAULT_PASS);
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
final HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
final CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
@Test
public void whenUploadFileUsingHttpClient_thenCorrect() throws IOException {
final CloseableHttpClient client = HttpClients.createDefault();
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
final HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
final CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
@Test
public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws IOException {
final CloseableHttpClient client = HttpClients.createDefault();
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
final HttpEntity multipart = builder.build();
final ProgressEntityWrapper.ProgressListener pListener = percentage -> assertFalse(Float.compare(percentage, 100) > 0);
httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener));
final CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
}
}
@@ -0,0 +1,129 @@
package com.baeldung.httpclient;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.HttpResponse;
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.client.params.ClientPNames;
import org.apache.http.config.SocketConfig;
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;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.junit.After;
import org.junit.Ignore;
import org.junit.Test;
public class HttpClientTimeoutLiveTest {
private CloseableHttpResponse response;
@After
public final void after() throws IllegalStateException, IOException {
ResponseUtil.closeResponse(response);
}
// tests
@Test
public final void givenUsingOldApi_whenSettingTimeoutViaParameter_thenCorrect() throws IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
int timeout = 5; // seconds
HttpParams httpParams = httpClient.getParams();
httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout * 1000);
httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout * 1000);
httpParams.setParameter(ClientPNames.CONN_MANAGER_TIMEOUT, new Long(timeout * 1000));
final HttpGet request = new HttpGet("http://www.github.com");
HttpResponse execute = httpClient.execute(request);
assertThat(execute.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
public final void givenUsingNewApi_whenSettingTimeoutViaRequestConfig_thenCorrect() throws IOException {
final int timeout = 2;
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.github.com");
response = client.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
public final void givenUsingNewApi_whenSettingTimeoutViaSocketConfig_thenCorrect() throws IOException {
final int timeout = 2;
final SocketConfig config = SocketConfig.custom().setSoTimeout(timeout * 1000).build();
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultSocketConfig(config).build();
final HttpGet request = new HttpGet("http://www.github.com");
response = client.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
public final void givenUsingNewApi_whenSettingTimeoutViaHighLevelApi_thenCorrect() throws IOException {
final int timeout = 5;
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.github.com");
response = client.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
/**
* This simulates a timeout against a domain with multiple routes/IPs to it (not a single raw IP)
*/
@Test(expected = ConnectTimeoutException.class)
@Ignore
public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws 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");
client.execute(request);
}
@Test
public void whenSecuredRestApiIsConsumed_then200OK() throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
int timeout = 20; // seconds
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout * 1000)
.setConnectTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
HttpGet getMethod = new HttpGet("http://localhost:8082/httpclient-simple/api/bars/1");
getMethod.setConfig(requestConfig);
int hardTimeout = 5; // seconds
TimerTask task = new TimerTask() {
@Override
public void run() {
getMethod.abort();
}
};
new Timer(true).schedule(task, hardTimeout * 1000);
HttpResponse response = httpClient.execute(getMethod);
System.out.println("HTTP Status of response: " + response.getStatusLine().getStatusCode());
}
}
@@ -0,0 +1,137 @@
package com.baeldung.httpclient;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.security.GeneralSecurityException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.junit.Test;
/**
* This test requires a localhost server over HTTPS <br>
* It should only be manually run, not part of the automated build
* */
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/";
// tests
@Test(expected = SSLHandshakeException.class)
public final void whenHttpsUrlIsConsumed_thenException() throws 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));
}
@Test
public final void givenHttpClientPre4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
final SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("https", sslsf).build();
PoolingHttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setConnectionManager(clientConnectionManager)
.build();
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
httpClient.close();
}
@Test
public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
final SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
httpClient.close();
}
@Test
public final void givenHttpClientPost4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException {
final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
.build();
final NoopHostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
final CloseableHttpClient httpClient = HttpClients.custom()
.setSSLHostnameVerifier(hostnameVerifier)
.setSSLSocketFactory(sslsf)
.build();
// new
final HttpGet getMethod = new HttpGet(HOST_WITH_SSL);
final HttpResponse response = httpClient.execute(getMethod);
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
httpClient.close();
}
@Test
public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception {
final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true)
.build();
final CloseableHttpClient client = HttpClients.custom()
.setSSLContext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
final HttpGet httpGet = new HttpGet(HOST_WITH_SSL);
httpGet.setHeader("Accept", "application/xml");
final HttpResponse response = client.execute(httpGet);
assertThat(response.getStatusLine()
.getStatusCode(), equalTo(200));
}
}
@@ -0,0 +1,58 @@
package com.baeldung.httpclient;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.entity.HttpEntityWrapper;
public class ProgressEntityWrapper extends HttpEntityWrapper {
private final ProgressListener listener;
ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) {
super(entity);
this.listener = listener;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
super.writeTo(new CountingOutputStream(outstream, listener, getContentLength()));
}
public interface ProgressListener {
void progress(float percentage);
}
public static class CountingOutputStream extends FilterOutputStream {
private final ProgressListener listener;
private long transferred;
private long totalBytes;
CountingOutputStream(final OutputStream out, final ProgressListener listener, final long totalBytes) {
super(out);
this.listener = listener;
transferred = 0;
this.totalBytes = totalBytes;
}
@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
out.write(b, off, len);
transferred += len;
listener.progress(getCurrentProgress());
}
@Override
public void write(final int b) throws IOException {
out.write(b);
transferred++;
listener.progress(getCurrentProgress());
}
private float getCurrentProgress() {
return ((float) transferred / totalBytes) * 100;
}
}
}
@@ -0,0 +1,26 @@
package com.baeldung.httpclient;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import java.io.IOException;
public final class ResponseUtil {
private ResponseUtil() {
}
public static void closeResponse(CloseableHttpResponse response) throws IOException {
if (response == null) {
return;
}
try {
final HttpEntity entity = response.getEntity();
if (entity != null) {
entity.getContent().close();
}
} finally {
response.close();
}
}
}
@@ -0,0 +1,72 @@
package com.baeldung.httpclient.base;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import com.baeldung.httpclient.ResponseUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
public class HttpClientBasicLiveTest {
private static final String SAMPLE_URL = "http://www.github.com";
private CloseableHttpClient instance;
private CloseableHttpResponse response;
@Before
public final void before() {
instance = HttpClientBuilder.create().build();
}
@After
public final void after() throws IllegalStateException, IOException {
ResponseUtil.closeResponse(response);
}
// tests
// simple request - response
@Test
public final void whenExecutingBasicGetRequest_thenNoExceptions() throws ClientProtocolException, IOException {
response = instance.execute(new HttpGet(SAMPLE_URL));
}
@Test
public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws ClientProtocolException, IOException {
response = instance.execute(new HttpGet(SAMPLE_URL));
final int statusCode = response.getStatusLine().getStatusCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
}
@Test
public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectMimeType() throws ClientProtocolException, IOException {
response = instance.execute(new HttpGet(SAMPLE_URL));
final String contentMimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
assertThat(contentMimeType, equalTo(ContentType.TEXT_HTML.getMimeType()));
}
@Test
public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectBody() throws ClientProtocolException, IOException {
response = instance.execute(new HttpGet(SAMPLE_URL));
final String bodyAsString = EntityUtils.toString(response.getEntity());
assertThat(bodyAsString, notNullValue());
}
}
@@ -0,0 +1,137 @@
package com.baeldung.httpclient.sec;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HttpContext;
import com.baeldung.httpclient.ResponseUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
/*
* NOTE : Need module httpclient-simple to be running
*/
public class HttpClientAuthLiveTest {
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://localhost:8082/httpclient-simple/api/foos/1";
private static final String DEFAULT_USER = "user1";
private static final String DEFAULT_PASS = "user1Pass";
private CloseableHttpClient client;
private CloseableHttpResponse response;
@Before
public final void before() {
client = HttpClientBuilder.create().build();
}
@After
public final void after() throws IllegalStateException, IOException {
ResponseUtil.closeResponse(response);
}
// tests
@Test
public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException {
client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider()).build();
response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION));
final int statusCode = response.getStatusLine().getStatusCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
}
@Test
public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException {
client = HttpClientBuilder.create().build();
response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context());
final int statusCode = response.getStatusLine().getStatusCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
}
@Test
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws IOException {
client = HttpClientBuilder.create().build();
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
request.setHeader(HttpHeaders.AUTHORIZATION, authorizationHeader(DEFAULT_USER, DEFAULT_PASS));
response = client.execute(request);
final int statusCode = response.getStatusLine().getStatusCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
}
@Test
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws IOException {
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
final String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
final String authHeader = "Basic " + new String(encodedAuth);
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
client = HttpClientBuilder.create().build();
response = client.execute(request);
final int statusCode = response.getStatusLine().getStatusCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
}
// UTILS
private CredentialsProvider provider() {
final CredentialsProvider provider = new BasicCredentialsProvider();
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
provider.setCredentials(AuthScope.ANY, credentials);
return provider;
}
private HttpContext context() {
final HttpHost targetHost = new HttpHost("localhost", 8082, "http");
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS));
// Create AuthCache instance
final AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
authCache.put(targetHost, new BasicScheme());
// Add AuthCache to the execution context
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
return context;
}
private String authorizationHeader(final String username, final String password) {
final String auth = username + ":" + password;
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
return "Basic " + new String(encodedAuth);
}
}
@@ -0,0 +1,103 @@
package com.baeldung.httpclient.sec;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import com.baeldung.httpclient.ResponseUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
public class HttpClientCookieLiveTest {
private CloseableHttpClient instance;
private CloseableHttpResponse response;
@Before
public final void before() {
instance = HttpClientBuilder.create().build();
}
@After
public final void after() throws IllegalStateException, IOException {
ResponseUtil.closeResponse(response);
}
// tests
@Test
public final void whenSettingCookiesOnARequest_thenCorrect() throws IOException {
instance = HttpClientBuilder.create().build();
final HttpGet request = new HttpGet("http://www.github.com");
request.setHeader("Cookie", "JSESSIONID=1234");
response = instance.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws 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");
response = (CloseableHttpResponse) client.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws 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");
response = instance.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
@Test
public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws 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 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));
}
}
@@ -0,0 +1,16 @@
package com.baeldung.test;
import com.baeldung.client.ClientLiveTest;
import com.baeldung.client.RestClientLiveManualTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
// @formatter:off
RestClientLiveManualTest.class
,ClientLiveTest.class
}) //
public class LiveTestSuite {
}