Merge pull request #6900 from amit2103/BAEL-9555

[BAEL-9555] - Created a core-java-modules folder
This commit is contained in:
Loredana Crusoveanu 2019-05-05 18:06:05 +03:00 committed by GitHub
commit 1275aa8bd9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1480 changed files with 25600 additions and 5594 deletions

View File

@ -12,6 +12,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>
</parent> </parent>
<build> <build>

View File

@ -12,6 +12,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>
</parent> </parent>
<dependencies> <dependencies>

View File

@ -1,132 +1,132 @@
/* /*
* To change this license header, choose License Headers in Project Properties. * To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates * To change this template file, choose Tools | Templates
* and open the template in the editor. * and open the template in the editor.
*/ */
package com.baeldung.java11.httpclient; package com.baeldung.java11.httpclient;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.http.HttpClient; import java.net.http.HttpClient;
import java.net.http.HttpClient.Version; import java.net.http.HttpClient.Version;
import java.net.http.HttpRequest; import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers; import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse; import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers; import java.net.http.HttpResponse.BodyHandlers;
import java.net.http.HttpResponse.PushPromiseHandler; import java.net.http.HttpResponse.PushPromiseHandler;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class HttpClientExample { public class HttpClientExample {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
httpGetRequest(); httpGetRequest();
httpPostRequest(); httpPostRequest();
asynchronousGetRequest(); asynchronousGetRequest();
asynchronousMultipleRequests(); asynchronousMultipleRequests();
pushRequest(); pushRequest();
} }
public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException { public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient(); HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.version(HttpClient.Version.HTTP_2) .version(HttpClient.Version.HTTP_2)
.uri(URI.create("http://jsonplaceholder.typicode.com/posts/1")) .uri(URI.create("http://jsonplaceholder.typicode.com/posts/1"))
.headers("Accept-Enconding", "gzip, deflate") .headers("Accept-Enconding", "gzip, deflate")
.build(); .build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString()); HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
String responseBody = response.body(); String responseBody = response.body();
int responseStatusCode = response.statusCode(); int responseStatusCode = response.statusCode();
System.out.println("httpGetRequest: " + responseBody); System.out.println("httpGetRequest: " + responseBody);
System.out.println("httpGetRequest status code: " + responseStatusCode); System.out.println("httpGetRequest status code: " + responseStatusCode);
} }
public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException { public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException {
HttpClient client = HttpClient.newBuilder() HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2) .version(HttpClient.Version.HTTP_2)
.build(); .build();
HttpRequest request = HttpRequest.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts")) HttpRequest request = HttpRequest.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts"))
.version(HttpClient.Version.HTTP_2) .version(HttpClient.Version.HTTP_2)
.POST(BodyPublishers.ofString("Sample Post Request")) .POST(BodyPublishers.ofString("Sample Post Request"))
.build(); .build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString()); HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
String responseBody = response.body(); String responseBody = response.body();
System.out.println("httpPostRequest : " + responseBody); System.out.println("httpPostRequest : " + responseBody);
} }
public static void asynchronousGetRequest() throws URISyntaxException { public static void asynchronousGetRequest() throws URISyntaxException {
HttpClient client = HttpClient.newHttpClient(); HttpClient client = HttpClient.newHttpClient();
URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1"); URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
HttpRequest request = HttpRequest.newBuilder(httpURI) HttpRequest request = HttpRequest.newBuilder(httpURI)
.version(HttpClient.Version.HTTP_2) .version(HttpClient.Version.HTTP_2)
.build(); .build();
CompletableFuture<Void> futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString()) CompletableFuture<Void> futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenAccept(resp -> { .thenAccept(resp -> {
System.out.println("Got pushed response " + resp.uri()); System.out.println("Got pushed response " + resp.uri());
System.out.println("Response statuscode: " + resp.statusCode()); System.out.println("Response statuscode: " + resp.statusCode());
System.out.println("Response body: " + resp.body()); System.out.println("Response body: " + resp.body());
}); });
System.out.println("futureResponse" + futureResponse); System.out.println("futureResponse" + futureResponse);
} }
public static void asynchronousMultipleRequests() throws URISyntaxException { public static void asynchronousMultipleRequests() throws URISyntaxException {
HttpClient client = HttpClient.newHttpClient(); HttpClient client = HttpClient.newHttpClient();
List<URI> uris = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2")); List<URI> uris = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2"));
List<HttpRequest> requests = uris.stream() List<HttpRequest> requests = uris.stream()
.map(HttpRequest::newBuilder) .map(HttpRequest::newBuilder)
.map(reqBuilder -> reqBuilder.build()) .map(reqBuilder -> reqBuilder.build())
.collect(Collectors.toList()); .collect(Collectors.toList());
System.out.println("Got pushed response1 " + requests); System.out.println("Got pushed response1 " + requests);
CompletableFuture.allOf(requests.stream() CompletableFuture.allOf(requests.stream()
.map(request -> client.sendAsync(request, BodyHandlers.ofString())) .map(request -> client.sendAsync(request, BodyHandlers.ofString()))
.toArray(CompletableFuture<?>[]::new)) .toArray(CompletableFuture<?>[]::new))
.thenAccept(System.out::println) .thenAccept(System.out::println)
.join(); .join();
} }
public static void pushRequest() throws URISyntaxException, InterruptedException { public static void pushRequest() throws URISyntaxException, InterruptedException {
System.out.println("Running HTTP/2 Server Push example..."); System.out.println("Running HTTP/2 Server Push example...");
HttpClient httpClient = HttpClient.newBuilder() HttpClient httpClient = HttpClient.newBuilder()
.version(Version.HTTP_2) .version(Version.HTTP_2)
.build(); .build();
HttpRequest pageRequest = HttpRequest.newBuilder() HttpRequest pageRequest = HttpRequest.newBuilder()
.uri(URI.create("https://http2.golang.org/serverpush")) .uri(URI.create("https://http2.golang.org/serverpush"))
.build(); .build();
// Interface HttpResponse.PushPromiseHandler<T> // Interface HttpResponse.PushPromiseHandler<T>
// void applyPushPromise(HttpRequest initiatingRequest, HttpRequest pushPromiseRequest, Function<HttpResponse.BodyHandler<T>,CompletableFuture<HttpResponse<T>>> acceptor) // void applyPushPromise(HttpRequest initiatingRequest, HttpRequest pushPromiseRequest, Function<HttpResponse.BodyHandler<T>,CompletableFuture<HttpResponse<T>>> acceptor)
httpClient.sendAsync(pageRequest, BodyHandlers.ofString(), pushPromiseHandler()) httpClient.sendAsync(pageRequest, BodyHandlers.ofString(), pushPromiseHandler())
.thenAccept(pageResponse -> { .thenAccept(pageResponse -> {
System.out.println("Page response status code: " + pageResponse.statusCode()); System.out.println("Page response status code: " + pageResponse.statusCode());
System.out.println("Page response headers: " + pageResponse.headers()); System.out.println("Page response headers: " + pageResponse.headers());
String responseBody = pageResponse.body(); String responseBody = pageResponse.body();
System.out.println(responseBody); System.out.println(responseBody);
}).join(); }).join();
Thread.sleep(1000); // waiting for full response Thread.sleep(1000); // waiting for full response
} }
private static PushPromiseHandler<String> pushPromiseHandler() { private static PushPromiseHandler<String> pushPromiseHandler() {
return (HttpRequest initiatingRequest, return (HttpRequest initiatingRequest,
HttpRequest pushPromiseRequest, HttpRequest pushPromiseRequest,
Function<HttpResponse.BodyHandler<String>, Function<HttpResponse.BodyHandler<String>,
CompletableFuture<HttpResponse<String>>> acceptor) -> { CompletableFuture<HttpResponse<String>>> acceptor) -> {
acceptor.apply(BodyHandlers.ofString()) acceptor.apply(BodyHandlers.ofString())
.thenAccept(resp -> { .thenAccept(resp -> {
System.out.println(" Pushed response: " + resp.uri() + ", headers: " + resp.headers()); System.out.println(" Pushed response: " + resp.uri() + ", headers: " + resp.headers());
}); });
System.out.println("Promise request: " + pushPromiseRequest.uri()); System.out.println("Promise request: " + pushPromiseRequest.uri());
System.out.println("Promise request: " + pushPromiseRequest.headers()); System.out.println("Promise request: " + pushPromiseRequest.headers());
}; };
} }
} }

