Merge branch 'eugenp:master' into JAVA-23970
This commit is contained in:
commit
9516c2bd9b
|
@ -1,7 +0,0 @@
|
||||||
## Annotations
|
|
||||||
|
|
||||||
This module contains articles about Java annotations
|
|
||||||
|
|
||||||
### Relevant Articles:
|
|
||||||
|
|
||||||
- [Java Annotation Processing and Creating a Builder](https://www.baeldung.com/java-annotation-processing-builder)
|
|
|
@ -1,21 +0,0 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<artifactId>annotations</artifactId>
|
|
||||||
<name>annotations</name>
|
|
||||||
<packaging>pom</packaging>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>parent-modules</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<modules>
|
|
||||||
<module>annotation-processing</module>
|
|
||||||
<module>annotation-user</module>
|
|
||||||
</modules>
|
|
||||||
|
|
||||||
</project>
|
|
|
@ -16,7 +16,7 @@ public class ApacheHttpClient5UnitTest {
|
||||||
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUseApacheHttpClient_thenCorrect() throws IOException {
|
void whenUseApacheHttpClient_thenCorrect() throws IOException {
|
||||||
HttpGet request = new HttpGet(DUMMY_URL);
|
HttpGet request = new HttpGet(DUMMY_URL);
|
||||||
|
|
||||||
try (CloseableHttpClient client = HttpClients.createDefault()) {
|
try (CloseableHttpClient client = HttpClients.createDefault()) {
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.httpclient.readresponsebodystring;
|
package com.baeldung.httpclient.readresponsebodystring;
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
|
@ -8,11 +7,13 @@ import java.net.http.HttpClient;
|
||||||
import java.net.http.HttpRequest;
|
import java.net.http.HttpRequest;
|
||||||
import java.net.http.HttpResponse;
|
import java.net.http.HttpResponse;
|
||||||
|
|
||||||
public class HttpClientUnitTest {
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class HttpClientUnitTest {
|
||||||
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUseHttpClient_thenCorrect() throws IOException, InterruptedException {
|
void whenUseHttpClient_thenCorrect() throws IOException, InterruptedException {
|
||||||
HttpClient client = HttpClient.newHttpClient();
|
HttpClient client = HttpClient.newHttpClient();
|
||||||
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(DUMMY_URL)).build();
|
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(DUMMY_URL)).build();
|
||||||
|
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
package com.baeldung.httpclient.readresponsebodystring;
|
package com.baeldung.httpclient.readresponsebodystring;
|
||||||
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
@ -10,12 +10,14 @@ import java.io.InputStreamReader;
|
||||||
import java.net.HttpURLConnection;
|
import java.net.HttpURLConnection;
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
public class HttpUrlConnectionUnitTest {
|
public class HttpUrlConnectionUnitTest {
|
||||||
|
|
||||||
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUseHttpUrlConnection_thenCorrect() throws IOException {
|
void whenUseHttpUrlConnection_thenCorrect() throws IOException {
|
||||||
HttpURLConnection connection = (HttpURLConnection) new URL(DUMMY_URL).openConnection();
|
HttpURLConnection connection = (HttpURLConnection) new URL(DUMMY_URL).openConnection();
|
||||||
|
|
||||||
InputStream inputStream = connection.getInputStream();
|
InputStream inputStream = connection.getInputStream();
|
||||||
|
@ -28,7 +30,7 @@ public class HttpUrlConnectionUnitTest {
|
||||||
response.append(currentLine);
|
response.append(currentLine);
|
||||||
|
|
||||||
in.close();
|
in.close();
|
||||||
Assert.assertNotNull(response.toString());
|
assertNotNull(response.toString());
|
||||||
System.out.println("Response -> " + response.toString());
|
System.out.println("Response -> " + response.toString());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
package com.baeldung.httpclient.readresponsebodystring;
|
package com.baeldung.httpclient.readresponsebodystring;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.springframework.web.client.RestTemplate;
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
public class SpringRestTemplateUnitTest {
|
public class SpringRestTemplateUnitTest {
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
package com.baeldung.httpclient.readresponsebodystring;
|
package com.baeldung.httpclient.readresponsebodystring;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.springframework.web.reactive.function.client.WebClient;
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
import reactor.core.publisher.Mono;
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
@ -8,7 +8,7 @@ public class SpringWebClientUnitTest {
|
||||||
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUseWebClientRetrieve_thenCorrect() {
|
void whenUseWebClientRetrieve_thenCorrect() {
|
||||||
WebClient webClient = WebClient.create(DUMMY_URL);
|
WebClient webClient = WebClient.create(DUMMY_URL);
|
||||||
Mono<String> body = webClient.get().retrieve().bodyToMono(String.class);
|
Mono<String> body = webClient.get().retrieve().bodyToMono(String.class);
|
||||||
String s = body.block();
|
String s = body.block();
|
||||||
|
|
|
@ -15,45 +15,6 @@
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<!-- http client -->
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.httpcomponents</groupId>
|
|
||||||
<artifactId>httpclient</artifactId>
|
|
||||||
<version>${httpclient.version}</version>
|
|
||||||
<exclusions>
|
|
||||||
<exclusion>
|
|
||||||
<artifactId>commons-logging</artifactId>
|
|
||||||
<groupId>commons-logging</groupId>
|
|
||||||
</exclusion>
|
|
||||||
</exclusions>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.httpcomponents</groupId>
|
|
||||||
<artifactId>fluent-hc</artifactId>
|
|
||||||
<version>${httpclient.version}</version>
|
|
||||||
<exclusions>
|
|
||||||
<exclusion>
|
|
||||||
<artifactId>commons-logging</artifactId>
|
|
||||||
<groupId>commons-logging</groupId>
|
|
||||||
</exclusion>
|
|
||||||
</exclusions>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.httpcomponents</groupId>
|
|
||||||
<artifactId>httpmime</artifactId>
|
|
||||||
<version>${httpclient.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.httpcomponents</groupId>
|
|
||||||
<artifactId>httpasyncclient</artifactId>
|
|
||||||
<version>${httpasyncclient.version}</version> <!-- 4.0.2 --> <!-- 4.1-beta1 -->
|
|
||||||
<exclusions>
|
|
||||||
<exclusion>
|
|
||||||
<artifactId>commons-logging</artifactId>
|
|
||||||
<groupId>commons-logging</groupId>
|
|
||||||
</exclusion>
|
|
||||||
</exclusions>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.apache.httpcomponents.core5</groupId>
|
<groupId>org.apache.httpcomponents.core5</groupId>
|
||||||
<artifactId>httpcore5</artifactId>
|
<artifactId>httpcore5</artifactId>
|
||||||
|
@ -115,12 +76,8 @@
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<!-- util -->
|
|
||||||
<httpasyncclient.version>4.1.4</httpasyncclient.version>
|
|
||||||
<!-- testing -->
|
|
||||||
<mockserver.version>5.6.1</mockserver.version>
|
<mockserver.version>5.6.1</mockserver.version>
|
||||||
<wiremock.version>2.5.1</wiremock.version>
|
<wiremock.version>2.5.1</wiremock.version>
|
||||||
<httpclient.version>4.5.8</httpclient.version> <!-- 4.3.6 --> <!-- 4.4-beta1 -->
|
|
||||||
<!-- http client & core 5 -->
|
<!-- http client & core 5 -->
|
||||||
<httpcore5.version>5.2</httpcore5.version>
|
<httpcore5.version>5.2</httpcore5.version>
|
||||||
<httpclient5.version>5.2</httpclient5.version>
|
<httpclient5.version>5.2</httpclient5.version>
|
||||||
|
|
|
@ -4,10 +4,10 @@ import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
import org.apache.hc.core5.http.ParseException;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
|
||||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||||
import org.apache.hc.client5.http.entity.mime.FileBody;
|
import org.apache.hc.client5.http.entity.mime.FileBody;
|
||||||
import org.apache.hc.client5.http.entity.mime.HttpMultipartMode;
|
import org.apache.hc.client5.http.entity.mime.HttpMultipartMode;
|
||||||
|
@ -19,6 +19,7 @@ import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
|
||||||
import org.apache.hc.core5.http.ContentType;
|
import org.apache.hc.core5.http.ContentType;
|
||||||
import org.apache.hc.core5.http.HttpEntity;
|
import org.apache.hc.core5.http.HttpEntity;
|
||||||
import org.apache.hc.core5.http.HttpStatus;
|
import org.apache.hc.core5.http.HttpStatus;
|
||||||
|
import org.apache.hc.core5.http.ParseException;
|
||||||
|
|
||||||
import java.io.BufferedReader;
|
import java.io.BufferedReader;
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
|
@ -30,9 +31,6 @@ import java.net.URL;
|
||||||
|
|
||||||
class HttpClientMultipartLiveTest extends GetRequestMockServer {
|
class HttpClientMultipartLiveTest extends GetRequestMockServer {
|
||||||
|
|
||||||
// No longer available
|
|
||||||
// private static final String SERVER = "http://echo.200please.com";
|
|
||||||
|
|
||||||
private static final String SERVER = "http://localhost:8080/spring-mvc-java/stub/multipart";
|
private static final String SERVER = "http://localhost:8080/spring-mvc-java/stub/multipart";
|
||||||
private static final String TEXTFILENAME = "temp.txt";
|
private static final String TEXTFILENAME = "temp.txt";
|
||||||
private static final String IMAGEFILENAME = "image.jpg";
|
private static final String IMAGEFILENAME = "image.jpg";
|
||||||
|
|
|
@ -1,15 +1,16 @@
|
||||||
package com.baeldung.httpclient;
|
package com.baeldung.httpclient;
|
||||||
|
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
||||||
import org.apache.hc.client5.http.impl.DefaultRedirectStrategy;
|
import org.apache.hc.client5.http.impl.DefaultRedirectStrategy;
|
||||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||||
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
|
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
|
||||||
import org.apache.hc.client5.http.impl.classic.HttpClients;
|
import org.apache.hc.client5.http.impl.classic.HttpClients;
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import static org.hamcrest.MatcherAssert.assertThat;
|
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
|
|
|
@ -8,7 +8,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
|
||||||
import static com.github.tomakehurst.wiremock.client.WireMock.post;
|
import static com.github.tomakehurst.wiremock.client.WireMock.post;
|
||||||
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
||||||
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
|
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
|
@ -29,21 +29,34 @@ import org.apache.hc.core5.http.HttpHeaders;
|
||||||
import org.apache.hc.core5.http.HttpHost;
|
import org.apache.hc.core5.http.HttpHost;
|
||||||
import org.apache.hc.core5.http.HttpResponse;
|
import org.apache.hc.core5.http.HttpResponse;
|
||||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
import org.apache.hc.core5.http.io.entity.StringEntity;
|
||||||
import org.junit.Rule;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import com.github.tomakehurst.wiremock.junit.WireMockRule;
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
public class HttpClientAdvancedConfigurationIntegrationTest {
|
import com.github.tomakehurst.wiremock.WireMockServer;
|
||||||
|
|
||||||
@Rule
|
class HttpClientAdvancedConfigurationIntegrationTest {
|
||||||
public WireMockRule serviceMock = new WireMockRule(8089);
|
|
||||||
|
|
||||||
@Rule
|
public WireMockServer serviceMock;
|
||||||
public WireMockRule proxyMock = new WireMockRule(8090);
|
public WireMockServer proxyMock;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
public void before () {
|
||||||
|
serviceMock = new WireMockServer(8089);
|
||||||
|
serviceMock.start();
|
||||||
|
proxyMock = new WireMockServer(8090);
|
||||||
|
proxyMock.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
public void after () {
|
||||||
|
serviceMock.stop();
|
||||||
|
proxyMock.stop();
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException {
|
void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException {
|
||||||
//given
|
//given
|
||||||
String userAgent = "BaeldungAgent/1.0";
|
String userAgent = "BaeldungAgent/1.0";
|
||||||
serviceMock.stubFor(get(urlEqualTo("/detail"))
|
serviceMock.stubFor(get(urlEqualTo("/detail"))
|
||||||
|
@ -59,11 +72,11 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||||
HttpResponse response = httpClient.execute(httpGet);
|
HttpResponse response = httpClient.execute(httpGet);
|
||||||
|
|
||||||
//then
|
//then
|
||||||
assertEquals(response.getCode(), 200);
|
assertEquals(200, response.getCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException {
|
void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException {
|
||||||
//given
|
//given
|
||||||
String xmlBody = "<xml><id>1</id></xml>";
|
String xmlBody = "<xml><id>1</id></xml>";
|
||||||
serviceMock.stubFor(post(urlEqualTo("/person"))
|
serviceMock.stubFor(post(urlEqualTo("/person"))
|
||||||
|
@ -82,12 +95,12 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||||
HttpResponse response = httpClient.execute(httpPost);
|
HttpResponse response = httpClient.execute(httpPost);
|
||||||
|
|
||||||
//then
|
//then
|
||||||
assertEquals(response.getCode(), 200);
|
assertEquals(200, response.getCode());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException {
|
void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException {
|
||||||
//given
|
//given
|
||||||
proxyMock.stubFor(get(urlMatching(".*"))
|
proxyMock.stubFor(get(urlMatching(".*"))
|
||||||
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
|
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
|
||||||
|
@ -107,7 +120,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||||
HttpResponse response = httpclient.execute(httpGet);
|
HttpResponse response = httpclient.execute(httpGet);
|
||||||
|
|
||||||
//then
|
//then
|
||||||
assertEquals(response.getCode(), 200);
|
assertEquals(200, response.getCode());
|
||||||
proxyMock.verify(getRequestedFor(urlEqualTo("/private")));
|
proxyMock.verify(getRequestedFor(urlEqualTo("/private")));
|
||||||
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
|
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
|
||||||
}
|
}
|
||||||
|
@ -151,7 +164,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||||
HttpResponse response = httpclient.execute(httpGet, context);
|
HttpResponse response = httpclient.execute(httpGet, context);
|
||||||
|
|
||||||
//then
|
//then
|
||||||
assertEquals(response.getCode(), 200);
|
assertEquals(200, response.getCode());
|
||||||
proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic")));
|
proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic")));
|
||||||
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
|
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,59 +0,0 @@
|
||||||
package com.baeldung.httpclient.base;
|
|
||||||
|
|
||||||
import com.baeldung.httpclient.ResponseUtil;
|
|
||||||
import org.apache.http.auth.AuthenticationException;
|
|
||||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
|
||||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
|
||||||
import org.apache.http.client.methods.HttpPost;
|
|
||||||
import org.apache.http.entity.StringEntity;
|
|
||||||
import org.apache.http.impl.auth.BasicScheme;
|
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
|
||||||
import org.apache.http.impl.client.HttpClientBuilder;
|
|
||||||
import org.junit.After;
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
public class HttpClientBasicPostLiveTest {
|
|
||||||
|
|
||||||
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 - non-GET
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public final void whenExecutingPostRequest_thenNoExceptions() throws IOException {
|
|
||||||
instance.execute(new HttpPost(SAMPLE_URL));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException {
|
|
||||||
final HttpPost request = new HttpPost(SAMPLE_URL);
|
|
||||||
request.setEntity(new StringEntity("in the body of the POST"));
|
|
||||||
instance.execute(request);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException, AuthenticationException {
|
|
||||||
final HttpPost request = new HttpPost(SAMPLE_URL);
|
|
||||||
request.setEntity(new StringEntity("in the body of the POST"));
|
|
||||||
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password");
|
|
||||||
request.addHeader(new BasicScheme().authenticate(creds, request, null));
|
|
||||||
instance.execute(request);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,75 +0,0 @@
|
||||||
package com.baeldung.httpclient.base;
|
|
||||||
|
|
||||||
import com.baeldung.httpclient.ResponseUtil;
|
|
||||||
|
|
||||||
import org.apache.http.Header;
|
|
||||||
import org.apache.http.HttpHeaders;
|
|
||||||
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.HttpClientBuilder;
|
|
||||||
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
|
|
||||||
import org.junit.After;
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
import static org.hamcrest.Matchers.emptyArray;
|
|
||||||
import static org.hamcrest.Matchers.not;
|
|
||||||
import static org.junit.Assert.assertThat;
|
|
||||||
|
|
||||||
public class HttpClientLiveTest {
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
@Test(expected = ConnectTimeoutException.class)
|
|
||||||
public final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws IOException {
|
|
||||||
final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5).setConnectTimeout(5).setSocketTimeout(2).build();
|
|
||||||
final HttpGet request = new HttpGet(SAMPLE_URL);
|
|
||||||
request.setConfig(requestConfig);
|
|
||||||
response = instance.execute(request);
|
|
||||||
}
|
|
||||||
|
|
||||||
// tests - configs
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public final void givenHttpClientIsConfiguredWithCustomConnectionManager_whenExecutingRequest_thenNoExceptions() throws IOException {
|
|
||||||
instance = HttpClientBuilder.create().setConnectionManager(new BasicHttpClientConnectionManager()).build();
|
|
||||||
response = instance.execute(new HttpGet(SAMPLE_URL));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public final void givenCustomHeaderIsSet_whenSendingRequest_thenNoExceptions() throws IOException {
|
|
||||||
final HttpGet request = new HttpGet(SAMPLE_URL);
|
|
||||||
request.addHeader(HttpHeaders.ACCEPT, "application/xml");
|
|
||||||
response = instance.execute(request);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public final void givenRequestWasSet_whenAnalyzingTheHeadersOfTheResponse_thenCorrect() throws IOException {
|
|
||||||
response = instance.execute(new HttpGet(SAMPLE_URL));
|
|
||||||
|
|
||||||
final Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
|
|
||||||
assertThat(headers, not(emptyArray()));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -1,5 +1,6 @@
|
||||||
package com.baeldung.httpclient.conn;
|
package com.baeldung.httpclient.conn;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
@ -34,14 +35,13 @@ import org.apache.hc.core5.pool.PoolStats;
|
||||||
import org.apache.hc.core5.util.Args;
|
import org.apache.hc.core5.util.Args;
|
||||||
import org.apache.hc.core5.util.TimeValue;
|
import org.apache.hc.core5.util.TimeValue;
|
||||||
import org.apache.hc.core5.util.Timeout;
|
import org.apache.hc.core5.util.Timeout;
|
||||||
import org.junit.Assert;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class HttpClientConnectionManagementLiveTest {
|
class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
// Example 2.1. Getting a Connection Request for a Low Level Connection (HttpClientConnection)
|
// Example 2.1. Getting a Connection Request for a Low Level Connection (HttpClientConnection)
|
||||||
@Test
|
@Test
|
||||||
public final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws ExecutionException, InterruptedException, TimeoutException {
|
final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws ExecutionException, InterruptedException, TimeoutException {
|
||||||
BasicHttpClientConnectionManager connMgr = new BasicHttpClientConnectionManager();
|
BasicHttpClientConnectionManager connMgr = new BasicHttpClientConnectionManager();
|
||||||
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 443));
|
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 443));
|
||||||
final LeaseRequest connRequest = connMgr.lease("some-id", route, null);
|
final LeaseRequest connRequest = connMgr.lease("some-id", route, null);
|
||||||
|
@ -51,7 +51,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
// Example 3.1. Setting the PoolingHttpClientConnectionManager on a HttpClient
|
// Example 3.1. Setting the PoolingHttpClientConnectionManager on a HttpClient
|
||||||
@Test
|
@Test
|
||||||
public final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws IOException {
|
final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws IOException {
|
||||||
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
|
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
|
||||||
CloseableHttpClient client = HttpClients.custom()
|
CloseableHttpClient client = HttpClients.custom()
|
||||||
.setConnectionManager(poolingConnManager)
|
.setConnectionManager(poolingConnManager)
|
||||||
|
@ -65,7 +65,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
// Example 3.2. Using Two HttpClients to Connect to One Target Host Each
|
// Example 3.2. Using Two HttpClients to Connect to One Target Host Each
|
||||||
@Test
|
@Test
|
||||||
public final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException, IOException {
|
final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException, IOException {
|
||||||
HttpGet get1 = new HttpGet("https://www.baeldung.com");
|
HttpGet get1 = new HttpGet("https://www.baeldung.com");
|
||||||
HttpGet get2 = new HttpGet("https://www.google.com");
|
HttpGet get2 = new HttpGet("https://www.google.com");
|
||||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||||
|
@ -83,8 +83,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
thread1.join();
|
thread1.join();
|
||||||
thread2.join();
|
thread2.join();
|
||||||
|
|
||||||
Assert.assertTrue(connManager.getTotalStats()
|
assertEquals(0, connManager.getTotalStats().getLeased());
|
||||||
.getLeased() == 0);
|
|
||||||
client1.close();
|
client1.close();
|
||||||
client2.close();
|
client2.close();
|
||||||
connManager.close();
|
connManager.close();
|
||||||
|
@ -92,7 +91,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
// Example 4.1. Increasing the Number of Connections that Can be Open and Managed Beyond the default Limits
|
// Example 4.1. Increasing the Number of Connections that Can be Open and Managed Beyond the default Limits
|
||||||
@Test
|
@Test
|
||||||
public final void whenIncreasingConnectionPool_thenNoExceptions() {
|
final void whenIncreasingConnectionPool_thenNoExceptions() {
|
||||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||||
connManager.setMaxTotal(5);
|
connManager.setMaxTotal(5);
|
||||||
connManager.setDefaultMaxPerRoute(4);
|
connManager.setDefaultMaxPerRoute(4);
|
||||||
|
@ -103,7 +102,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
// Example 4.2. Using Threads to Execute Connections
|
// Example 4.2. Using Threads to Execute Connections
|
||||||
@Test
|
@Test
|
||||||
public final void whenExecutingSameRequestsInDifferentThreads_thenExecuteRequest() throws InterruptedException, IOException {
|
final void whenExecutingSameRequestsInDifferentThreads_thenExecuteRequest() throws InterruptedException, IOException {
|
||||||
HttpGet get = new HttpGet("http://www.baeldung.com");
|
HttpGet get = new HttpGet("http://www.baeldung.com");
|
||||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||||
CloseableHttpClient client = HttpClients.custom()
|
CloseableHttpClient client = HttpClients.custom()
|
||||||
|
@ -133,7 +132,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
// Example 5.1. A Custom Keep Alive Strategy
|
// Example 5.1. A Custom Keep Alive Strategy
|
||||||
@Test
|
@Test
|
||||||
public final void whenCustomizingKeepAliveStrategy_thenNoExceptions() {
|
final void whenCustomizingKeepAliveStrategy_thenNoExceptions() {
|
||||||
final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
|
final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
|
||||||
@Override
|
@Override
|
||||||
public TimeValue getKeepAliveDuration(HttpResponse response, HttpContext context) {
|
public TimeValue getKeepAliveDuration(HttpResponse response, HttpContext context) {
|
||||||
|
@ -162,7 +161,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
//Example 6.1. BasicHttpClientConnectionManager Connection Reuse
|
//Example 6.1. BasicHttpClientConnectionManager Connection Reuse
|
||||||
@Test
|
@Test
|
||||||
public final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws InterruptedException, ExecutionException, TimeoutException, IOException, URISyntaxException {
|
final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws InterruptedException, ExecutionException, TimeoutException, IOException, URISyntaxException {
|
||||||
BasicHttpClientConnectionManager connMgr = new BasicHttpClientConnectionManager();
|
BasicHttpClientConnectionManager connMgr = new BasicHttpClientConnectionManager();
|
||||||
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 443));
|
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 443));
|
||||||
final HttpContext context = new BasicHttpContext();
|
final HttpContext context = new BasicHttpContext();
|
||||||
|
@ -184,7 +183,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
// Example 6.2. PoolingHttpClientConnectionManager: Re-Using Connections with Threads
|
// Example 6.2. PoolingHttpClientConnectionManager: Re-Using Connections with Threads
|
||||||
@Test
|
@Test
|
||||||
public final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException, IOException {
|
final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException, IOException {
|
||||||
HttpGet get = new HttpGet("http://www.baeldung.com");
|
HttpGet get = new HttpGet("http://www.baeldung.com");
|
||||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||||
connManager.setDefaultMaxPerRoute(6);
|
connManager.setDefaultMaxPerRoute(6);
|
||||||
|
@ -208,7 +207,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
// Example 7.1. Setting Socket Timeout to 5 Seconds
|
// Example 7.1. Setting Socket Timeout to 5 Seconds
|
||||||
@Test
|
@Test
|
||||||
public final void whenConfiguringTimeOut_thenNoExceptions() throws ExecutionException, InterruptedException, TimeoutException, IOException {
|
final void whenConfiguringTimeOut_thenNoExceptions() throws ExecutionException, InterruptedException, TimeoutException, IOException {
|
||||||
final HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80));
|
final HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80));
|
||||||
final HttpContext context = new BasicHttpContext();
|
final HttpContext context = new BasicHttpContext();
|
||||||
final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||||
|
@ -227,7 +226,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
// Example 8.1. Setting the HttpClient to Check for Stale Connections
|
// Example 8.1. Setting the HttpClient to Check for Stale Connections
|
||||||
@Test
|
@Test
|
||||||
public final void whenEvictIdealConn_thenNoExceptions() throws InterruptedException, IOException {
|
final void whenEvictIdealConn_thenNoExceptions() throws InterruptedException, IOException {
|
||||||
final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||||
connManager.setMaxTotal(100);
|
connManager.setMaxTotal(100);
|
||||||
try (final CloseableHttpClient httpclient = HttpClients.custom()
|
try (final CloseableHttpClient httpclient = HttpClients.custom()
|
||||||
|
@ -266,7 +265,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
// Example 9.1. Closing Connection and Releasing Resources
|
// Example 9.1. Closing Connection and Releasing Resources
|
||||||
@Test
|
@Test
|
||||||
public final void whenClosingConnectionsandManager_thenCloseWithNoExceptions1() throws IOException {
|
final void whenClosingConnectionsAndManager_thenCloseWithNoExceptions1() throws IOException {
|
||||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||||
CloseableHttpClient client = HttpClients.custom()
|
CloseableHttpClient client = HttpClients.custom()
|
||||||
.setConnectionManager(connManager)
|
.setConnectionManager(connManager)
|
||||||
|
@ -282,7 +281,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
// Example 3.2. TESTER VERSION
|
// Example 3.2. TESTER VERSION
|
||||||
public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException, IOException {
|
final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException, IOException {
|
||||||
HttpGet get1 = new HttpGet("https://www.baeldung.com");
|
HttpGet get1 = new HttpGet("https://www.baeldung.com");
|
||||||
HttpGet get2 = new HttpGet("https://www.google.com");
|
HttpGet get2 = new HttpGet("https://www.google.com");
|
||||||
|
|
||||||
|
@ -300,8 +299,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
thread2.start();
|
thread2.start();
|
||||||
thread1.join();
|
thread1.join();
|
||||||
thread2.join(1000);
|
thread2.join(1000);
|
||||||
Assert.assertTrue(poolingConnManager.getTotalStats()
|
assertEquals(2, poolingConnManager.getTotalStats().getLeased());
|
||||||
.getLeased() == 2);
|
|
||||||
|
|
||||||
client1.close();
|
client1.close();
|
||||||
client2.close();
|
client2.close();
|
||||||
|
|
|
@ -1,41 +0,0 @@
|
||||||
package com.baeldung.httpclient.conn;
|
|
||||||
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
|
|
||||||
import org.apache.http.conn.HttpClientConnectionManager;
|
|
||||||
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
|
||||||
|
|
||||||
public class IdleConnectionMonitorThread extends Thread {
|
|
||||||
private final HttpClientConnectionManager connMgr;
|
|
||||||
private volatile boolean shutdown;
|
|
||||||
|
|
||||||
IdleConnectionMonitorThread(final PoolingHttpClientConnectionManager connMgr) {
|
|
||||||
super();
|
|
||||||
this.connMgr = connMgr;
|
|
||||||
}
|
|
||||||
|
|
||||||
// API
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public final void run() {
|
|
||||||
try {
|
|
||||||
while (!shutdown) {
|
|
||||||
synchronized (this) {
|
|
||||||
wait(1000);
|
|
||||||
connMgr.closeExpiredConnections();
|
|
||||||
connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (final InterruptedException ex) {
|
|
||||||
shutdown();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void shutdown() {
|
|
||||||
shutdown = true;
|
|
||||||
synchronized (this) {
|
|
||||||
notifyAll();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
|
@ -6,7 +6,6 @@ import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||||
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
|
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
|
||||||
import org.apache.hc.core5.http.HttpEntity;
|
import org.apache.hc.core5.http.HttpEntity;
|
||||||
import org.apache.hc.core5.http.HttpResponse;
|
|
||||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
package com.baeldung.httpclient.base;
|
package com.baeldung.client;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
import com.baeldung.httpclient.GetRequestMockServer;
|
|
||||||
import com.baeldung.httpclient.ResponseUtil;
|
|
||||||
import org.apache.http.auth.AuthScope;
|
import org.apache.http.auth.AuthScope;
|
||||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||||
import org.apache.http.client.CredentialsProvider;
|
import org.apache.http.client.CredentialsProvider;
|
||||||
|
@ -12,15 +12,16 @@ import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.apache.http.impl.client.HttpClientBuilder;
|
import org.apache.http.impl.client.HttpClientBuilder;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import java.io.IOException;
|
import com.baeldung.GetRequestMockServer;
|
||||||
|
import com.baeldung.httpclient.ResponseUtil;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* NOTE : Need module spring-security-rest-basic-auth to be running
|
* NOTE : Need module spring-security-rest-basic-auth to be running
|
||||||
*/
|
*/
|
||||||
public class HttpClientSandboxLiveTest extends GetRequestMockServer {
|
class HttpClientSandboxLiveTest extends GetRequestMockServer {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException {
|
final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException {
|
||||||
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
|
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
|
||||||
final AuthScope authscp = new AuthScope("localhost", 8080);
|
final AuthScope authscp = new AuthScope("localhost", 8080);
|
||||||
credentialsProvider.setCredentials(authscp, new UsernamePasswordCredentials("user1", "user1Pass"));
|
credentialsProvider.setCredentials(authscp, new UsernamePasswordCredentials("user1", "user1Pass"));
|
|
@ -35,7 +35,7 @@ import org.springframework.web.client.RestTemplate;
|
||||||
* This test requires a localhost server over HTTPS <br>
|
* This test requires a localhost server over HTTPS <br>
|
||||||
* It should only be manually run, not part of the automated build
|
* It should only be manually run, not part of the automated build
|
||||||
* */
|
* */
|
||||||
public class RestClientV4LiveManualTest {
|
class RestClientV4LiveManualTest {
|
||||||
|
|
||||||
final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1";
|
final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1";
|
||||||
|
|
||||||
|
@ -81,7 +81,7 @@ public class RestClientV4LiveManualTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException {
|
void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException {
|
||||||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||||||
String urlOverHttps = "https://localhost:8082/httpclient-simple";
|
String urlOverHttps = "https://localhost:8082/httpclient-simple";
|
||||||
HttpGet getMethod = new HttpGet(urlOverHttps);
|
HttpGet getMethod = new HttpGet(urlOverHttps);
|
||||||
|
|
|
@ -2,8 +2,6 @@ package com.baeldung.httpclient;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
import org.apache.http.HttpEntity;
|
|
||||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
|
|
||||||
public final class ClientUtil {
|
public final class ClientUtil {
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
package com.baeldung.httpclient;
|
package com.baeldung.httpclient;
|
||||||
|
|
||||||
import static org.hamcrest.MatcherAssert.assertThat;
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
|
|
||||||
|
|
|
@ -9,11 +9,11 @@ import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.apache.http.impl.client.HttpClientBuilder;
|
import org.apache.http.impl.client.HttpClientBuilder;
|
||||||
import org.apache.http.impl.client.HttpClients;
|
import org.apache.http.impl.client.HttpClients;
|
||||||
|
|
||||||
import org.junit.After;
|
import org.junit.jupiter.api.AfterEach;
|
||||||
import org.junit.Before;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
public class HttpClientCancelRequestV4LiveTest {
|
class HttpClientCancelRequestV4LiveTest {
|
||||||
|
|
||||||
private static final String SAMPLE_URL = "http://www.github.com";
|
private static final String SAMPLE_URL = "http://www.github.com";
|
||||||
|
|
||||||
|
@ -21,18 +21,18 @@ public class HttpClientCancelRequestV4LiveTest {
|
||||||
|
|
||||||
private CloseableHttpResponse response;
|
private CloseableHttpResponse response;
|
||||||
|
|
||||||
@Before
|
@BeforeEach
|
||||||
public final void before() {
|
public final void before() {
|
||||||
instance = HttpClientBuilder.create().build();
|
instance = HttpClientBuilder.create().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@After
|
@AfterEach
|
||||||
public final void after() throws IllegalStateException, IOException {
|
public final void after() throws IllegalStateException, IOException {
|
||||||
ResponseUtil.closeResponse(response);
|
ResponseUtil.closeResponse(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void whenRequestIsCanceled_thenCorrect() throws IOException {
|
final void whenRequestIsCanceled_thenCorrect() throws IOException {
|
||||||
instance = HttpClients.custom().build();
|
instance = HttpClients.custom().build();
|
||||||
final HttpGet request = new HttpGet(SAMPLE_URL);
|
final HttpGet request = new HttpGet(SAMPLE_URL);
|
||||||
response = instance.execute(request);
|
response = instance.execute(request);
|
||||||
|
|
|
@ -1,5 +1,9 @@
|
||||||
package com.baeldung.httpclient;
|
package com.baeldung.httpclient;
|
||||||
|
|
||||||
|
import org.apache.http.auth.AuthenticationException;
|
||||||
|
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||||
|
import org.apache.http.entity.StringEntity;
|
||||||
|
import org.apache.http.impl.auth.BasicScheme;
|
||||||
import org.junit.jupiter.api.AfterEach;
|
import org.junit.jupiter.api.AfterEach;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
@ -181,4 +185,20 @@ class HttpClientCookBookV4LiveTest {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
final void whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException {
|
||||||
|
final HttpPost request = new HttpPost(SAMPLE_POST_URL);
|
||||||
|
request.setEntity(new StringEntity("in the body of the POST"));
|
||||||
|
client.execute(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws IOException, AuthenticationException {
|
||||||
|
final HttpPost request = new HttpPost(SAMPLE_POST_URL);
|
||||||
|
request.setEntity(new StringEntity("in the body of the POST"));
|
||||||
|
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password");
|
||||||
|
request.addHeader(new BasicScheme().authenticate(creds, request, null));
|
||||||
|
client.execute(request);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
package com.baeldung.httpclient;
|
package com.baeldung.httpclient;
|
||||||
|
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
|
|
||||||
import org.junit.jupiter.api.AfterEach;
|
import org.junit.jupiter.api.AfterEach;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import static org.hamcrest.MatcherAssert.assertThat;
|
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||||
|
|
|
@ -92,6 +92,26 @@ class HttpClientTimeoutV4LiveTest extends GetRequestMockServer {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
final void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() {
|
||||||
|
final RequestConfig requestConfig = RequestConfig.custom()
|
||||||
|
.setConnectionRequestTimeout(5)
|
||||||
|
.setConnectTimeout(5)
|
||||||
|
.setSocketTimeout(2)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
final CloseableHttpClient client = HttpClientBuilder.create()
|
||||||
|
.setDefaultRequestConfig(requestConfig)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
final HttpGet request = new HttpGet("http://www.github.com");
|
||||||
|
|
||||||
|
assertThrows(ConnectTimeoutException.class, () -> {
|
||||||
|
response = client.execute(request);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void whenSecuredRestApiIsConsumed_then200OK() throws IOException {
|
void whenSecuredRestApiIsConsumed_then200OK() throws IOException {
|
||||||
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
|
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
package com.baeldung.httpclient.advancedconfig;
|
package com.baeldung.httpclient.advancedconfig;
|
||||||
|
|
||||||
|
import com.github.tomakehurst.wiremock.WireMockServer;
|
||||||
|
|
||||||
import com.github.tomakehurst.wiremock.junit.WireMockRule;
|
|
||||||
import org.apache.http.HttpHeaders;
|
import org.apache.http.HttpHeaders;
|
||||||
import org.apache.http.HttpHost;
|
import org.apache.http.HttpHost;
|
||||||
import org.apache.http.HttpResponse;
|
import org.apache.http.HttpResponse;
|
||||||
|
@ -19,8 +19,10 @@ import org.apache.http.impl.client.BasicAuthCache;
|
||||||
import org.apache.http.impl.client.BasicCredentialsProvider;
|
import org.apache.http.impl.client.BasicCredentialsProvider;
|
||||||
import org.apache.http.impl.client.HttpClients;
|
import org.apache.http.impl.client.HttpClients;
|
||||||
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
|
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
|
||||||
import org.junit.Rule;
|
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
|
@ -32,18 +34,29 @@ import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
|
||||||
import static com.github.tomakehurst.wiremock.client.WireMock.post;
|
import static com.github.tomakehurst.wiremock.client.WireMock.post;
|
||||||
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
||||||
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
|
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
public class HttpClientAdvancedConfigurationIntegrationTest {
|
class HttpClientAdvancedConfigurationIntegrationTest {
|
||||||
|
|
||||||
@Rule
|
public WireMockServer serviceMock;
|
||||||
public WireMockRule serviceMock = new WireMockRule(8089);
|
public WireMockServer proxyMock;
|
||||||
|
|
||||||
@Rule
|
@BeforeEach
|
||||||
public WireMockRule proxyMock = new WireMockRule(8090);
|
public void before () {
|
||||||
|
serviceMock = new WireMockServer(8089);
|
||||||
|
serviceMock.start();
|
||||||
|
proxyMock = new WireMockServer(8090);
|
||||||
|
proxyMock.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
public void after () {
|
||||||
|
serviceMock.stop();
|
||||||
|
proxyMock.stop();
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException {
|
void givenClientWithCustomUserAgentHeader_whenExecuteRequest_shouldReturn200() throws IOException {
|
||||||
//given
|
//given
|
||||||
String userAgent = "BaeldungAgent/1.0";
|
String userAgent = "BaeldungAgent/1.0";
|
||||||
serviceMock.stubFor(get(urlEqualTo("/detail"))
|
serviceMock.stubFor(get(urlEqualTo("/detail"))
|
||||||
|
@ -59,11 +72,11 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||||
HttpResponse response = httpClient.execute(httpGet);
|
HttpResponse response = httpClient.execute(httpGet);
|
||||||
|
|
||||||
//then
|
//then
|
||||||
assertEquals(response.getStatusLine().getStatusCode(), 200);
|
assertEquals(200, response.getStatusLine().getStatusCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException {
|
void givenClientThatSendDataInBody_whenSendXmlInBody_shouldReturn200() throws IOException {
|
||||||
//given
|
//given
|
||||||
String xmlBody = "<xml><id>1</id></xml>";
|
String xmlBody = "<xml><id>1</id></xml>";
|
||||||
serviceMock.stubFor(post(urlEqualTo("/person"))
|
serviceMock.stubFor(post(urlEqualTo("/person"))
|
||||||
|
@ -82,12 +95,11 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||||
HttpResponse response = httpClient.execute(httpPost);
|
HttpResponse response = httpClient.execute(httpPost);
|
||||||
|
|
||||||
//then
|
//then
|
||||||
assertEquals(response.getStatusLine().getStatusCode(), 200);
|
assertEquals(200, response.getStatusLine().getStatusCode());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException {
|
void givenServerThatIsBehindProxy_whenClientIsConfiguredToSendRequestViaProxy_shouldReturn200() throws IOException {
|
||||||
//given
|
//given
|
||||||
proxyMock.stubFor(get(urlMatching(".*"))
|
proxyMock.stubFor(get(urlMatching(".*"))
|
||||||
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
|
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
|
||||||
|
@ -107,13 +119,13 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||||
HttpResponse response = httpclient.execute(httpGet);
|
HttpResponse response = httpclient.execute(httpGet);
|
||||||
|
|
||||||
//then
|
//then
|
||||||
assertEquals(response.getStatusLine().getStatusCode(), 200);
|
assertEquals(200, response.getStatusLine().getStatusCode());
|
||||||
proxyMock.verify(getRequestedFor(urlEqualTo("/private")));
|
proxyMock.verify(getRequestedFor(urlEqualTo("/private")));
|
||||||
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
|
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException {
|
void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException {
|
||||||
//given
|
//given
|
||||||
proxyMock.stubFor(get(urlMatching("/private"))
|
proxyMock.stubFor(get(urlMatching("/private"))
|
||||||
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
|
.willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
|
||||||
|
@ -152,7 +164,7 @@ public class HttpClientAdvancedConfigurationIntegrationTest {
|
||||||
HttpResponse response = httpclient.execute(httpGet, context);
|
HttpResponse response = httpclient.execute(httpGet, context);
|
||||||
|
|
||||||
//then
|
//then
|
||||||
assertEquals(response.getStatusLine().getStatusCode(), 200);
|
assertEquals(200, response.getStatusLine().getStatusCode());
|
||||||
proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic")));
|
proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic")));
|
||||||
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
|
serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
|
||||||
}
|
}
|
||||||
|
|
|
@ -12,34 +12,35 @@ import org.apache.http.client.methods.HttpHead;
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.apache.http.impl.client.HttpClientBuilder;
|
import org.apache.http.impl.client.HttpClientBuilder;
|
||||||
import org.apache.http.util.EntityUtils;
|
import org.apache.http.util.EntityUtils;
|
||||||
import org.junit.Before;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
import static org.hamcrest.Matchers.equalTo;
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
import static org.junit.Assert.assertThat;
|
|
||||||
|
|
||||||
public class HttpClientExpandUrlLiveTest {
|
|
||||||
|
class HttpClientExpandUrlLiveTest {
|
||||||
|
|
||||||
private CloseableHttpClient client;
|
private CloseableHttpClient client;
|
||||||
|
|
||||||
@Before
|
@BeforeEach
|
||||||
public final void before() {
|
public final void beforeEach() {
|
||||||
client = HttpClientBuilder.create().disableRedirectHandling().build();
|
client = HttpClientBuilder.create().disableRedirectHandling().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenShortenedOnce_whenUrlIsExpanded_thenCorrectResult() throws IOException {
|
final void givenShortenedOnce_whenUrlIsExpanded_thenCorrectResult() throws IOException {
|
||||||
final String expectedResult = "https://www.baeldung.com/rest-versioning";
|
final String expectedResult = "https://www.baeldung.com/rest-versioning";
|
||||||
final String actualResult = expandSingleLevel("http://bit.ly/3LScTri");
|
final String actualResult = expandSingleLevel("http://bit.ly/3LScTri");
|
||||||
assertThat(actualResult, equalTo(expectedResult));
|
assertThat(actualResult, equalTo(expectedResult));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenShortenedMultiple_whenUrlIsExpanded_thenCorrectResult() throws IOException {
|
final void givenShortenedMultiple_whenUrlIsExpanded_thenCorrectResult() throws IOException {
|
||||||
final String expectedResult = "https://www.baeldung.com/rest-versioning";
|
final String expectedResult = "https://www.baeldung.com/rest-versioning";
|
||||||
final String actualResult = expand("http://t.co/e4rDDbnzmk");
|
final String actualResult = expand("http://t.co/e4rDDbnzmk");
|
||||||
assertThat(actualResult, equalTo(expectedResult));
|
assertThat(actualResult, equalTo(expectedResult));
|
||||||
|
|
|
@ -17,7 +17,6 @@ import com.baeldung.GetRequestMockServer;
|
||||||
|
|
||||||
class ApacheHttpClientUnitTest extends GetRequestMockServer {
|
class ApacheHttpClientUnitTest extends GetRequestMockServer {
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void givenDeveloperUsedCloseableHttpResponse_whenExecutingGetRequest_thenStatusIsOk() throws IOException {
|
void givenDeveloperUsedCloseableHttpResponse_whenExecutingGetRequest_thenStatusIsOk() throws IOException {
|
||||||
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
|
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
|
||||||
|
|
|
@ -1,7 +1,9 @@
|
||||||
package com.baeldung.httpclient.httpclient.conn;
|
package com.baeldung.httpclient.httpclient.conn;
|
||||||
|
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.concurrent.ExecutionException;
|
import java.util.concurrent.ExecutionException;
|
||||||
|
@ -24,6 +26,7 @@ import org.apache.http.conn.ConnectionPoolTimeoutException;
|
||||||
import org.apache.http.conn.ConnectionRequest;
|
import org.apache.http.conn.ConnectionRequest;
|
||||||
import org.apache.http.conn.routing.HttpRoute;
|
import org.apache.http.conn.routing.HttpRoute;
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
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.client.HttpClients;
|
||||||
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
|
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
|
||||||
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
||||||
|
@ -33,14 +36,14 @@ import org.apache.http.protocol.HttpContext;
|
||||||
import org.apache.http.protocol.HttpCoreContext;
|
import org.apache.http.protocol.HttpCoreContext;
|
||||||
import org.apache.http.protocol.HttpRequestExecutor;
|
import org.apache.http.protocol.HttpRequestExecutor;
|
||||||
import org.apache.http.util.EntityUtils;
|
import org.apache.http.util.EntityUtils;
|
||||||
import org.junit.Ignore;
|
import org.junit.jupiter.api.Disabled;
|
||||||
import org.junit.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
public class HttpClientConnectionManagementLiveTest {
|
class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
// Example 2.1. Getting a Connection Request for a Low Level Connection (HttpClientConnection)
|
// Example 2.1. Getting a Connection Request for a Low Level Connection (HttpClientConnection)
|
||||||
@Test
|
@Test
|
||||||
public final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws ConnectionPoolTimeoutException, InterruptedException, ExecutionException {
|
final void whenLowLevelConnectionIsEstablished_thenNoExceptions() throws ConnectionPoolTimeoutException, InterruptedException, ExecutionException {
|
||||||
try (BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager()) {
|
try (BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager()) {
|
||||||
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80));
|
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80));
|
||||||
final ConnectionRequest connRequest = connManager.requestConnection(route, null);
|
final ConnectionRequest connRequest = connManager.requestConnection(route, null);
|
||||||
|
@ -50,20 +53,20 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
// Example 3.1. Setting the PoolingHttpClientConnectionManager on a HttpClient
|
// Example 3.1. Setting the PoolingHttpClientConnectionManager on a HttpClient
|
||||||
@Test
|
@Test
|
||||||
public final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws ClientProtocolException, IOException {
|
final void whenPollingConnectionManagerIsConfiguredOnHttpClient_thenNoExceptions() throws ClientProtocolException, IOException {
|
||||||
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
|
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
|
||||||
CloseableHttpClient client = HttpClients.custom()
|
CloseableHttpClient client = HttpClients.custom()
|
||||||
.setConnectionManager(poolingConnManager)
|
.setConnectionManager(poolingConnManager)
|
||||||
.build();
|
.build();
|
||||||
client.execute(new HttpGet("https://www.baeldung.com"));
|
client.execute(new HttpGet("https://www.baeldung.com"));
|
||||||
|
|
||||||
assertTrue(poolingConnManager.getTotalStats()
|
assertEquals(1, poolingConnManager.getTotalStats()
|
||||||
.getLeased() == 1);
|
.getLeased());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Example 3.2. Using Two HttpClients to Connect to One Target Host Each
|
// Example 3.2. Using Two HttpClients to Connect to One Target Host Each
|
||||||
@Test
|
@Test
|
||||||
public final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException {
|
final void whenTwoConnectionsForTwoRequests_thenNoExceptions() throws InterruptedException {
|
||||||
HttpGet get1 = new HttpGet("https://www.baeldung.com");
|
HttpGet get1 = new HttpGet("https://www.baeldung.com");
|
||||||
HttpGet get2 = new HttpGet("https://www.google.com");
|
HttpGet get2 = new HttpGet("https://www.google.com");
|
||||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||||
|
@ -81,13 +84,13 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
thread1.join();
|
thread1.join();
|
||||||
thread2.join();
|
thread2.join();
|
||||||
|
|
||||||
assertTrue(connManager.getTotalStats()
|
assertEquals(0, connManager.getTotalStats()
|
||||||
.getLeased() == 0);
|
.getLeased());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Example 4.1. Increasing the Number of Connections that Can be Open and Managed Beyond the default Limits
|
// Example 4.1. Increasing the Number of Connections that Can be Open and Managed Beyond the default Limits
|
||||||
@Test
|
@Test
|
||||||
public final void whenIncreasingConnectionPool_thenNoEceptions() {
|
final void whenIncreasingConnectionPool_thenNoEceptions() {
|
||||||
try (PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager()) {
|
try (PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager()) {
|
||||||
connManager.setMaxTotal(5);
|
connManager.setMaxTotal(5);
|
||||||
connManager.setDefaultMaxPerRoute(4);
|
connManager.setDefaultMaxPerRoute(4);
|
||||||
|
@ -98,7 +101,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
// Example 4.2. Using Threads to Execute Connections
|
// Example 4.2. Using Threads to Execute Connections
|
||||||
@Test
|
@Test
|
||||||
public final void whenExecutingSameRequestsInDifferentThreads_thenExecuteReuqest() throws InterruptedException {
|
final void whenExecutingSameRequestsInDifferentThreads_thenExecuteReuqest() throws InterruptedException {
|
||||||
HttpGet get = new HttpGet("http://www.baeldung.com");
|
HttpGet get = new HttpGet("http://www.baeldung.com");
|
||||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||||
CloseableHttpClient client = HttpClients.custom()
|
CloseableHttpClient client = HttpClients.custom()
|
||||||
|
@ -117,7 +120,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
// Example 5.1. A Custom Keep Alive Strategy
|
// Example 5.1. A Custom Keep Alive Strategy
|
||||||
@Test
|
@Test
|
||||||
public final void whenCustomizingKeepAliveStrategy_thenNoExceptions() {
|
final void whenCustomizingKeepAliveStrategy_thenNoExceptions() {
|
||||||
final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
|
final ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
|
||||||
@Override
|
@Override
|
||||||
public long getKeepAliveDuration(final HttpResponse myResponse, final HttpContext myContext) {
|
public long getKeepAliveDuration(final HttpResponse myResponse, final HttpContext myContext) {
|
||||||
|
@ -148,7 +151,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
// Example 6.1. BasicHttpClientConnectionManager Connection Reuse
|
// Example 6.1. BasicHttpClientConnectionManager Connection Reuse
|
||||||
@Test
|
@Test
|
||||||
public final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws IOException, HttpException, InterruptedException, ExecutionException {
|
final void givenBasicHttpClientConnManager_whenConnectionReuse_thenNoExceptions() throws IOException, HttpException, InterruptedException, ExecutionException {
|
||||||
BasicHttpClientConnectionManager basicConnManager = new BasicHttpClientConnectionManager();
|
BasicHttpClientConnectionManager basicConnManager = new BasicHttpClientConnectionManager();
|
||||||
HttpClientContext context = HttpClientContext.create();
|
HttpClientContext context = HttpClientContext.create();
|
||||||
|
|
||||||
|
@ -175,7 +178,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
// Example 6.2. PoolingHttpClientConnectionManager: Re-Using Connections with Threads
|
// Example 6.2. PoolingHttpClientConnectionManager: Re-Using Connections with Threads
|
||||||
@Test
|
@Test
|
||||||
public final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException {
|
final void whenConnectionsNeededGreaterThanMaxTotal_thenLeaseMasTotalandReuse() throws InterruptedException {
|
||||||
HttpGet get = new HttpGet("http://echo.200please.com");
|
HttpGet get = new HttpGet("http://echo.200please.com");
|
||||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||||
connManager.setDefaultMaxPerRoute(5);
|
connManager.setDefaultMaxPerRoute(5);
|
||||||
|
@ -197,20 +200,20 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
// Example 7.1. Setting Socket Timeout to 5 Seconds
|
// Example 7.1. Setting Socket Timeout to 5 Seconds
|
||||||
@Test
|
@Test
|
||||||
public final void whenConfiguringTimeOut_thenNoExceptions() {
|
final void whenConfiguringTimeOut_thenNoExceptions() {
|
||||||
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80));
|
HttpRoute route = new HttpRoute(new HttpHost("www.baeldung.com", 80));
|
||||||
try (PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager()) {
|
try (PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager()) {
|
||||||
connManager.setSocketConfig(route.getTargetHost(), SocketConfig.custom()
|
connManager.setSocketConfig(route.getTargetHost(), SocketConfig.custom()
|
||||||
.setSoTimeout(5000)
|
.setSoTimeout(5000)
|
||||||
.build());
|
.build());
|
||||||
assertTrue(connManager.getSocketConfig(route.getTargetHost())
|
assertEquals(5000, connManager.getSocketConfig(route.getTargetHost())
|
||||||
.getSoTimeout() == 5000);
|
.getSoTimeout());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Example 8.1. Setting the HttpClient to Check for Stale Connections
|
// Example 8.1. Setting the HttpClient to Check for Stale Connections
|
||||||
@Test
|
@Test
|
||||||
public final void whenHttpClientChecksStaleConns_thenNoExceptions() {
|
final void whenHttpClientChecksStaleConns_thenNoExceptions() {
|
||||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||||
HttpClients.custom()
|
HttpClients.custom()
|
||||||
.setDefaultRequestConfig(RequestConfig.custom()
|
.setDefaultRequestConfig(RequestConfig.custom()
|
||||||
|
@ -222,7 +225,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
// Example 8.2. Using a Stale Connection Monitor Thread
|
// Example 8.2. Using a Stale Connection Monitor Thread
|
||||||
@Test
|
@Test
|
||||||
public final void whenCustomizedIdleConnMonitor_thenNoExceptions() throws InterruptedException {
|
final void whenCustomizedIdleConnMonitor_thenNoExceptions() throws InterruptedException {
|
||||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||||
HttpClients.custom()
|
HttpClients.custom()
|
||||||
.setConnectionManager(connManager)
|
.setConnectionManager(connManager)
|
||||||
|
@ -233,8 +236,8 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Example 9.1. Closing Connection and Releasing Resources
|
// Example 9.1. Closing Connection and Releasing Resources
|
||||||
@Test(expected = IllegalStateException.class)
|
@Test
|
||||||
public final void whenClosingConnectionsandManager_thenCloseWithNoExceptions1() throws InterruptedException, ExecutionException, IOException, HttpException {
|
final void whenClosingConnectionsAndManager_thenCloseWithNoExceptions1() throws IOException {
|
||||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
|
||||||
CloseableHttpClient client = HttpClients.custom()
|
CloseableHttpClient client = HttpClients.custom()
|
||||||
.setConnectionManager(connManager)
|
.setConnectionManager(connManager)
|
||||||
|
@ -248,14 +251,14 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
connManager.close();
|
connManager.close();
|
||||||
connManager.shutdown();
|
connManager.shutdown();
|
||||||
|
|
||||||
client.execute(get);
|
assertThrows(IllegalStateException.class, () -> {
|
||||||
|
client.execute(get);
|
||||||
assertTrue(response.getEntity() == null);
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
// Example 3.2. TESTER VERSION
|
// Example 3.2. TESTER VERSION
|
||||||
public final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException {
|
final void whenTwoConnectionsForTwoRequests_thenTwoConnectionsAreLeased() throws InterruptedException {
|
||||||
HttpGet get1 = new HttpGet("https://www.baeldung.com");
|
HttpGet get1 = new HttpGet("https://www.baeldung.com");
|
||||||
HttpGet get2 = new HttpGet("https://www.google.com");
|
HttpGet get2 = new HttpGet("https://www.google.com");
|
||||||
|
|
||||||
|
@ -273,13 +276,13 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
thread2.start();
|
thread2.start();
|
||||||
thread1.join();
|
thread1.join();
|
||||||
thread2.join(1000);
|
thread2.join(1000);
|
||||||
assertTrue(poolingConnManager.getTotalStats()
|
assertEquals(2, poolingConnManager.getTotalStats()
|
||||||
.getLeased() == 2);
|
.getLeased());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
// Example 4.2 Tester Version
|
// Example 4.2 Tester Version
|
||||||
public final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException {
|
final void whenExecutingSameRequestsInDifferentThreads_thenUseDefaultConnLimit() throws InterruptedException {
|
||||||
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
|
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
|
||||||
CloseableHttpClient client = HttpClients.custom()
|
CloseableHttpClient client = HttpClients.custom()
|
||||||
.setConnectionManager(poolingConnManager)
|
.setConnectionManager(poolingConnManager)
|
||||||
|
@ -297,7 +300,7 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
// 6.2 TESTER VERSION
|
// 6.2 TESTER VERSION
|
||||||
public final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException {
|
final void whenConnectionsNeededGreaterThanMaxTotal_thenReuseConnections() throws InterruptedException {
|
||||||
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
|
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
|
||||||
poolingConnManager.setDefaultMaxPerRoute(5);
|
poolingConnManager.setDefaultMaxPerRoute(5);
|
||||||
poolingConnManager.setMaxTotal(5);
|
poolingConnManager.setMaxTotal(5);
|
||||||
|
@ -316,15 +319,15 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
thread.join(10000);
|
thread.join(10000);
|
||||||
countConnMade++;
|
countConnMade++;
|
||||||
if (countConnMade == 0) {
|
if (countConnMade == 0) {
|
||||||
assertTrue(thread.getLeasedConn() == 5);
|
assertEquals(5, thread.getLeasedConn());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@Ignore("Very Long Running")
|
@Disabled("Very Long Running")
|
||||||
// 8.2 TESTER VERSION
|
// 8.2 TESTER VERSION
|
||||||
public final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException {
|
final void whenCustomizedIdleConnMonitor_thenEliminateIdleConns() throws InterruptedException {
|
||||||
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
|
PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
|
||||||
CloseableHttpClient client = HttpClients.custom()
|
CloseableHttpClient client = HttpClients.custom()
|
||||||
.setConnectionManager(poolingConnManager)
|
.setConnectionManager(poolingConnManager)
|
||||||
|
@ -340,10 +343,10 @@ public class HttpClientConnectionManagementLiveTest {
|
||||||
thread2.start();
|
thread2.start();
|
||||||
thread2.join();
|
thread2.join();
|
||||||
thread3.start();
|
thread3.start();
|
||||||
assertTrue(poolingConnManager.getTotalStats()
|
assertEquals(1, poolingConnManager.getTotalStats()
|
||||||
.getAvailable() == 1);
|
.getAvailable());
|
||||||
thread3.join(32000);
|
thread3.join(32000);
|
||||||
assertTrue(poolingConnManager.getTotalStats()
|
assertEquals(0, poolingConnManager.getTotalStats()
|
||||||
.getAvailable() == 0);
|
.getAvailable());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,7 +3,6 @@ package com.baeldung.httpclient.httpclient.conn;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
import org.apache.http.HttpResponse;
|
import org.apache.http.HttpResponse;
|
||||||
import org.apache.http.client.ClientProtocolException;
|
|
||||||
import org.apache.http.client.methods.HttpGet;
|
import org.apache.http.client.methods.HttpGet;
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
||||||
|
|
|
@ -2,7 +2,6 @@ package com.baeldung.httpclient.httpclient.conn;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
import org.apache.http.client.ClientProtocolException;
|
|
||||||
import org.apache.http.client.methods.HttpGet;
|
import org.apache.http.client.methods.HttpGet;
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
||||||
|
|
|
@ -6,18 +6,19 @@ import org.apache.http.client.methods.HttpGet;
|
||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.apache.http.impl.client.HttpClients;
|
import org.apache.http.impl.client.HttpClients;
|
||||||
import org.apache.http.util.EntityUtils;
|
import org.apache.http.util.EntityUtils;
|
||||||
import org.junit.Test;
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
public class ApacheHttpClientUnitTest {
|
class ApacheHttpClientUnitTest {
|
||||||
private final Logger logger = LoggerFactory.getLogger(this.getClass());
|
private final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||||
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
public static final String DUMMY_URL = "https://postman-echo.com/get";
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenUseApacheHttpClient_thenCorrect() throws IOException {
|
void whenUseApacheHttpClient_thenCorrect() throws IOException {
|
||||||
HttpGet request = new HttpGet(DUMMY_URL);
|
HttpGet request = new HttpGet(DUMMY_URL);
|
||||||
|
|
||||||
try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(request)) {
|
try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(request)) {
|
||||||
|
|
|
@ -24,7 +24,7 @@ import org.junit.jupiter.api.AfterEach;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
public class ApacheHttpClientRetryLiveTest {
|
class ApacheHttpClientRetryLiveTest {
|
||||||
|
|
||||||
private Integer requestCounter;
|
private Integer requestCounter;
|
||||||
private CloseableHttpClient httpClient;
|
private CloseableHttpClient httpClient;
|
||||||
|
@ -93,14 +93,14 @@ public class ApacheHttpClientRetryLiveTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDefaultConfiguration_whenReceivedIOException_thenRetriesPerformed() {
|
void givenDefaultConfiguration_whenReceivedIOException_thenRetriesPerformed() {
|
||||||
createFailingHttpClient();
|
createFailingHttpClient();
|
||||||
assertThrows(IOException.class, () -> httpClient.execute(new HttpGet("https://httpstat.us/200")));
|
assertThrows(IOException.class, () -> httpClient.execute(new HttpGet("https://httpstat.us/200")));
|
||||||
assertThat(requestCounter).isEqualTo(4);
|
assertThat(requestCounter).isEqualTo(4);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDefaultConfiguration_whenDomainNameNotResolved_thenNoRetryApplied() {
|
void givenDefaultConfiguration_whenDomainNameNotResolved_thenNoRetryApplied() {
|
||||||
createDefaultApacheHttpClient();
|
createDefaultApacheHttpClient();
|
||||||
HttpGet request = new HttpGet(URI.create("http://domain.that.does.not.exist:80/api/v1"));
|
HttpGet request = new HttpGet(URI.create("http://domain.that.does.not.exist:80/api/v1"));
|
||||||
|
|
||||||
|
@ -109,7 +109,7 @@ public class ApacheHttpClientRetryLiveTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDefaultConfiguration_whenGotInternalServerError_thenNoRetryLogicApplied() throws IOException {
|
void givenDefaultConfiguration_whenGotInternalServerError_thenNoRetryLogicApplied() throws IOException {
|
||||||
createDefaultApacheHttpClient();
|
createDefaultApacheHttpClient();
|
||||||
HttpGet request = new HttpGet(URI.create("https://httpstat.us/500"));
|
HttpGet request = new HttpGet(URI.create("https://httpstat.us/500"));
|
||||||
|
|
||||||
|
@ -120,7 +120,7 @@ public class ApacheHttpClientRetryLiveTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDefaultConfiguration_whenHttpPatchRequest_thenRetryIsNotApplied() {
|
void givenDefaultConfiguration_whenHttpPatchRequest_thenRetryIsNotApplied() {
|
||||||
createFailingHttpClient();
|
createFailingHttpClient();
|
||||||
HttpPatch request = new HttpPatch(URI.create("https://httpstat.us/500"));
|
HttpPatch request = new HttpPatch(URI.create("https://httpstat.us/500"));
|
||||||
|
|
||||||
|
@ -129,7 +129,7 @@ public class ApacheHttpClientRetryLiveTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDefaultConfiguration_whenHttpPutRequest_thenRetryIsNotApplied() {
|
void givenDefaultConfiguration_whenHttpPutRequest_thenRetryIsNotApplied() {
|
||||||
createFailingHttpClient();
|
createFailingHttpClient();
|
||||||
HttpPut request = new HttpPut(URI.create("https://httpstat.us/500"));
|
HttpPut request = new HttpPut(URI.create("https://httpstat.us/500"));
|
||||||
|
|
||||||
|
@ -138,7 +138,7 @@ public class ApacheHttpClientRetryLiveTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenConfiguredRetryHandler_whenHttpPostRequest_thenRetriesPerformed() {
|
void givenConfiguredRetryHandler_whenHttpPostRequest_thenRetriesPerformed() {
|
||||||
createHttpClientWithRetryHandler();
|
createHttpClientWithRetryHandler();
|
||||||
|
|
||||||
HttpPost request = new HttpPost(URI.create("https://httpstat.us/200"));
|
HttpPost request = new HttpPost(URI.create("https://httpstat.us/200"));
|
||||||
|
@ -148,7 +148,7 @@ public class ApacheHttpClientRetryLiveTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenCustomRetryHandler_whenUnknownHostException_thenRetryAnyway() {
|
void givenCustomRetryHandler_whenUnknownHostException_thenRetryAnyway() {
|
||||||
createHttpClientWithCustomRetryHandler();
|
createHttpClientWithCustomRetryHandler();
|
||||||
|
|
||||||
HttpGet request = new HttpGet(URI.create("https://domain.that.does.not.exist/200"));
|
HttpGet request = new HttpGet(URI.create("https://domain.that.does.not.exist/200"));
|
||||||
|
@ -158,7 +158,7 @@ public class ApacheHttpClientRetryLiveTest {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenDisabledRetries_whenExecutedHttpRequestEndUpWithIOException_thenRetryIsNotApplied() {
|
void givenDisabledRetries_whenExecutedHttpRequestEndUpWithIOException_thenRetryIsNotApplied() {
|
||||||
createHttpClientWithRetriesDisabled();
|
createHttpClientWithRetriesDisabled();
|
||||||
HttpGet request = new HttpGet(URI.create("https://httpstat.us/200"));
|
HttpGet request = new HttpGet(URI.create("https://httpstat.us/200"));
|
||||||
|
|
||||||
|
|
|
@ -10,7 +10,7 @@
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-modules</artifactId>
|
<artifactId>parent-modules</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
<relativePath>../../</relativePath>
|
<relativePath>../../pom.xml</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
|
|
@ -4,9 +4,9 @@
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
<artifactId>core-java-9-jigsaw</artifactId>
|
<artifactId>core-java-9-jigsaw</artifactId>
|
||||||
<version>0.2-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<artifactId>library-core</artifactId>
|
<artifactId>library-core</artifactId>
|
||||||
|
|
|
@ -11,10 +11,9 @@
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
<artifactId>parent-modules</artifactId>
|
<artifactId>core-java-modules</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../../</relativePath>
|
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
|
|
@ -0,0 +1,16 @@
|
||||||
|
package com.baeldung.streams.regexmatches;
|
||||||
|
|
||||||
|
import java.util.regex.MatchResult;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
public class StreamFromRegexUtil {
|
||||||
|
|
||||||
|
public static Stream<String> getStream(String input, String regex) {
|
||||||
|
Pattern pattern = Pattern.compile(regex);
|
||||||
|
Matcher matcher = pattern.matcher(input);
|
||||||
|
return matcher.results().map(MatchResult::group);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
package com.baeldung.streams.regexmatches;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import static java.util.Arrays.asList;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class StreamFromRegexUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenInputStringIncludeLettersAndNumbersAndRegex_ThenReturnStreamOfNumbers() {
|
||||||
|
List<String> result = StreamFromRegexUtil.getStream("There are 3 apples and 2 bananas on the table.", "\\d+")
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
assertEquals(asList("3", "2"), result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenInputStringsAndRegex_ThenReturnStreamOfJavaWords() {
|
||||||
|
List<String> result = StreamFromRegexUtil.getStream("sample sentence with some words Java Java", "\\bJava\\b")
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
assertEquals(asList("Java", "Java"), result);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -13,4 +13,18 @@
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<argLine>
|
||||||
|
--add-opens java.base/java.nio=ALL-UNNAMED
|
||||||
|
</argLine>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -0,0 +1,67 @@
|
||||||
|
package com.baeldung.integertodigits;
|
||||||
|
|
||||||
|
import com.google.common.collect.Lists;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class IntegerToDigitsUnitTest {
|
||||||
|
private final static int THE_NUMBER = 1230456;
|
||||||
|
private final static List<Integer> EXPECTED_INT_LIST = Lists.newArrayList(1, 2, 3, 0, 4, 5, 6);
|
||||||
|
private final static String[] EXPECTED_STR_ARRAY = new String[] { "1", "2", "3", "0", "4", "5", "6" };
|
||||||
|
private final static List<String> EXPECTED_STR_LIST = Lists.newArrayList("1", "2", "3", "0", "4", "5", "6");
|
||||||
|
private final static char[] EXPECTED_CHAR_ARRAY = new char[] { '1', '2', '3', '0', '4', '5', '6' };
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingModOperator_thenGetExpectedResult() {
|
||||||
|
int number = THE_NUMBER;
|
||||||
|
LinkedList<Integer> result = new LinkedList<>();
|
||||||
|
while (number > 0) {
|
||||||
|
result.push(number % 10);
|
||||||
|
number /= 10;
|
||||||
|
}
|
||||||
|
assertEquals(EXPECTED_INT_LIST, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private void collectDigits(int num, List<Integer> digitList) {
|
||||||
|
if (num / 10 > 0) {
|
||||||
|
collectDigits(num / 10, digitList);
|
||||||
|
}
|
||||||
|
digitList.add(num % 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingModOperatorAndRecursion_thenGetExpectedResult() {
|
||||||
|
List<Integer> result = new ArrayList<>();
|
||||||
|
collectDigits(THE_NUMBER, result);
|
||||||
|
assertEquals(EXPECTED_INT_LIST, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingIntStream_thenGetExpectedResult() {
|
||||||
|
String numStr = String.valueOf(THE_NUMBER);
|
||||||
|
List<Integer> result = numStr.chars().map(Character::getNumericValue).boxed().collect(Collectors.toList());
|
||||||
|
assertEquals(EXPECTED_INT_LIST, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingToCharArray_thenGetExpectedResult() {
|
||||||
|
String numStr = String.valueOf(THE_NUMBER);
|
||||||
|
char[] result = numStr.toCharArray();
|
||||||
|
assertArrayEquals(EXPECTED_CHAR_ARRAY, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingSplit_thenGetExpectedResult() {
|
||||||
|
String numStr = String.valueOf(THE_NUMBER);
|
||||||
|
String[] result = numStr.split("(?<=.)");
|
||||||
|
assertArrayEquals(EXPECTED_STR_ARRAY, result);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,15 @@
|
||||||
|
#include <jni.h>
|
||||||
|
#include "CoreDump.h"
|
||||||
|
|
||||||
|
void core() {
|
||||||
|
int *p = NULL;
|
||||||
|
*p = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
JNIEXPORT void JNICALL Java_CoreDump_core (JNIEnv *env, jobject obj) {
|
||||||
|
core();
|
||||||
|
};
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,21 @@
|
||||||
|
/* DO NOT EDIT THIS FILE - it is machine generated */
|
||||||
|
#include <jni.h>
|
||||||
|
/* Header for class CoreDump */
|
||||||
|
|
||||||
|
#ifndef _Included_CoreDump
|
||||||
|
#define _Included_CoreDump
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
/*
|
||||||
|
* Class: CoreDump
|
||||||
|
* Method: core
|
||||||
|
* Signature: ()V
|
||||||
|
*/
|
||||||
|
JNIEXPORT void JNICALL Java_CoreDump_core
|
||||||
|
(JNIEnv *, jobject);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
#endif
|
|
@ -0,0 +1,13 @@
|
||||||
|
package com.baeldung.dumps;
|
||||||
|
|
||||||
|
public class CoreDump {
|
||||||
|
static {
|
||||||
|
System.loadLibrary("nativelib");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
new CoreDump().core();
|
||||||
|
}
|
||||||
|
|
||||||
|
private native void core();
|
||||||
|
}
|
|
@ -0,0 +1,19 @@
|
||||||
|
package com.baeldung.dumps;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class HeapDump {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
List<Integer> numbers = new ArrayList<>();
|
||||||
|
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
numbers.add(10);
|
||||||
|
}
|
||||||
|
} catch (OutOfMemoryError e) {
|
||||||
|
System.out.println("Out of memory error occurred!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
package com.baeldung.dumps;
|
||||||
|
|
||||||
|
public class ThreadDump {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
longRunningTask();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void longRunningTask() {
|
||||||
|
for (int i = 0; i < Integer.MAX_VALUE; i++) {
|
||||||
|
if (Thread.currentThread().isInterrupted()) {
|
||||||
|
System.out.println("Interrupted!");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
System.out.println(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
package com.baeldung.reflection.createobject.basic;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
|
||||||
|
public class BronzeJobCard {
|
||||||
|
private Object jobType;
|
||||||
|
public void setJobType(String jobType) throws ClassNotFoundException,
|
||||||
|
NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
|
||||||
|
Class jobTypeClass = Class.forName(jobType);
|
||||||
|
this.jobType = jobTypeClass.getDeclaredConstructor().newInstance();
|
||||||
|
}
|
||||||
|
public String startJob() {
|
||||||
|
if(this.jobType instanceof RepairJob) {
|
||||||
|
return "Start Bronze " + ((RepairJob) this.jobType).getJobType();
|
||||||
|
}
|
||||||
|
if(this.jobType instanceof MaintenanceJob) {
|
||||||
|
return "Start Bronze " + ((MaintenanceJob) this.jobType).getJobType();
|
||||||
|
}
|
||||||
|
return "Bronze Job Failed";
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
package com.baeldung.reflection.createobject.basic;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
|
||||||
|
public class GoldJobCard<T> {
|
||||||
|
private T jobType;
|
||||||
|
|
||||||
|
public void setJobType(Class<T> jobTypeClass) throws
|
||||||
|
NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
|
||||||
|
this.jobType = jobTypeClass.getDeclaredConstructor().newInstance();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String startJob() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
|
||||||
|
return "Start Gold " + this.jobType.getClass().getMethod("getJobType")
|
||||||
|
.invoke(this.jobType).toString();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,7 @@
|
||||||
|
package com.baeldung.reflection.createobject.basic;
|
||||||
|
|
||||||
|
public class MaintenanceJob {
|
||||||
|
public String getJobType() {
|
||||||
|
return "Maintenance Job";
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,7 @@
|
||||||
|
package com.baeldung.reflection.createobject.basic;
|
||||||
|
|
||||||
|
public class PaintJob {
|
||||||
|
public String getJobType() {
|
||||||
|
return "Paint Job";
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,7 @@
|
||||||
|
package com.baeldung.reflection.createobject.basic;
|
||||||
|
|
||||||
|
public class RepairJob {
|
||||||
|
public String getJobType() {
|
||||||
|
return "Repair Job";
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,22 @@
|
||||||
|
package com.baeldung.reflection.createobject.basic;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
|
||||||
|
public class SilverJobCard {
|
||||||
|
private Object jobType;
|
||||||
|
|
||||||
|
public void setJobType(Class jobTypeClass) throws
|
||||||
|
NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
|
||||||
|
this.jobType = jobTypeClass.getDeclaredConstructor().newInstance();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String startJob() {
|
||||||
|
if (this.jobType instanceof RepairJob) {
|
||||||
|
return "Start Silver " + ((RepairJob) this.jobType).getJobType();
|
||||||
|
}
|
||||||
|
if (this.jobType instanceof MaintenanceJob) {
|
||||||
|
return "Start Silver " + ((MaintenanceJob) this.jobType).getJobType();
|
||||||
|
}
|
||||||
|
return "Silver Job Failed";
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,5 @@
|
||||||
|
package com.baeldung.reflection.createobject.special;
|
||||||
|
|
||||||
|
public interface Job {
|
||||||
|
String getJobType();
|
||||||
|
}
|
|
@ -0,0 +1,7 @@
|
||||||
|
package com.baeldung.reflection.createobject.special;
|
||||||
|
|
||||||
|
public class MaintenanceJob implements Job {
|
||||||
|
public String getJobType() {
|
||||||
|
return "Maintenance Job";
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,8 @@
|
||||||
|
package com.baeldung.reflection.createobject.special;
|
||||||
|
|
||||||
|
public class PaintJob implements Job {
|
||||||
|
@Override
|
||||||
|
public String getJobType() {
|
||||||
|
return "Paint Job";
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,16 @@
|
||||||
|
package com.baeldung.reflection.createobject.special;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
|
||||||
|
public class PlatinumJobCard<T extends Job> {
|
||||||
|
private T jobType;
|
||||||
|
|
||||||
|
public void setJobType(Class<T> jobTypeClass) throws
|
||||||
|
NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
|
||||||
|
this.jobType = jobTypeClass.getDeclaredConstructor().newInstance();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String startJob() {
|
||||||
|
return "Start Platinum " + this.jobType.getJobType();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,7 @@
|
||||||
|
package com.baeldung.reflection.createobject.special;
|
||||||
|
|
||||||
|
public class RepairJob implements Job {
|
||||||
|
public String getJobType() {
|
||||||
|
return "Repair Job";
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
@startuml
|
||||||
|
'https://plantuml.com/class-diagram
|
||||||
|
|
||||||
|
class BronzeJobCard {
|
||||||
|
-Object jobType
|
||||||
|
+setJobType(String jobType)
|
||||||
|
+startJob()
|
||||||
|
}
|
||||||
|
|
||||||
|
class MaintenanceJob {
|
||||||
|
+getJobType()
|
||||||
|
}
|
||||||
|
class RepairJob {
|
||||||
|
+getJobType()
|
||||||
|
}
|
||||||
|
BronzeJobCard -left-> MaintenanceJob:creates
|
||||||
|
BronzeJobCard -right-> RepairJob:creates
|
||||||
|
|
||||||
|
|
||||||
|
@enduml
|
|
@ -0,0 +1,20 @@
|
||||||
|
@startuml
|
||||||
|
'https://plantuml.com/class-diagram
|
||||||
|
|
||||||
|
class GoldJobCard<T> {
|
||||||
|
-T jobType
|
||||||
|
+setJobType(Class<T> jobTypeClass)
|
||||||
|
+startJob()
|
||||||
|
}
|
||||||
|
|
||||||
|
class MaintenanceJob {
|
||||||
|
+getJobType()
|
||||||
|
}
|
||||||
|
class RepairJob {
|
||||||
|
+getJobType()
|
||||||
|
}
|
||||||
|
GoldJobCard -left-> MaintenanceJob:creates
|
||||||
|
GoldJobCard -right-> RepairJob:creates
|
||||||
|
|
||||||
|
|
||||||
|
@enduml
|
|
@ -0,0 +1,25 @@
|
||||||
|
@startuml
|
||||||
|
'https://plantuml.com/class-diagram
|
||||||
|
interface Job {
|
||||||
|
+getJobType
|
||||||
|
}
|
||||||
|
class PlatinumJobCard <T extends Job> {
|
||||||
|
+setJobType(Class<T> jobTypeClass)
|
||||||
|
+startJob()
|
||||||
|
}
|
||||||
|
|
||||||
|
class MaintenanceJob implements Job {
|
||||||
|
+getJobType()
|
||||||
|
}
|
||||||
|
class RepairJob implements Job {
|
||||||
|
+getJobType()
|
||||||
|
}
|
||||||
|
class PaintJob implements Job {
|
||||||
|
+getJobType()
|
||||||
|
}
|
||||||
|
PlatinumJobCard -up-> MaintenanceJob:creates
|
||||||
|
PlatinumJobCard -up-> RepairJob:creates
|
||||||
|
PlatinumJobCard -up-> PaintJob:creates
|
||||||
|
|
||||||
|
|
||||||
|
@enduml
|
|
@ -0,0 +1,20 @@
|
||||||
|
@startuml
|
||||||
|
'https://plantuml.com/class-diagram
|
||||||
|
|
||||||
|
class SilverJobCard {
|
||||||
|
-Object jobType
|
||||||
|
+setJobType(Class jobTypeClass);
|
||||||
|
+startJob();
|
||||||
|
}
|
||||||
|
|
||||||
|
class MaintenanceJob {
|
||||||
|
+getJobType();
|
||||||
|
}
|
||||||
|
class RepairJob {
|
||||||
|
+getJobType();
|
||||||
|
}
|
||||||
|
SilverJobCard -left-> MaintenanceJob:creates
|
||||||
|
SilverJobCard -right-> RepairJob:creates
|
||||||
|
|
||||||
|
|
||||||
|
@enduml
|
|
@ -0,0 +1,67 @@
|
||||||
|
package com.baeldung.reflection.createobject;
|
||||||
|
|
||||||
|
import com.baeldung.reflection.createobject.basic.*;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class CreateObjectBasicUnitTest {
|
||||||
|
@Test
|
||||||
|
public void givenBronzeJobCard_whenJobTypeRepairAndMaintenance_thenStartJob() throws ClassNotFoundException,
|
||||||
|
InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
|
||||||
|
|
||||||
|
BronzeJobCard bronzeJobCard1 = new BronzeJobCard();
|
||||||
|
bronzeJobCard1.setJobType("com.baeldung.reflection.createobject.basic.RepairJob");
|
||||||
|
assertEquals("Start Bronze Repair Job", bronzeJobCard1.startJob());
|
||||||
|
|
||||||
|
BronzeJobCard bronzeJobCard2 = new BronzeJobCard();
|
||||||
|
bronzeJobCard2.setJobType("com.baeldung.reflection.createobject.basic.MaintenanceJob");
|
||||||
|
assertEquals("Start Bronze Maintenance Job", bronzeJobCard2.startJob());
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenBronzeJobCard_whenJobTypePaint_thenFailJob() throws ClassNotFoundException,
|
||||||
|
InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
|
||||||
|
|
||||||
|
BronzeJobCard bronzeJobCard = new BronzeJobCard();
|
||||||
|
bronzeJobCard.setJobType("com.baeldung.reflection.createobject.basic.PaintJob");
|
||||||
|
assertEquals("Bronze Job Failed", bronzeJobCard.startJob());
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenSilverJobCard_whenJobTypeRepairAndMaintenance_thenStartJob() throws InvocationTargetException,
|
||||||
|
NoSuchMethodException, InstantiationException, IllegalAccessException {
|
||||||
|
|
||||||
|
SilverJobCard silverJobCard1 = new SilverJobCard();
|
||||||
|
silverJobCard1.setJobType(RepairJob.class);
|
||||||
|
assertEquals("Start Silver Repair Job", silverJobCard1.startJob());
|
||||||
|
|
||||||
|
SilverJobCard silverJobCard2 = new SilverJobCard();
|
||||||
|
silverJobCard2.setJobType(MaintenanceJob.class);
|
||||||
|
assertEquals("Start Silver Maintenance Job", silverJobCard2.startJob());
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenSilverJobCard_whenJobTypePaint_thenFailJob() throws ClassNotFoundException,
|
||||||
|
InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
|
||||||
|
|
||||||
|
SilverJobCard silverJobCard = new SilverJobCard();
|
||||||
|
silverJobCard.setJobType(PaintJob.class);
|
||||||
|
assertEquals("Silver Job Failed", silverJobCard.startJob());
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void givenGoldJobCard_whenJobTypeRepairMaintenanceAndPaint_thenStartJob() throws InvocationTargetException,
|
||||||
|
NoSuchMethodException, InstantiationException, IllegalAccessException {
|
||||||
|
|
||||||
|
GoldJobCard<RepairJob> goldJobCard1 = new GoldJobCard<RepairJob>();
|
||||||
|
goldJobCard1.setJobType(RepairJob.class);
|
||||||
|
assertEquals("Start Gold Repair Job", goldJobCard1.startJob());
|
||||||
|
|
||||||
|
GoldJobCard<MaintenanceJob> goldJobCard2 = new GoldJobCard<MaintenanceJob>();
|
||||||
|
goldJobCard2.setJobType(MaintenanceJob.class);
|
||||||
|
assertEquals("Start Gold Maintenance Job", goldJobCard2.startJob());
|
||||||
|
|
||||||
|
GoldJobCard<PaintJob> goldJobCard3 = new GoldJobCard<PaintJob>();
|
||||||
|
goldJobCard3.setJobType(PaintJob.class);
|
||||||
|
assertEquals("Start Gold Paint Job", goldJobCard3.startJob());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,29 @@
|
||||||
|
package com.baeldung.reflection.createobject;
|
||||||
|
|
||||||
|
import com.baeldung.reflection.createobject.special.MaintenanceJob;
|
||||||
|
import com.baeldung.reflection.createobject.special.PaintJob;
|
||||||
|
import com.baeldung.reflection.createobject.special.PlatinumJobCard;
|
||||||
|
import com.baeldung.reflection.createobject.special.RepairJob;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
|
||||||
|
public class CreateObjectSpecialUnitTest {
|
||||||
|
@Test
|
||||||
|
public void givenPlatinumJobCard_whenJobTypeRepairMaintenanceAndPaint_thenStartJob() throws InvocationTargetException,
|
||||||
|
NoSuchMethodException, InstantiationException, IllegalAccessException {
|
||||||
|
|
||||||
|
PlatinumJobCard<RepairJob> platinumJobCard1 = new PlatinumJobCard<RepairJob>();
|
||||||
|
platinumJobCard1.setJobType(RepairJob.class);
|
||||||
|
assertEquals("Start Platinum Repair Job", platinumJobCard1.startJob());
|
||||||
|
|
||||||
|
PlatinumJobCard<MaintenanceJob> platinumJobCard2 = new PlatinumJobCard<MaintenanceJob>();
|
||||||
|
platinumJobCard2.setJobType(MaintenanceJob.class);
|
||||||
|
assertEquals("Start Platinum Maintenance Job", platinumJobCard2.startJob());
|
||||||
|
|
||||||
|
PlatinumJobCard<PaintJob> platinumJobCard3 = new PlatinumJobCard<PaintJob>();
|
||||||
|
platinumJobCard3.setJobType(PaintJob.class);
|
||||||
|
assertEquals("Start Platinum Paint Job", platinumJobCard3.startJob());
|
||||||
|
}
|
||||||
|
}
|
|
@ -53,6 +53,12 @@
|
||||||
<version>${spring.core.version}</version>
|
<version>${spring.core.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<version>${lombok.version}</version>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
|
|
@ -24,9 +24,7 @@
|
||||||
<!--<module>core-java-collections-conversions-2</module> -->
|
<!--<module>core-java-collections-conversions-2</module> -->
|
||||||
<!--<module>core-java-lang</module> -->
|
<!--<module>core-java-lang</module> -->
|
||||||
<!--<module>core-java-lang-math-3</module> -->
|
<!--<module>core-java-lang-math-3</module> -->
|
||||||
<!--<module>core-java-nio-2</module> -->
|
|
||||||
<!--<module>core-java-security</module> -->
|
<!--<module>core-java-security</module> -->
|
||||||
<!--<module>core-java-serialization</module> -->
|
|
||||||
<!--<module>core-java-streams-2</module> -->
|
<!--<module>core-java-streams-2</module> -->
|
||||||
<!--<module>core-java-sun</module> -->
|
<!--<module>core-java-sun</module> -->
|
||||||
<module>core-java-9-improvements</module>
|
<module>core-java-9-improvements</module>
|
||||||
|
@ -143,6 +141,7 @@
|
||||||
<module>core-java-networking-2</module>
|
<module>core-java-networking-2</module>
|
||||||
<module>core-java-networking-4</module>
|
<module>core-java-networking-4</module>
|
||||||
<module>core-java-nio</module>
|
<module>core-java-nio</module>
|
||||||
|
<module>core-java-nio-2</module>
|
||||||
<module>core-java-numbers</module>
|
<module>core-java-numbers</module>
|
||||||
<module>core-java-numbers-2</module>
|
<module>core-java-numbers-2</module>
|
||||||
<module>core-java-numbers-3</module>
|
<module>core-java-numbers-3</module>
|
||||||
|
@ -159,6 +158,7 @@
|
||||||
<module>core-java-security-3</module>
|
<module>core-java-security-3</module>
|
||||||
<module>core-java-security-4</module>
|
<module>core-java-security-4</module>
|
||||||
<module>core-java-security-algorithms</module>
|
<module>core-java-security-algorithms</module>
|
||||||
|
<module>core-java-serialization</module>
|
||||||
<module>core-java-streams</module>
|
<module>core-java-streams</module>
|
||||||
<module>core-java-streams-3</module>
|
<module>core-java-streams-3</module>
|
||||||
<module>core-java-string-algorithms</module>
|
<module>core-java-string-algorithms</module>
|
||||||
|
@ -176,6 +176,7 @@
|
||||||
<module>core-java-uuid</module>
|
<module>core-java-uuid</module>
|
||||||
<module>core-java-collections-maps-6</module>
|
<module>core-java-collections-maps-6</module>
|
||||||
<module>core-java-records</module>
|
<module>core-java-records</module>
|
||||||
|
<module>core-java-9-jigsaw</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
<dependencyManagement>
|
<dependencyManagement>
|
||||||
|
|
|
@ -8,3 +8,5 @@ This module contains articles about automatic code generation
|
||||||
- [Introduction to AutoFactory](https://www.baeldung.com/autofactory)
|
- [Introduction to AutoFactory](https://www.baeldung.com/autofactory)
|
||||||
- [Google AutoService](https://www.baeldung.com/google-autoservice)
|
- [Google AutoService](https://www.baeldung.com/google-autoservice)
|
||||||
- [Defensive Copies for Collections Using AutoValue](https://www.baeldung.com/autovalue-defensive-copies)
|
- [Defensive Copies for Collections Using AutoValue](https://www.baeldung.com/autovalue-defensive-copies)
|
||||||
|
- [Java Annotation Processing and Creating a Builder](https://www.baeldung.com/java-annotation-processing-builder)
|
||||||
|
|
||||||
|
|
|
@ -8,8 +8,8 @@
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<artifactId>google-auto-project</artifactId>
|
||||||
<artifactId>annotations</artifactId>
|
<version>1.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
|
@ -8,8 +8,8 @@
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>annotations</artifactId>
|
<artifactId>google-auto-project</artifactId>
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
|
@ -6,6 +6,8 @@
|
||||||
<artifactId>google-auto-project</artifactId>
|
<artifactId>google-auto-project</artifactId>
|
||||||
<version>1.0</version>
|
<version>1.0</version>
|
||||||
<name>google-auto-project</name>
|
<name>google-auto-project</name>
|
||||||
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
|
@ -13,6 +15,11 @@
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
|
<modules>
|
||||||
|
<module>annotation-processing</module>
|
||||||
|
<module>annotation-user</module>
|
||||||
|
</modules>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.auto.value</groupId>
|
<groupId>com.google.auto.value</groupId>
|
||||||
|
|
|
@ -1,10 +1,10 @@
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>${project.model.version}</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung.java.panama</groupId>
|
<groupId>com.baeldung.java.panama</groupId>
|
||||||
<artifactId>java-panama</artifactId>
|
<artifactId>java-panama</artifactId>
|
||||||
<version>${project.version}</version>
|
<version>1.0</version>
|
||||||
<name>java-panama</name>
|
<name>java-panama</name>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
|
|
@ -117,7 +117,7 @@
|
||||||
<module>rethinkdb</module>
|
<module>rethinkdb</module>
|
||||||
<module>scylladb</module>
|
<module>scylladb</module>
|
||||||
<module>spring-data-cassandra-2</module>
|
<module>spring-data-cassandra-2</module>
|
||||||
<!--<module>spring-data-jpa-repo-3</module>--> <!--Fix in JAVA-24547-->
|
<module>spring-data-jpa-repo-3</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
|
|
|
@ -32,5 +32,8 @@
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
<properties>
|
||||||
|
<start-class>com.baeldung.spring.data.jpa.naturalid.Application</start-class>
|
||||||
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
11
pom.xml
11
pom.xml
|
@ -342,8 +342,6 @@
|
||||||
<module>core-java-modules/core-java-8-datetime-2</module>
|
<module>core-java-modules/core-java-8-datetime-2</module>
|
||||||
<module>core-java-modules/core-java-sun</module>
|
<module>core-java-modules/core-java-sun</module>
|
||||||
<module>core-java-modules/core-java-security</module>
|
<module>core-java-modules/core-java-security</module>
|
||||||
<module>core-java-modules/core-java-nio-2</module>
|
|
||||||
<module>core-java-modules/core-java-serialization</module>
|
|
||||||
<module>core-java-modules/core-java-lang</module>
|
<module>core-java-modules/core-java-lang</module>
|
||||||
<module>core-java-modules/core-java-lang-math-3</module>
|
<module>core-java-modules/core-java-lang-math-3</module>
|
||||||
|
|
||||||
|
@ -519,8 +517,6 @@
|
||||||
<module>core-java-modules/core-java-8-datetime-2</module>
|
<module>core-java-modules/core-java-8-datetime-2</module>
|
||||||
<module>core-java-modules/core-java-sun</module>
|
<module>core-java-modules/core-java-sun</module>
|
||||||
<module>core-java-modules/core-java-security</module>
|
<module>core-java-modules/core-java-security</module>
|
||||||
<module>core-java-modules/core-java-nio-2</module>
|
|
||||||
<module>core-java-modules/core-java-serialization</module>
|
|
||||||
<module>core-java-modules/core-java-lang</module>
|
<module>core-java-modules/core-java-lang</module>
|
||||||
<module>core-java-modules/core-java-lang-math-3</module>
|
<module>core-java-modules/core-java-lang-math-3</module>
|
||||||
|
|
||||||
|
@ -543,6 +539,7 @@
|
||||||
<module>persistence-modules/hibernate-ogm</module> <!-- hibernate-ogm wasn't updated because it doesn't support jakarta API -->
|
<module>persistence-modules/hibernate-ogm</module> <!-- hibernate-ogm wasn't updated because it doesn't support jakarta API -->
|
||||||
<module>persistence-modules/spring-data-cassandra-reactive</module> <!--JAVA-21844-->
|
<module>persistence-modules/spring-data-cassandra-reactive</module> <!--JAVA-21844-->
|
||||||
<module>java-nashorn</module>
|
<module>java-nashorn</module>
|
||||||
|
<module>jeromq</module>
|
||||||
<module>spring-ejb-modules/ejb-beans</module>
|
<module>spring-ejb-modules/ejb-beans</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
|
@ -812,7 +809,6 @@
|
||||||
<!-- Modules from default-first -->
|
<!-- Modules from default-first -->
|
||||||
|
|
||||||
<module>akka-modules</module>
|
<module>akka-modules</module>
|
||||||
<module>annotations</module>
|
|
||||||
<module>httpclient-simple</module>
|
<module>httpclient-simple</module>
|
||||||
<module>antlr</module>
|
<module>antlr</module>
|
||||||
<module>apache-kafka</module>
|
<module>apache-kafka</module>
|
||||||
|
@ -939,6 +935,7 @@
|
||||||
<module>gradle-modules/gradle/maven-to-gradle</module>
|
<module>gradle-modules/gradle/maven-to-gradle</module>
|
||||||
<module>persistence-modules/spring-data-neo4j</module>
|
<module>persistence-modules/spring-data-neo4j</module>
|
||||||
<module>parent-boot-3</module>
|
<module>parent-boot-3</module>
|
||||||
|
<!--<module>java-panama</module> Java-19 module-->
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
|
@ -1086,7 +1083,6 @@
|
||||||
<!-- Modules from default-first -->
|
<!-- Modules from default-first -->
|
||||||
|
|
||||||
<module>akka-modules</module>
|
<module>akka-modules</module>
|
||||||
<module>annotations</module>
|
|
||||||
<module>antlr</module>
|
<module>antlr</module>
|
||||||
<module>apache-kafka</module>
|
<module>apache-kafka</module>
|
||||||
<module>apache-kafka-2</module>
|
<module>apache-kafka-2</module>
|
||||||
|
@ -1213,6 +1209,9 @@
|
||||||
<module>language-interop</module>
|
<module>language-interop</module>
|
||||||
<module>gradle-modules/gradle/maven-to-gradle</module>
|
<module>gradle-modules/gradle/maven-to-gradle</module>
|
||||||
<module>persistence-modules/spring-data-neo4j</module>
|
<module>persistence-modules/spring-data-neo4j</module>
|
||||||
|
<module>spring-actuator</module>
|
||||||
|
<module>spring-cloud-modules/spring-cloud-azure</module>
|
||||||
|
<module>spring-cloud-modules/spring-cloud-contract</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
|
|
|
@ -103,6 +103,7 @@
|
||||||
<module>spring-boot-mvc-legacy</module>
|
<module>spring-boot-mvc-legacy</module>
|
||||||
<module>spring-boot-springdoc-2</module>
|
<module>spring-boot-springdoc-2</module>
|
||||||
<module>spring-boot-documentation</module>
|
<module>spring-boot-documentation</module>
|
||||||
|
<module>spring-boot-3-url-matching</module>
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
<dependencyManagement>
|
<dependencyManagement>
|
||||||
|
|
|
@ -67,7 +67,7 @@
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>io.projectreactor</groupId>
|
<groupId>io.projectreactor</groupId>
|
||||||
<artifactId>reactor-test</artifactId>
|
<artifactId>reactor-test</artifactId>
|
||||||
<version>${reactor-test.version}</version>
|
<version>${reactor-core.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
Loading…
Reference in New Issue