View File

@ -1,240 +1,240 @@
package com.baeldung.java11.httpclient.test; package com.baeldung.java11.httpclient.test;
import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import java.io.IOException; import java.io.IOException;
import java.net.Authenticator; import java.net.Authenticator;
import java.net.CookieManager; import java.net.CookieManager;
import java.net.CookiePolicy; import java.net.CookiePolicy;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.PasswordAuthentication; import java.net.PasswordAuthentication;
import java.net.ProxySelector; import java.net.ProxySelector;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.http.HttpClient; 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;
import java.net.http.HttpResponse.BodyHandlers; import java.net.http.HttpResponse.BodyHandlers;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
public class HttpClientTest { public class HttpClientTest {
@Test @Test
public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException { public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post")) .uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8") .headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofString("Sample body")) .POST(HttpRequest.BodyPublishers.ofString("Sample body"))
.build(); .build();
HttpResponse<String> response = HttpClient.newBuilder() HttpResponse<String> response = HttpClient.newBuilder()
.proxy(ProxySelector.getDefault()) .proxy(ProxySelector.getDefault())
.build() .build()
.send(request, HttpResponse.BodyHandlers.ofString()); .send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.body(), containsString("Sample body")); assertThat(response.body(), containsString("Sample body"));
} }
@Test @Test
public void shouldNotFollowRedirectWhenSetToDefaultNever() throws IOException, InterruptedException, URISyntaxException { public void shouldNotFollowRedirectWhenSetToDefaultNever() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("http://stackoverflow.com")) .uri(new URI("http://stackoverflow.com"))
.version(HttpClient.Version.HTTP_1_1) .version(HttpClient.Version.HTTP_1_1)
.GET() .GET()
.build(); .build();
HttpResponse<String> response = HttpClient.newBuilder() HttpResponse<String> response = HttpClient.newBuilder()
.build() .build()
.send(request, HttpResponse.BodyHandlers.ofString()); .send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM)); assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
assertThat(response.body(), containsString("https://stackoverflow.com/")); assertThat(response.body(), containsString("https://stackoverflow.com/"));
} }
@Test @Test
public void shouldFollowRedirectWhenSetToAlways() throws IOException, InterruptedException, URISyntaxException { public void shouldFollowRedirectWhenSetToAlways() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("http://stackoverflow.com")) .uri(new URI("http://stackoverflow.com"))
.version(HttpClient.Version.HTTP_1_1) .version(HttpClient.Version.HTTP_1_1)
.GET() .GET()
.build(); .build();
HttpResponse<String> response = HttpClient.newBuilder() HttpResponse<String> response = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.ALWAYS) .followRedirects(HttpClient.Redirect.ALWAYS)
.build() .build()
.send(request, HttpResponse.BodyHandlers.ofString()); .send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.request() assertThat(response.request()
.uri() .uri()
.toString(), equalTo("https://stackoverflow.com/")); .toString(), equalTo("https://stackoverflow.com/"));
} }
@Test @Test
public void shouldReturnOKStatusForAuthenticatedAccess() throws URISyntaxException, IOException, InterruptedException { public void shouldReturnOKStatusForAuthenticatedAccess() throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/basic-auth")) .uri(new URI("https://postman-echo.com/basic-auth"))
.GET() .GET()
.build(); .build();
HttpResponse<String> response = HttpClient.newBuilder() HttpResponse<String> response = HttpClient.newBuilder()
.authenticator(new Authenticator() { .authenticator(new Authenticator() {
@Override @Override
protected PasswordAuthentication getPasswordAuthentication() { protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("postman", "password".toCharArray()); return new PasswordAuthentication("postman", "password".toCharArray());
} }
}) })
.build() .build()
.send(request, HttpResponse.BodyHandlers.ofString()); .send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
} }
@Test @Test
public void shouldSendRequestAsync() throws URISyntaxException, InterruptedException, ExecutionException { public void shouldSendRequestAsync() throws URISyntaxException, InterruptedException, ExecutionException {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post")) .uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8") .headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofString("Sample body")) .POST(HttpRequest.BodyPublishers.ofString("Sample body"))
.build(); .build();
CompletableFuture<HttpResponse<String>> response = HttpClient.newBuilder() CompletableFuture<HttpResponse<String>> response = HttpClient.newBuilder()
.build() .build()
.sendAsync(request, HttpResponse.BodyHandlers.ofString()); .sendAsync(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.get() assertThat(response.get()
.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); .statusCode(), equalTo(HttpURLConnection.HTTP_OK));
} }
@Test @Test
public void shouldUseJustTwoThreadWhenProcessingSendAsyncRequest() throws URISyntaxException, InterruptedException, ExecutionException { public void shouldUseJustTwoThreadWhenProcessingSendAsyncRequest() throws URISyntaxException, InterruptedException, ExecutionException {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get")) .uri(new URI("https://postman-echo.com/get"))
.GET() .GET()
.build(); .build();
ExecutorService executorService = Executors.newFixedThreadPool(2); ExecutorService executorService = Executors.newFixedThreadPool(2);
CompletableFuture<HttpResponse<String>> response1 = HttpClient.newBuilder() CompletableFuture<HttpResponse<String>> response1 = HttpClient.newBuilder()
.executor(executorService) .executor(executorService)
.build() .build()
.sendAsync(request, HttpResponse.BodyHandlers.ofString()); .sendAsync(request, HttpResponse.BodyHandlers.ofString());
CompletableFuture<HttpResponse<String>> response2 = HttpClient.newBuilder() CompletableFuture<HttpResponse<String>> response2 = HttpClient.newBuilder()
.executor(executorService) .executor(executorService)
.build() .build()
.sendAsync(request, HttpResponse.BodyHandlers.ofString()); .sendAsync(request, HttpResponse.BodyHandlers.ofString());
CompletableFuture<HttpResponse<String>> response3 = HttpClient.newBuilder() CompletableFuture<HttpResponse<String>> response3 = HttpClient.newBuilder()
.executor(executorService) .executor(executorService)
.build() .build()
.sendAsync(request, HttpResponse.BodyHandlers.ofString()); .sendAsync(request, HttpResponse.BodyHandlers.ofString());
CompletableFuture.allOf(response1, response2, response3) CompletableFuture.allOf(response1, response2, response3)
.join(); .join();
assertThat(response1.get() assertThat(response1.get()
.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); .statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response2.get() assertThat(response2.get()
.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); .statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response3.get() assertThat(response3.get()
.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); .statusCode(), equalTo(HttpURLConnection.HTTP_OK));
} }
@Test @Test
public void shouldNotStoreCookieWhenPolicyAcceptNone() throws URISyntaxException, IOException, InterruptedException { public void shouldNotStoreCookieWhenPolicyAcceptNone() throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get")) .uri(new URI("https://postman-echo.com/get"))
.GET() .GET()
.build(); .build();
HttpClient httpClient = HttpClient.newBuilder() HttpClient httpClient = HttpClient.newBuilder()
.cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_NONE)) .cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_NONE))
.build(); .build();
httpClient.send(request, HttpResponse.BodyHandlers.ofString()); httpClient.send(request, HttpResponse.BodyHandlers.ofString());
assertTrue(httpClient.cookieHandler() assertTrue(httpClient.cookieHandler()
.isPresent()); .isPresent());
} }
@Test @Test
public void shouldStoreCookieWhenPolicyAcceptAll() throws URISyntaxException, IOException, InterruptedException { public void shouldStoreCookieWhenPolicyAcceptAll() throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get")) .uri(new URI("https://postman-echo.com/get"))
.GET() .GET()
.build(); .build();
HttpClient httpClient = HttpClient.newBuilder() HttpClient httpClient = HttpClient.newBuilder()
.cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ALL)) .cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ALL))
.build(); .build();
httpClient.send(request, HttpResponse.BodyHandlers.ofString()); httpClient.send(request, HttpResponse.BodyHandlers.ofString());
assertTrue(httpClient.cookieHandler() assertTrue(httpClient.cookieHandler()
.isPresent()); .isPresent());
} }
@Test @Test
public void shouldProcessMultipleRequestViaStream() throws URISyntaxException, ExecutionException, InterruptedException { public void shouldProcessMultipleRequestViaStream() throws URISyntaxException, ExecutionException, InterruptedException {
List<URI> targets = Arrays.asList(new URI("https://postman-echo.com/get?foo1=bar1"), new URI("https://postman-echo.com/get?foo2=bar2")); List<URI> targets = Arrays.asList(new URI("https://postman-echo.com/get?foo1=bar1"), new URI("https://postman-echo.com/get?foo2=bar2"));
HttpClient client = HttpClient.newHttpClient(); HttpClient client = HttpClient.newHttpClient();
List<CompletableFuture<String>> futures = targets.stream() List<CompletableFuture<String>> futures = targets.stream()
.map(target -> client.sendAsync(HttpRequest.newBuilder(target) .map(target -> client.sendAsync(HttpRequest.newBuilder(target)
.GET() .GET()
.build(), HttpResponse.BodyHandlers.ofString()) .build(), HttpResponse.BodyHandlers.ofString())
.thenApply(response -> response.body())) .thenApply(response -> response.body()))
.collect(Collectors.toList()); .collect(Collectors.toList());
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])) CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.join(); .join();
if (futures.get(0) if (futures.get(0)
.get() .get()
.contains("foo1")) { .contains("foo1")) {
assertThat(futures.get(0) assertThat(futures.get(0)
.get(), containsString("bar1")); .get(), containsString("bar1"));
assertThat(futures.get(1) assertThat(futures.get(1)
.get(), containsString("bar2")); .get(), containsString("bar2"));
} else { } else {
assertThat(futures.get(1) assertThat(futures.get(1)
.get(), containsString("bar2")); .get(), containsString("bar2"));
assertThat(futures.get(1) assertThat(futures.get(1)
.get(), containsString("bar1")); .get(), containsString("bar1"));
} }
} }
@Test @Test
public void completeExceptionallyExample() { public void completeExceptionallyExample() {
CompletableFuture<String> cf = CompletableFuture.completedFuture("message").thenApplyAsync(String::toUpperCase, CompletableFuture<String> cf = CompletableFuture.completedFuture("message").thenApplyAsync(String::toUpperCase,
CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS)); CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS));
CompletableFuture<String> exceptionHandler = cf.handle((s, th) -> { return (th != null) ? "message upon cancel" : ""; }); CompletableFuture<String> exceptionHandler = cf.handle((s, th) -> { return (th != null) ? "message upon cancel" : ""; });
cf.completeExceptionally(new RuntimeException("completed exceptionally")); cf.completeExceptionally(new RuntimeException("completed exceptionally"));
assertTrue("Was not completed exceptionally", cf.isCompletedExceptionally()); assertTrue("Was not completed exceptionally", cf.isCompletedExceptionally());
try { try {
cf.join(); cf.join();
fail("Should have thrown an exception"); fail("Should have thrown an exception");
} catch (CompletionException ex) { // just for testing } catch (CompletionException ex) { // just for testing
assertEquals("completed exceptionally", ex.getCause().getMessage()); assertEquals("completed exceptionally", ex.getCause().getMessage());
} }
assertEquals("message upon cancel", exceptionHandler.join()); assertEquals("message upon cancel", exceptionHandler.join());
} }
} }

View File

@ -1,168 +1,168 @@
package com.baeldung.java11.httpclient.test; package com.baeldung.java11.httpclient.test;
import static java.time.temporal.ChronoUnit.SECONDS; import static java.time.temporal.ChronoUnit.SECONDS;
import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.http.HttpClient; 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;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.time.Duration; import java.time.Duration;
import org.junit.Test; import org.junit.Test;
public class HttpRequestTest { public class HttpRequestTest {
@Test @Test
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException { public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get")) .uri(new URI("https://postman-echo.com/get"))
.GET() .GET()
.build(); .build();
HttpResponse<String> response = HttpClient.newHttpClient() HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString()); .send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
} }
@Test @Test
public void shouldUseHttp2WhenWebsiteUsesHttp2() throws IOException, InterruptedException, URISyntaxException { public void shouldUseHttp2WhenWebsiteUsesHttp2() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://stackoverflow.com")) .uri(new URI("https://stackoverflow.com"))
.version(HttpClient.Version.HTTP_2) .version(HttpClient.Version.HTTP_2)
.GET() .GET()
.build(); .build();
HttpResponse<String> response = HttpClient.newHttpClient() HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString()); .send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_2)); assertThat(response.version(), equalTo(HttpClient.Version.HTTP_2));
} }
@Test @Test
public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException { public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get")) .uri(new URI("https://postman-echo.com/get"))
.version(HttpClient.Version.HTTP_2) .version(HttpClient.Version.HTTP_2)
.GET() .GET()
.build(); .build();
HttpResponse<String> response = HttpClient.newHttpClient() HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString()); .send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.version(), equalTo(HttpClient.Version.HTTP_1_1)); assertThat(response.version(), equalTo(HttpClient.Version.HTTP_1_1));
} }
@Test @Test
public void shouldReturnStatusOKWhenSendGetRequestWithDummyHeaders() throws IOException, InterruptedException, URISyntaxException { public void shouldReturnStatusOKWhenSendGetRequestWithDummyHeaders() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get")) .uri(new URI("https://postman-echo.com/get"))
.headers("key1", "value1", "key2", "value2") .headers("key1", "value1", "key2", "value2")
.GET() .GET()
.build(); .build();
HttpResponse<String> response = HttpClient.newHttpClient() HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString()); .send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
} }
@Test @Test
public void shouldReturnStatusOKWhenSendGetRequestTimeoutSet() throws IOException, InterruptedException, URISyntaxException { public void shouldReturnStatusOKWhenSendGetRequestTimeoutSet() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get")) .uri(new URI("https://postman-echo.com/get"))
.timeout(Duration.of(10, SECONDS)) .timeout(Duration.of(10, SECONDS))
.GET() .GET()
.build(); .build();
HttpResponse<String> response = HttpClient.newHttpClient() HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString()); .send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
} }
@Test @Test
public void shouldReturnNoContentWhenPostWithNoBody() throws IOException, InterruptedException, URISyntaxException { public void shouldReturnNoContentWhenPostWithNoBody() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post")) .uri(new URI("https://postman-echo.com/post"))
.POST(HttpRequest.BodyPublishers.noBody()) .POST(HttpRequest.BodyPublishers.noBody())
.build(); .build();
HttpResponse<String> response = HttpClient.newHttpClient() HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString()); .send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
} }
@Test @Test
public void shouldReturnSampleDataContentWhenPostWithBodyText() throws IOException, InterruptedException, URISyntaxException { public void shouldReturnSampleDataContentWhenPostWithBodyText() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post")) .uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8") .headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofString("Sample request body")) .POST(HttpRequest.BodyPublishers.ofString("Sample request body"))
.build(); .build();
HttpResponse<String> response = HttpClient.newHttpClient() HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString()); .send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.body(), containsString("Sample request body")); assertThat(response.body(), containsString("Sample request body"));
} }
@Test @Test
public void shouldReturnSampleDataContentWhenPostWithInputStream() throws IOException, InterruptedException, URISyntaxException { public void shouldReturnSampleDataContentWhenPostWithInputStream() throws IOException, InterruptedException, URISyntaxException {
byte[] sampleData = "Sample request body".getBytes(); byte[] sampleData = "Sample request body".getBytes();
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post")) .uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8") .headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofInputStream(() -> new ByteArrayInputStream(sampleData))) .POST(HttpRequest.BodyPublishers.ofInputStream(() -> new ByteArrayInputStream(sampleData)))
.build(); .build();
HttpResponse<String> response = HttpClient.newHttpClient() HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString()); .send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.body(), containsString("Sample request body")); assertThat(response.body(), containsString("Sample request body"));
} }
@Test @Test
public void shouldReturnSampleDataContentWhenPostWithByteArrayProcessorStream() throws IOException, InterruptedException, URISyntaxException { public void shouldReturnSampleDataContentWhenPostWithByteArrayProcessorStream() throws IOException, InterruptedException, URISyntaxException {
byte[] sampleData = "Sample request body".getBytes(); byte[] sampleData = "Sample request body".getBytes();
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post")) .uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8") .headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofByteArray(sampleData)) .POST(HttpRequest.BodyPublishers.ofByteArray(sampleData))
.build(); .build();
HttpResponse<String> response = HttpClient.newHttpClient() HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString()); .send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.body(), containsString("Sample request body")); assertThat(response.body(), containsString("Sample request body"));
} }
@Test @Test
public void shouldReturnSampleDataContentWhenPostWithFileProcessorStream() throws IOException, InterruptedException, URISyntaxException { public void shouldReturnSampleDataContentWhenPostWithFileProcessorStream() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/post")) .uri(new URI("https://postman-echo.com/post"))
.headers("Content-Type", "text/plain;charset=UTF-8") .headers("Content-Type", "text/plain;charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofFile(Paths.get("src/test/resources/sample.txt"))) .POST(HttpRequest.BodyPublishers.ofFile(Paths.get("src/test/resources/sample.txt")))
.build(); .build();
HttpResponse<String> response = HttpClient.newHttpClient() HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString()); .send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertThat(response.body(), containsString("Sample file content")); assertThat(response.body(), containsString("Sample file content"));
} }
} }

View File

@ -1,54 +1,54 @@
package com.baeldung.java11.httpclient.test; package com.baeldung.java11.httpclient.test;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import java.io.IOException; import java.io.IOException;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.http.HttpClient; 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;
import org.junit.Test; import org.junit.Test;
public class HttpResponseTest { public class HttpResponseTest {
@Test @Test
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException { public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get")) .uri(new URI("https://postman-echo.com/get"))
.version(HttpClient.Version.HTTP_2) .version(HttpClient.Version.HTTP_2)
.GET() .GET()
.build(); .build();
HttpResponse<String> response = HttpClient.newBuilder() HttpResponse<String> response = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL) .followRedirects(HttpClient.Redirect.NORMAL)
.build() .build()
.send(request, HttpResponse.BodyHandlers.ofString()); .send(request, HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
assertNotNull(response.body()); assertNotNull(response.body());
} }
@Test @Test
public void shouldResponseURIDifferentThanRequestUIRWhenRedirect() throws IOException, InterruptedException, URISyntaxException { public void shouldResponseURIDifferentThanRequestUIRWhenRedirect() throws IOException, InterruptedException, URISyntaxException {
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("http://stackoverflow.com")) .uri(new URI("http://stackoverflow.com"))
.version(HttpClient.Version.HTTP_2) .version(HttpClient.Version.HTTP_2)
.GET() .GET()
.build(); .build();
HttpResponse<String> response = HttpClient.newBuilder() HttpResponse<String> response = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL) .followRedirects(HttpClient.Redirect.NORMAL)
.build() .build()
.send(request, HttpResponse.BodyHandlers.ofString()); .send(request, HttpResponse.BodyHandlers.ofString());
assertThat(request.uri() assertThat(request.uri()
.toString(), equalTo("http://stackoverflow.com")); .toString(), equalTo("http://stackoverflow.com"));
assertThat(response.uri() assertThat(response.uri()
.toString(), equalTo("https://stackoverflow.com/")); .toString(), equalTo("https://stackoverflow.com/"));
} }
} }

View File

@ -14,6 +14,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>
</parent> </parent>
<dependencies> <dependencies>

View File

@ -14,7 +14,7 @@
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId> <artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath> <relativePath>../../parent-java</relativePath>
</parent> </parent>
<properties> <properties>

View File

@ -1,199 +1,199 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <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"> 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>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>core-java-8</artifactId> <artifactId>core-java-8</artifactId>
<version>0.1.0-SNAPSHOT</version> <version>0.1.0-SNAPSHOT</version>
<name>core-java-8</name> <name>core-java-8</name>
<packaging>jar</packaging> <packaging>jar</packaging>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId> <artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath> <relativePath>../../parent-java</relativePath>
</parent> </parent>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId> <artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version> <version>${commons-collections4.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
<version>${commons-io.version}</version> <version>${commons-io.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version> <version>${commons-lang3.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId> <artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version> <version>${commons-math3.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>log4j</groupId> <groupId>log4j</groupId>
<artifactId>log4j</artifactId> <artifactId>log4j</artifactId>
<version>${log4j.version}</version> <version>${log4j.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-codec</groupId> <groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId> <artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version> <version>${commons-codec.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
<version>${lombok.version}</version> <version>${lombok.version}</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!-- test scoped --> <!-- test scoped -->
<dependency> <dependency>
<groupId>org.assertj</groupId> <groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId> <artifactId>assertj-core</artifactId>
<version>${assertj.version}</version> <version>${assertj.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.jayway.awaitility</groupId> <groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId> <artifactId>awaitility</artifactId>
<version>${avaitility.version}</version> <version>${avaitility.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.openjdk.jmh</groupId> <groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId> <artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version> <version>${jmh-core.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.openjdk.jmh</groupId> <groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId> <artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version> <version>${jmh-generator.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.openjdk.jmh</groupId> <groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-bytecode</artifactId> <artifactId>jmh-generator-bytecode</artifactId>
<version>${jmh-generator.version}</version> <version>${jmh-generator.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.codepoetics</groupId> <groupId>com.codepoetics</groupId>
<artifactId>protonpack</artifactId> <artifactId>protonpack</artifactId>
<version>${protonpack.version}</version> <version>${protonpack.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.vavr</groupId> <groupId>io.vavr</groupId>
<artifactId>vavr</artifactId> <artifactId>vavr</artifactId>
<version>${vavr.version}</version> <version>${vavr.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>joda-time</groupId> <groupId>joda-time</groupId>
<artifactId>joda-time</artifactId> <artifactId>joda-time</artifactId>
<version>${joda.version}</version> <version>${joda.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.aspectj</groupId> <groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId> <artifactId>aspectjrt</artifactId>
<version>${asspectj.version}</version> <version>${asspectj.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.aspectj</groupId> <groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId> <artifactId>aspectjweaver</artifactId>
<version>${asspectj.version}</version> <version>${asspectj.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.powermock</groupId> <groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId> <artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version> <version>${powermock.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.powermock</groupId> <groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId> <artifactId>powermock-api-mockito2</artifactId>
<version>${powermock.version}</version> <version>${powermock.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.jmockit</groupId> <groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId> <artifactId>jmockit</artifactId>
<version>${jmockit.version}</version> <version>${jmockit.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>
<finalName>core-java-8</finalName> <finalName>core-java-8</finalName>
<resources> <resources>
<resource> <resource>
<directory>src/main/resources</directory> <directory>src/main/resources</directory>
<filtering>true</filtering> <filtering>true</filtering>
</resource> </resource>
</resources> </resources>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version> <version>${maven-compiler-plugin.version}</version>
<configuration> <configuration>
<source>1.8</source> <source>1.8</source>
<target>1.8</target> <target>1.8</target>
<compilerArgument>-parameters</compilerArgument> <compilerArgument>-parameters</compilerArgument>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot-maven-plugin.version}</version> <version>${spring-boot-maven-plugin.version}</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>repackage</goal> <goal>repackage</goal>
</goals> </goals>
<configuration> <configuration>
<classifier>spring-boot</classifier> <classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> <mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version> <version>${maven-surefire-plugin.version}</version>
<configuration> <configuration>
<argLine> <argLine>
-javaagent:${settings.localRepository}/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar -javaagent:${settings.localRepository}/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar
</argLine> </argLine>
<disableXmlReport>true</disableXmlReport> <disableXmlReport>true</disableXmlReport>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<properties> <properties>
<!-- util --> <!-- util -->
<commons-lang3.version>3.5</commons-lang3.version> <commons-lang3.version>3.5</commons-lang3.version>
<commons-math3.version>3.6.1</commons-math3.version> <commons-math3.version>3.6.1</commons-math3.version>
<commons-collections4.version>4.1</commons-collections4.version> <commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version> <collections-generic.version>4.01</collections-generic.version>
<commons-codec.version>1.10</commons-codec.version> <commons-codec.version>1.10</commons-codec.version>
<vavr.version>0.9.0</vavr.version> <vavr.version>0.9.0</vavr.version>
<protonpack.version>1.13</protonpack.version> <protonpack.version>1.13</protonpack.version>
<joda.version>2.10</joda.version> <joda.version>2.10</joda.version>
<!-- testing --> <!-- testing -->
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>
<asspectj.version>1.8.9</asspectj.version> <asspectj.version>1.8.9</asspectj.version>
<powermock.version>2.0.0-RC.4</powermock.version> <powermock.version>2.0.0-RC.4</powermock.version>
<jmockit.version>1.44</jmockit.version> <jmockit.version>1.44</jmockit.version>
<avaitility.version>1.7.0</avaitility.version> <avaitility.version>1.7.0</avaitility.version>
<jmh-core.version>1.19</jmh-core.version> <jmh-core.version>1.19</jmh-core.version>
<jmh-generator.version>1.19</jmh-generator.version> <jmh-generator.version>1.19</jmh-generator.version>
<spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version> <spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version>
<!-- plugins --> <!-- plugins -->
<maven-compiler-plugin.version>3.8.0</maven-compiler-plugin.version> <maven-compiler-plugin.version>3.8.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.22.1</maven-surefire-plugin.version> <maven-surefire-plugin.version>2.22.1</maven-surefire-plugin.version>
</properties> </properties>
</project> </project>

View File

@ -1,13 +1,13 @@
package com.baeldung.customannotations; package com.baeldung.customannotations;
import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.Target; import java.lang.annotation.Target;
@Retention(RUNTIME) @Retention(RUNTIME)
@Target(METHOD) @Target(METHOD)
public @interface Init { public @interface Init {
} }

View File

@ -1,13 +1,13 @@
package com.baeldung.customannotations; package com.baeldung.customannotations;
import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.Target; import java.lang.annotation.Target;
@Retention(RUNTIME) @Retention(RUNTIME)
@Target({ FIELD }) @Target({ FIELD })
public @interface JsonElement { public @interface JsonElement {
public String key() default ""; public String key() default "";
} }

View File

@ -1,13 +1,13 @@
package com.baeldung.customannotations; package com.baeldung.customannotations;
import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.Target; import java.lang.annotation.Target;
@Retention(RUNTIME) @Retention(RUNTIME)
@Target(TYPE) @Target(TYPE)
public @interface JsonSerializable { public @interface JsonSerializable {
} }

View File

@ -1,10 +1,10 @@
package com.baeldung.customannotations; package com.baeldung.customannotations;
public class JsonSerializationException extends RuntimeException { public class JsonSerializationException extends RuntimeException {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public JsonSerializationException(String message) { public JsonSerializationException(String message) {
super(message); super(message);
} }
} }

View File

@ -1,67 +1,67 @@
package com.baeldung.customannotations; package com.baeldung.customannotations;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class ObjectToJsonConverter { public class ObjectToJsonConverter {
public String convertToJson(Object object) throws JsonSerializationException { public String convertToJson(Object object) throws JsonSerializationException {
try { try {
checkIfSerializable(object); checkIfSerializable(object);
initializeObject(object); initializeObject(object);
return getJsonString(object); return getJsonString(object);
} catch (Exception e) { } catch (Exception e) {
throw new JsonSerializationException(e.getMessage()); throw new JsonSerializationException(e.getMessage());
} }
} }
private void checkIfSerializable(Object object) { private void checkIfSerializable(Object object) {
if (Objects.isNull(object)) { if (Objects.isNull(object)) {
throw new JsonSerializationException("Can't serialize a null object"); throw new JsonSerializationException("Can't serialize a null object");
} }
Class<?> clazz = object.getClass(); Class<?> clazz = object.getClass();
if (!clazz.isAnnotationPresent(JsonSerializable.class)) { if (!clazz.isAnnotationPresent(JsonSerializable.class)) {
throw new JsonSerializationException("The class " + clazz.getSimpleName() + " is not annotated with JsonSerializable"); throw new JsonSerializationException("The class " + clazz.getSimpleName() + " is not annotated with JsonSerializable");
} }
} }
private void initializeObject(Object object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { private void initializeObject(Object object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class<?> clazz = object.getClass(); Class<?> clazz = object.getClass();
for (Method method : clazz.getDeclaredMethods()) { for (Method method : clazz.getDeclaredMethods()) {
if (method.isAnnotationPresent(Init.class)) { if (method.isAnnotationPresent(Init.class)) {
method.setAccessible(true); method.setAccessible(true);
method.invoke(object); method.invoke(object);
} }
} }
} }
private String getJsonString(Object object) throws IllegalArgumentException, IllegalAccessException { private String getJsonString(Object object) throws IllegalArgumentException, IllegalAccessException {
Class<?> clazz = object.getClass(); Class<?> clazz = object.getClass();
Map<String, String> jsonElementsMap = new HashMap<>(); Map<String, String> jsonElementsMap = new HashMap<>();
for (Field field : clazz.getDeclaredFields()) { for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true); field.setAccessible(true);
if (field.isAnnotationPresent(JsonElement.class)) { if (field.isAnnotationPresent(JsonElement.class)) {
jsonElementsMap.put(getKey(field), (String) field.get(object)); jsonElementsMap.put(getKey(field), (String) field.get(object));
} }
} }
String jsonString = jsonElementsMap.entrySet() String jsonString = jsonElementsMap.entrySet()
.stream() .stream()
.map(entry -> "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"") .map(entry -> "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"")
.collect(Collectors.joining(",")); .collect(Collectors.joining(","));
return "{" + jsonString + "}"; return "{" + jsonString + "}";
} }
private String getKey(Field field) { private String getKey(Field field) {
String value = field.getAnnotation(JsonElement.class) String value = field.getAnnotation(JsonElement.class)
.key(); .key();
return value.isEmpty() ? field.getName() : value; return value.isEmpty() ? field.getName() : value;
} }
} }

View File

@ -1,66 +1,66 @@
package com.baeldung.customannotations; package com.baeldung.customannotations;
@JsonSerializable @JsonSerializable
public class Person { public class Person {
@JsonElement @JsonElement
private String firstName; private String firstName;
@JsonElement @JsonElement
private String lastName; private String lastName;
@JsonElement(key = "personAge") @JsonElement(key = "personAge")
private String age; private String age;
private String address; private String address;
public Person(String firstName, String lastName) { public Person(String firstName, String lastName) {
super(); super();
this.firstName = firstName; this.firstName = firstName;
this.lastName = lastName; this.lastName = lastName;
} }
public Person(String firstName, String lastName, String age) { public Person(String firstName, String lastName, String age) {
this.firstName = firstName; this.firstName = firstName;
this.lastName = lastName; this.lastName = lastName;
this.age = age; this.age = age;
} }
@Init @Init
private void initNames() { private void initNames() {
this.firstName = this.firstName.substring(0, 1) this.firstName = this.firstName.substring(0, 1)
.toUpperCase() + this.firstName.substring(1); .toUpperCase() + this.firstName.substring(1);
this.lastName = this.lastName.substring(0, 1) this.lastName = this.lastName.substring(0, 1)
.toUpperCase() + this.lastName.substring(1); .toUpperCase() + this.lastName.substring(1);
} }
public String getFirstName() { public String getFirstName() {
return firstName; return firstName;
} }
public void setFirstName(String firstName) { public void setFirstName(String firstName) {
this.firstName = firstName; this.firstName = firstName;
} }
public String getLastName() { public String getLastName() {
return lastName; return lastName;
} }
public void setLastName(String lastName) { public void setLastName(String lastName) {
this.lastName = lastName; this.lastName = lastName;
} }
public String getAge() { public String getAge() {
return age; return age;
} }
public void setAge(String age) { public void setAge(String age) {
this.age = age; this.age = age;
} }
public String getAddress() { public String getAddress() {
return address; return address;
} }
public void setAddress(String address) { public void setAddress(String address) {
this.address = address; this.address = address;
} }
} }

Some files were not shown because too many files have changed in this diff Show More