From d3c73637c287229ae619d020140fe433dc33f34a Mon Sep 17 00:00:00 2001 From: Roger Yates <587230+rojyates@users.noreply.github.com> Date: Sat, 9 Jan 2021 07:54:57 +1000 Subject: [PATCH 01/51] BAEL-4614 JVM property java.security.egd --- .../baeldung/egd/JavaSecurityEgdTester.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 core-java-modules/core-java-security-2/src/main/java/com/baeldung/egd/JavaSecurityEgdTester.java diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/egd/JavaSecurityEgdTester.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/egd/JavaSecurityEgdTester.java new file mode 100644 index 0000000000..347d3b4cba --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/egd/JavaSecurityEgdTester.java @@ -0,0 +1,23 @@ +package com.baeldung.egd; + +import java.security.SecureRandom; + +/** + * JavaSecurityEgdTester - run this with JVM parameter java.security.egd, e.g.: + * java -Djava.security.egd=file:/dev/urandom -cp . com.baeldung.egd.JavaSecurityEgdTester + */ +public class JavaSecurityEgdTester { + public static final double NANOSECS = 1000000000.0; + public static final String JAVA_SECURITY_EGD = "java.security.egd"; + + public static void main(String[] args) { + SecureRandom secureRandom = new SecureRandom(); + long start = System.nanoTime(); + byte[] randomBytes = new byte[256]; + secureRandom.nextBytes(randomBytes); + double duration = (System.nanoTime() - start) / NANOSECS; + + String message = String.format("java.security.egd=%s took %.3f seconds and used the %s algorithm", System.getProperty(JAVA_SECURITY_EGD), duration, secureRandom.getAlgorithm()); + System.out.println(message); + } +} From df31e606c3d8486dfb99a0be50491e74097b2810 Mon Sep 17 00:00:00 2001 From: Trixi Turny Date: Sat, 9 Jan 2021 15:55:24 +0000 Subject: [PATCH 02/51] BAEL-4748 implement UserConsumerService with webClient and write UnitTests --- .../webclient/json/UserConsumerService.java | 16 ++++ .../json/UserConsumerServiceImpl.java | 90 +++++++++++++++++++ .../webclient/json/model/Address.java | 29 ++++++ .../baeldung/webclient/json/model/User.java | 30 +++++++ .../json/UserConsumerServiceImplUnitTest.java | 74 +++++++++++++++ 5 files changed, 239 insertions(+) create mode 100644 spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/UserConsumerService.java create mode 100644 spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/UserConsumerServiceImpl.java create mode 100644 spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Address.java create mode 100644 spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/User.java create mode 100644 spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/UserConsumerServiceImplUnitTest.java diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/UserConsumerService.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/UserConsumerService.java new file mode 100644 index 0000000000..9afc207ff2 --- /dev/null +++ b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/UserConsumerService.java @@ -0,0 +1,16 @@ +package com.baeldung.webclient.json; + +import java.util.List; + +public interface UserConsumerService { + + List processUserDataFromObjectArray(); + + List processUserDataFromUserArray(); + + List processUserDataFromUserList(); + + List processNestedUserDataFromUserArray(); + + List processNestedUserDataFromUserList(); +} diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/UserConsumerServiceImpl.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/UserConsumerServiceImpl.java new file mode 100644 index 0000000000..30cd4a5617 --- /dev/null +++ b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/UserConsumerServiceImpl.java @@ -0,0 +1,90 @@ +package com.baeldung.webclient.json; + +import com.baeldung.webclient.json.model.Address; +import com.baeldung.webclient.json.model.User; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.MediaType; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class UserConsumerServiceImpl implements UserConsumerService { + + private final WebClient webClient; + private static final ObjectMapper mapper = new ObjectMapper(); + + public UserConsumerServiceImpl(WebClient webClient) { + this.webClient = webClient; + } + @Override + public List processUserDataFromObjectArray() { + Mono response = webClient.get() + .accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono(Object[].class).log(); + Object[] objects = response.block(); + return Arrays.stream(objects) + .map(object -> mapper.convertValue(object, User.class)) + .map(User::getName) + .collect(Collectors.toList()); + } + + @Override + public List processUserDataFromUserArray() { + Mono response = + webClient.get() + .accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono(User[].class).log(); + + User[] userArray = response.block(); + return Arrays.stream(userArray) + .map(User::getName) + .collect(Collectors.toList()); + } + + @Override + public List processUserDataFromUserList() { + Mono> response = webClient.get() + .accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() {}); + List userList = response.block(); + + return userList.stream() + .map(User::getName) + .collect(Collectors.toList()); + } + + @Override + public List processNestedUserDataFromUserArray() { + Mono response = webClient.get() + .accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono(User[].class).log(); + User[] userArray = response.block(); + + return Arrays.stream(userArray) + .flatMap(user -> user.getAddressList().stream()) + .map(Address::getPostCode) + .collect(Collectors.toList()); + } + + @Override + public List processNestedUserDataFromUserList() { + Mono> response = webClient.get() + .accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() {}); + + List userList = response.block(); + return userList.stream() + .flatMap(user -> user.getAddressList().stream()) + .map(Address::getPostCode) + .collect(Collectors.toList()); + } +} \ No newline at end of file diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Address.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Address.java new file mode 100644 index 0000000000..cc4323b72b --- /dev/null +++ b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Address.java @@ -0,0 +1,29 @@ +package com.baeldung.webclient.json.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class Address { + private final String addressLine1; + private final String addressLine2; + private final String town; + private final String postCode; + + @JsonCreator + public Address( + @JsonProperty("addressLine1") String addressLine1, + @JsonProperty("addressLine2") String addressLine2, + @JsonProperty("town") String town, + @JsonProperty("postCode") String postCode) { + this.addressLine1 = addressLine1; + this.addressLine2 = addressLine2; + this.town = town; + this.postCode = postCode; + } + public String getPostCode() { + return postCode; + } +} diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/User.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/User.java new file mode 100644 index 0000000000..6ed359f9db --- /dev/null +++ b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/User.java @@ -0,0 +1,30 @@ +package com.baeldung.webclient.json.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class User { + private final int id; + private final String name; + private final List
addressList; + + @JsonCreator + public User( + @JsonProperty("id") int id, + @JsonProperty("name") String name, + @JsonProperty("addressList") List
addressList) { + this.id = id; + this.name = name; + this.addressList = addressList; + } + + public String getName() { + return name; + } + + public List
getAddressList() { return addressList; } +} diff --git a/spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/UserConsumerServiceImplUnitTest.java b/spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/UserConsumerServiceImplUnitTest.java new file mode 100644 index 0000000000..151554efde --- /dev/null +++ b/spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/UserConsumerServiceImplUnitTest.java @@ -0,0 +1,74 @@ +package com.baeldung.webclient.json; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.web.reactive.function.client.ClientResponse; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; + +public class UserConsumerServiceImplUnitTest { + + private static String USER_JSON = "[{\"id\":1,\"name\":\"user1\",\"addressList\":[{\"addressLine1\":\"address1_addressLine1\",\"addressLine2\":\"address1_addressLine2\",\"town\":\"address1_town\",\"postCode\":\"user1_address1_postCode\"}," + + "{\"addressLine1\":\"address2_addressLine1\",\"addressLine2\":\"address2_addressLine2\",\"town\":\"address2_town\",\"postCode\":\"user1_address2_postCode\"}]}," + + "{\"id\":2,\"name\":\"user2\",\"addressList\":[{\"addressLine1\":\"address1_addressLine1\",\"addressLine2\":\"address1_addressLine2\",\"town\":\"address1_town\",\"postCode\":\"user2_address1_postCode\"}]}]"; + + private static String BASE_URL = "http://localhost:8080"; + + WebClient webClientMock = WebClient.builder() + .exchangeFunction(clientRequest -> Mono.just(ClientResponse.create(HttpStatus.OK) + .header("content-type", "application/json") + .body(USER_JSON) + .build())) + .build(); + + private final UserConsumerService tested = new UserConsumerServiceImpl(webClientMock); + + @Test + void when_processUserDataFromObjectArray_then_OK() { + List expected = Arrays.asList("user1", "user2"); + List actual = tested.processUserDataFromObjectArray(); + assertThat(actual, contains(expected.get(0), expected.get(1))); + } + + @Test + void when_processUserDataFromUserArray_then_OK() { + List expected = Arrays.asList("user1", "user2"); + List actual = tested.processUserDataFromUserArray(); + assertThat(actual, contains(expected.get(0), expected.get(1))); + } + + @Test + void when_processUserDataFromUserList_then_OK() { + List expected = Arrays.asList("user1", "user2"); + List actual = tested.processUserDataFromUserList(); + assertThat(actual, contains(expected.get(0), expected.get(1))); + } + + @Test + void when_processNestedUserDataFromUserArray_then_OK() { + List expected = Arrays.asList( + "user1_address1_postCode", + "user1_address2_postCode", + "user2_address1_postCode"); + + List actual = tested.processNestedUserDataFromUserArray(); + assertThat(actual, contains(expected.get(0), expected.get(1), expected.get(2))); + } + + @Test + void when_processNestedUserDataFromUserList_then_OK() { + List expected = Arrays.asList( + "user1_address1_postCode", + "user1_address2_postCode", + "user2_address1_postCode"); + + List actual = tested.processNestedUserDataFromUserList(); + assertThat(actual, contains(expected.get(0), expected.get(1), expected.get(2))); + } +} \ No newline at end of file From 100e3b652dd7bdfc7369799a292c089dde77a9fb Mon Sep 17 00:00:00 2001 From: Azhwani Date: Sun, 17 Jan 2021 02:08:18 +0100 Subject: [PATCH 03/51] first commit --- .../RestTemplateExceptionApplication.java | 13 +++++ .../controller/ProductApi.java | 50 +++++++++++++++++ .../model/Criterion.java | 28 ++++++++++ .../resttemplateexception/model/Product.java | 43 +++++++++++++++ .../RestTemplateExceptionLiveTest.java | 53 +++++++++++++++++++ 5 files changed, 187 insertions(+) create mode 100644 spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/RestTemplateExceptionApplication.java create mode 100644 spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/controller/ProductApi.java create mode 100644 spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/model/Criterion.java create mode 100644 spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/model/Product.java create mode 100644 spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/resttemplateexception/RestTemplateExceptionLiveTest.java diff --git a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/RestTemplateExceptionApplication.java b/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/RestTemplateExceptionApplication.java new file mode 100644 index 0000000000..84a337f5ee --- /dev/null +++ b/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/RestTemplateExceptionApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.resttemplateexception; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class RestTemplateExceptionApplication { + + public static void main(String[] args) { + SpringApplication.run(RestTemplateExceptionApplication.class, args); + } + +} diff --git a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/controller/ProductApi.java b/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/controller/ProductApi.java new file mode 100644 index 0000000000..66fbfa487d --- /dev/null +++ b/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/controller/ProductApi.java @@ -0,0 +1,50 @@ +package com.baeldung.resttemplateexception.controller; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.resttemplateexception.model.Criterion; +import com.baeldung.resttemplateexception.model.Product; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RestController +@RequestMapping("/api") +public class ProductApi { + + private List productList = new ArrayList<>(Arrays.asList(new Product(1, "Acer Aspire 5", 437), new Product(2, "ASUS VivoBook", 650), new Product(3, "Lenovo Legion", 990))); + + @GetMapping("/get") + public Product get(@RequestParam String criterion) throws JsonMappingException, JsonProcessingException { + + ObjectMapper objectMapper = new ObjectMapper(); + Criterion crt; + + crt = objectMapper.readValue(criterion, Criterion.class); + if (crt.getProp().equals("name")) + return findByName(crt.getValue()); + + // Search by other properties (id,price) + + return null; + } + + private Product findByName(String name) { + for (Product product : this.productList) { + if (product.getName().equals(name)) { + return product; + } + } + return null; + } + + // Other methods + +} diff --git a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/model/Criterion.java b/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/model/Criterion.java new file mode 100644 index 0000000000..9a96ad4dc3 --- /dev/null +++ b/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/model/Criterion.java @@ -0,0 +1,28 @@ +package com.baeldung.resttemplateexception.model; + +public class Criterion { + + private String prop; + private String value; + + public Criterion() { + + } + + public String getProp() { + return prop; + } + + public void setProp(String prop) { + this.prop = prop; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} diff --git a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/model/Product.java b/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/model/Product.java new file mode 100644 index 0000000000..e4cc29279c --- /dev/null +++ b/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/model/Product.java @@ -0,0 +1,43 @@ +package com.baeldung.resttemplateexception.model; + +public class Product { + + private int id; + private String name; + private double price; + + public Product() { + + } + + public Product(int id, String name, double price) { + this.id = id; + this.name = name; + this.price = price; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } + +} diff --git a/spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/resttemplateexception/RestTemplateExceptionLiveTest.java b/spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/resttemplateexception/RestTemplateExceptionLiveTest.java new file mode 100644 index 0000000000..f5938e1f0a --- /dev/null +++ b/spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/resttemplateexception/RestTemplateExceptionLiveTest.java @@ -0,0 +1,53 @@ +package com.baeldung.resttemplateexception; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; + +import com.baeldung.resttemplateexception.model.Product; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { RestTemplate.class, RestTemplateExceptionApplication.class }) +public class RestTemplateExceptionLiveTest { + + @Autowired + RestTemplate restTemplate; + + @Test(expected = IllegalArgumentException.class) + public void givenGetUrl_whenJsonIsPassed_thenThrowException() { + + String url = "http://localhost:8080/spring-rest/api/get?criterion={\"prop\":\"name\",\"value\":\"ASUS VivoBook\"}"; + Product product = restTemplate.getForObject(url, Product.class); + + } + + @Test + public void givenGetUrl_whenJsonIsPassed_thenGetProduct() { + + String criterion = "{\"prop\":\"name\",\"value\":\"ASUS VivoBook\"}"; + String url = "http://localhost:8080/spring-rest/api/get?criterion={criterion}"; + Product product = restTemplate.getForObject(url, Product.class, criterion); + + assertEquals(product.getPrice(), 650, 0); + + } + + @Test + public void givenGetUrl_whenJsonIsPassed_thenReturnProduct() { + + String criterion = "{\"prop\":\"name\",\"value\":\"Acer Aspire 5\"}"; + String url = "http://localhost:8080/spring-rest/api/get"; + + UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url).queryParam("criterion", criterion); + Product product = restTemplate.getForObject(builder.build().toUri(), Product.class); + + assertEquals(product.getId(), 1, 0); + + } +} From 8396dabf774f1b66bc8a74015b2b6385fc105af3 Mon Sep 17 00:00:00 2001 From: Azhwani Date: Sun, 17 Jan 2021 02:27:34 +0100 Subject: [PATCH 04/51] quick fix --- .../resttemplateexception/controller/ProductApi.java | 6 +----- .../RestTemplateExceptionLiveTest.java | 6 ------ 2 files changed, 1 insertion(+), 11 deletions(-) diff --git a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/controller/ProductApi.java b/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/controller/ProductApi.java index 66fbfa487d..2c530cae2b 100644 --- a/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/controller/ProductApi.java +++ b/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/resttemplateexception/controller/ProductApi.java @@ -23,11 +23,8 @@ public class ProductApi { @GetMapping("/get") public Product get(@RequestParam String criterion) throws JsonMappingException, JsonProcessingException { - ObjectMapper objectMapper = new ObjectMapper(); - Criterion crt; - - crt = objectMapper.readValue(criterion, Criterion.class); + Criterion crt = objectMapper.readValue(criterion, Criterion.class); if (crt.getProp().equals("name")) return findByName(crt.getValue()); @@ -46,5 +43,4 @@ public class ProductApi { } // Other methods - } diff --git a/spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/resttemplateexception/RestTemplateExceptionLiveTest.java b/spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/resttemplateexception/RestTemplateExceptionLiveTest.java index f5938e1f0a..adfb8ffa4e 100644 --- a/spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/resttemplateexception/RestTemplateExceptionLiveTest.java +++ b/spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/resttemplateexception/RestTemplateExceptionLiveTest.java @@ -21,26 +21,21 @@ public class RestTemplateExceptionLiveTest { @Test(expected = IllegalArgumentException.class) public void givenGetUrl_whenJsonIsPassed_thenThrowException() { - String url = "http://localhost:8080/spring-rest/api/get?criterion={\"prop\":\"name\",\"value\":\"ASUS VivoBook\"}"; Product product = restTemplate.getForObject(url, Product.class); - } @Test public void givenGetUrl_whenJsonIsPassed_thenGetProduct() { - String criterion = "{\"prop\":\"name\",\"value\":\"ASUS VivoBook\"}"; String url = "http://localhost:8080/spring-rest/api/get?criterion={criterion}"; Product product = restTemplate.getForObject(url, Product.class, criterion); assertEquals(product.getPrice(), 650, 0); - } @Test public void givenGetUrl_whenJsonIsPassed_thenReturnProduct() { - String criterion = "{\"prop\":\"name\",\"value\":\"Acer Aspire 5\"}"; String url = "http://localhost:8080/spring-rest/api/get"; @@ -48,6 +43,5 @@ public class RestTemplateExceptionLiveTest { Product product = restTemplate.getForObject(builder.build().toUri(), Product.class); assertEquals(product.getId(), 1, 0); - } } From 0c5441380750ef523d88d39469af1102d4e2d711 Mon Sep 17 00:00:00 2001 From: "Kent@lhind.hp.g5" Date: Fri, 22 Jan 2021 19:56:18 +0100 Subject: [PATCH 05/51] BAEL-2517 --- .../core-java-lang-oop-generics/pom.xml | 28 ++++++++++++ .../UncheckedConversion.java | 45 +++++++++++++++++++ .../UncheckedConversionUnitTest.java | 39 ++++++++++++++++ 3 files changed, 112 insertions(+) create mode 100644 core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/uncheckedconversion/UncheckedConversion.java create mode 100644 core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/uncheckedconversion/UncheckedConversionUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-generics/pom.xml b/core-java-modules/core-java-lang-oop-generics/pom.xml index 65a0aeac59..1a538edac9 100644 --- a/core-java-modules/core-java-lang-oop-generics/pom.xml +++ b/core-java-modules/core-java-lang-oop-generics/pom.xml @@ -13,4 +13,32 @@ core-java-lang-oop-generics jar + + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + + + 1.8 + 1.8 + + \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/uncheckedconversion/UncheckedConversion.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/uncheckedconversion/UncheckedConversion.java new file mode 100644 index 0000000000..9ad4a92077 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/uncheckedconversion/UncheckedConversion.java @@ -0,0 +1,45 @@ +package com.baeldung.uncheckedconversion; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; + +public class UncheckedConversion { + public static List getRawList() { + List result = new ArrayList(); + result.add("I am the 1st String."); + result.add("I am the 2nd String."); + result.add("I am the 3rd String."); + return result; + } + + public static List getRawListWithMixedTypes() { + List result = new ArrayList(); + result.add("I am the 1st String."); + result.add("I am the 2nd String."); + result.add("I am the 3rd String."); + result.add(new Date()); + return result; + } + + public static List castList(Class clazz, Collection rawCollection) { + List result = new ArrayList<>(rawCollection.size()); + for (Object o : rawCollection) { + try { + result.add(clazz.cast(o)); + } catch (ClassCastException e) { + // log the exception or other error handling + } + } + return result; + } + + public static List castList2(Class clazz, Collection rawCollection) throws ClassCastException { + List result = new ArrayList<>(rawCollection.size()); + for (Object o : rawCollection) { + result.add(clazz.cast(o)); + } + return result; + } +} diff --git a/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/uncheckedconversion/UncheckedConversionUnitTest.java b/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/uncheckedconversion/UncheckedConversionUnitTest.java new file mode 100644 index 0000000000..37b9a878d3 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/uncheckedconversion/UncheckedConversionUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.uncheckedconversion; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.List; + +public class UncheckedConversionUnitTest { + + @Test + public void givenRawList_whenAssignToTypedList_shouldHaveCompilerWarning() { + List fromRawList = UncheckedConversion.getRawList(); + Assert.assertEquals(3, fromRawList.size()); + Assert.assertEquals("I am the 1st String.", fromRawList.get(0)); + } + + @Test(expected = ClassCastException.class) + public void givenRawList_whenListHasMixedType_shouldThrowClassCastException() { + List fromRawList = UncheckedConversion.getRawListWithMixedTypes(); + Assert.assertEquals(4, fromRawList.size()); + Assert.assertFalse(fromRawList.get(3).endsWith("String.")); + } + + @Test + public void givenRawList_whenAssignToTypedListAfterCallingCastList_shouldOnlyHaveElementsWithExpectedType() { + List rawList = UncheckedConversion.getRawListWithMixedTypes(); + List strList = UncheckedConversion.castList(String.class, rawList); + Assert.assertEquals(4, rawList.size()); + Assert.assertEquals("One element with the wrong type has been filtered out.", 3, strList.size()); + Assert.assertTrue(strList.stream().allMatch(el -> el.endsWith("String."))); + } + + @Test(expected = ClassCastException.class) + public void givenRawListWithWrongType_whenAssignToTypedListAfterCallingCastList2_shouldThrowException() { + List rawList = UncheckedConversion.getRawListWithMixedTypes(); + UncheckedConversion.castList2(String.class, rawList); + } + +} From 70a0e0de969efdcb8da019e01a1ca122b47cb6e1 Mon Sep 17 00:00:00 2001 From: Trixi Turny Date: Sat, 23 Jan 2021 11:19:30 +0000 Subject: [PATCH 06/51] BAEL-4748 change user to reader and address to favouriteBooks --- .../webclient/json/ReaderConsumerService.java | 16 ++++ .../json/ReaderConsumerServiceImpl.java | 90 +++++++++++++++++++ .../webclient/json/UserConsumerService.java | 16 ---- .../json/UserConsumerServiceImpl.java | 90 ------------------- .../webclient/json/model/Address.java | 29 ------ .../baeldung/webclient/json/model/Book.java | 22 +++++ .../baeldung/webclient/json/model/Reader.java | 0 .../baeldung/webclient/json/model/User.java | 30 ------- .../ReaderConsumerServiceImplUnitTest.java | 77 ++++++++++++++++ .../json/UserConsumerServiceImplUnitTest.java | 74 --------------- 10 files changed, 205 insertions(+), 239 deletions(-) create mode 100644 spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/ReaderConsumerService.java create mode 100644 spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/ReaderConsumerServiceImpl.java delete mode 100644 spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/UserConsumerService.java delete mode 100644 spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/UserConsumerServiceImpl.java delete mode 100644 spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Address.java create mode 100644 spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Book.java create mode 100644 spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Reader.java delete mode 100644 spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/User.java create mode 100644 spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/ReaderConsumerServiceImplUnitTest.java delete mode 100644 spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/UserConsumerServiceImplUnitTest.java diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/ReaderConsumerService.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/ReaderConsumerService.java new file mode 100644 index 0000000000..b0bc71d2ed --- /dev/null +++ b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/ReaderConsumerService.java @@ -0,0 +1,16 @@ +package com.baeldung.webclient.json; + +import java.util.List; + +public interface ReaderConsumerService { + + List processReaderDataFromObjectArray(); + + List processReaderDataFromReaderArray(); + + List processReaderDataFromReaderList(); + + List processNestedReaderDataFromReaderArray(); + + List processNestedReaderDataFromReaderList(); +} diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/ReaderConsumerServiceImpl.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/ReaderConsumerServiceImpl.java new file mode 100644 index 0000000000..d1800a7f65 --- /dev/null +++ b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/ReaderConsumerServiceImpl.java @@ -0,0 +1,90 @@ +package com.baeldung.webclient.json; + +import com.baeldung.webclient.json.model.Book; +import com.baeldung.webclient.json.model.Reader; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.MediaType; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class ReaderConsumerServiceImpl implements ReaderConsumerService { + + private final WebClient webClient; + private static final ObjectMapper mapper = new ObjectMapper(); + + public ReaderConsumerServiceImpl(WebClient webClient) { + this.webClient = webClient; + } + @Override + public List processReaderDataFromObjectArray() { + Mono response = webClient.get() + .accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono(Object[].class).log(); + Object[] objects = response.block(); + return Arrays.stream(objects) + .map(object -> mapper.convertValue(object, Reader.class)) + .map(Reader::getName) + .collect(Collectors.toList()); + } + + @Override + public List processReaderDataFromReaderArray() { + Mono response = + webClient.get() + .accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono(Reader[].class).log(); + + Reader[] readers = response.block(); + return Arrays.stream(readers) + .map(Reader::getName) + .collect(Collectors.toList()); + } + + @Override + public List processReaderDataFromReaderList() { + Mono> response = webClient.get() + .accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() {}); + List readers = response.block(); + + return readers.stream() + .map(Reader::getName) + .collect(Collectors.toList()); + } + + @Override + public List processNestedReaderDataFromReaderArray() { + Mono response = webClient.get() + .accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono(Reader[].class).log(); + Reader[] readers = response.block(); + + return Arrays.stream(readers) + .flatMap(reader -> reader.getFavouriteBooks().stream()) + .map(Book::getAuthor) + .collect(Collectors.toList()); + } + + @Override + public List processNestedReaderDataFromReaderList() { + Mono> response = webClient.get() + .accept(MediaType.APPLICATION_JSON) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() {}); + + List readers = response.block(); + return readers.stream() + .flatMap(reader -> reader.getFavouriteBooks().stream()) + .map(Book::getAuthor) + .collect(Collectors.toList()); + } +} \ No newline at end of file diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/UserConsumerService.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/UserConsumerService.java deleted file mode 100644 index 9afc207ff2..0000000000 --- a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/UserConsumerService.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.webclient.json; - -import java.util.List; - -public interface UserConsumerService { - - List processUserDataFromObjectArray(); - - List processUserDataFromUserArray(); - - List processUserDataFromUserList(); - - List processNestedUserDataFromUserArray(); - - List processNestedUserDataFromUserList(); -} diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/UserConsumerServiceImpl.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/UserConsumerServiceImpl.java deleted file mode 100644 index 30cd4a5617..0000000000 --- a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/UserConsumerServiceImpl.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.baeldung.webclient.json; - -import com.baeldung.webclient.json.model.Address; -import com.baeldung.webclient.json.model.User; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.MediaType; -import org.springframework.web.reactive.function.client.WebClient; -import reactor.core.publisher.Mono; - -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -public class UserConsumerServiceImpl implements UserConsumerService { - - private final WebClient webClient; - private static final ObjectMapper mapper = new ObjectMapper(); - - public UserConsumerServiceImpl(WebClient webClient) { - this.webClient = webClient; - } - @Override - public List processUserDataFromObjectArray() { - Mono response = webClient.get() - .accept(MediaType.APPLICATION_JSON) - .retrieve() - .bodyToMono(Object[].class).log(); - Object[] objects = response.block(); - return Arrays.stream(objects) - .map(object -> mapper.convertValue(object, User.class)) - .map(User::getName) - .collect(Collectors.toList()); - } - - @Override - public List processUserDataFromUserArray() { - Mono response = - webClient.get() - .accept(MediaType.APPLICATION_JSON) - .retrieve() - .bodyToMono(User[].class).log(); - - User[] userArray = response.block(); - return Arrays.stream(userArray) - .map(User::getName) - .collect(Collectors.toList()); - } - - @Override - public List processUserDataFromUserList() { - Mono> response = webClient.get() - .accept(MediaType.APPLICATION_JSON) - .retrieve() - .bodyToMono(new ParameterizedTypeReference>() {}); - List userList = response.block(); - - return userList.stream() - .map(User::getName) - .collect(Collectors.toList()); - } - - @Override - public List processNestedUserDataFromUserArray() { - Mono response = webClient.get() - .accept(MediaType.APPLICATION_JSON) - .retrieve() - .bodyToMono(User[].class).log(); - User[] userArray = response.block(); - - return Arrays.stream(userArray) - .flatMap(user -> user.getAddressList().stream()) - .map(Address::getPostCode) - .collect(Collectors.toList()); - } - - @Override - public List processNestedUserDataFromUserList() { - Mono> response = webClient.get() - .accept(MediaType.APPLICATION_JSON) - .retrieve() - .bodyToMono(new ParameterizedTypeReference>() {}); - - List userList = response.block(); - return userList.stream() - .flatMap(user -> user.getAddressList().stream()) - .map(Address::getPostCode) - .collect(Collectors.toList()); - } -} \ No newline at end of file diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Address.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Address.java deleted file mode 100644 index cc4323b72b..0000000000 --- a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Address.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.webclient.json.model; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; - - -@JsonInclude(JsonInclude.Include.NON_NULL) -public class Address { - private final String addressLine1; - private final String addressLine2; - private final String town; - private final String postCode; - - @JsonCreator - public Address( - @JsonProperty("addressLine1") String addressLine1, - @JsonProperty("addressLine2") String addressLine2, - @JsonProperty("town") String town, - @JsonProperty("postCode") String postCode) { - this.addressLine1 = addressLine1; - this.addressLine2 = addressLine2; - this.town = town; - this.postCode = postCode; - } - public String getPostCode() { - return postCode; - } -} diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Book.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Book.java new file mode 100644 index 0000000000..cb3fb258d4 --- /dev/null +++ b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Book.java @@ -0,0 +1,22 @@ +package com.baeldung.webclient.json.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class Book { + private final String author; + private final String title; + + @JsonCreator + public Book( + @JsonProperty("author") String author, + @JsonProperty("title") String title) { + this.author = author; + this.title = title; + } + public String getAuthor() { + return this.author; + } +} diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Reader.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Reader.java new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/User.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/User.java deleted file mode 100644 index 6ed359f9db..0000000000 --- a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/User.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.webclient.json.model; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.List; - -@JsonInclude(JsonInclude.Include.NON_NULL) -public class User { - private final int id; - private final String name; - private final List
addressList; - - @JsonCreator - public User( - @JsonProperty("id") int id, - @JsonProperty("name") String name, - @JsonProperty("addressList") List
addressList) { - this.id = id; - this.name = name; - this.addressList = addressList; - } - - public String getName() { - return name; - } - - public List
getAddressList() { return addressList; } -} diff --git a/spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/ReaderConsumerServiceImplUnitTest.java b/spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/ReaderConsumerServiceImplUnitTest.java new file mode 100644 index 0000000000..92f7bf4f3f --- /dev/null +++ b/spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/ReaderConsumerServiceImplUnitTest.java @@ -0,0 +1,77 @@ +package com.baeldung.webclient.json; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.web.reactive.function.client.ClientResponse; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Mono; + +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; + +public class ReaderConsumerServiceImplUnitTest { + + private static String READER_JSON = "[{\"id\":1,\"name\":\"reader1\",\"favouriteBooks\":[{\"author\":\"Milan Kundera\",\"title\":\"The Unbearable Lightness of Being\"}," + + "{\"author\":\"Charles Dickens\",\"title\":\"Oliver Twist\"}]}," + + "{\"id\":2,\"name\":\"reader2\",\"favouriteBooks\":[{\"author\":\"J.R.R. Tolkien\",\"title\":\"Lord of the Rings\"}, " + + "{\"author\":\"Douglas Adams\",\"title\":\"The Hitchhiker\'s Guide to the Galaxy\"}]}]"; + + private static String BASE_URL = "http://localhost:8080"; + + WebClient webClientMock = WebClient.builder() + .exchangeFunction(clientRequest -> Mono.just(ClientResponse.create(HttpStatus.OK) + .header("content-type", "application/json") + .body(READER_JSON) + .build())) + .build(); + + private final ReaderConsumerService tested = new ReaderConsumerServiceImpl(webClientMock); + + @Test + void when_processReaderDataFromObjectArray_then_OK() { + List expected = Arrays.asList("reader1", "reader2"); + List actual = tested.processReaderDataFromObjectArray(); + assertThat(actual, contains(expected.get(0), expected.get(1))); + } + + @Test + void when_processReaderDataFromReaderArray_then_OK() { + List expected = Arrays.asList("reader1", "reader2"); + List actual = tested.processReaderDataFromReaderArray(); + assertThat(actual, contains(expected.get(0), expected.get(1))); + } + + @Test + void when_processReaderDataFromReaderList_then_OK() { + List expected = Arrays.asList("reader1", "reader2"); + List actual = tested.processReaderDataFromReaderList(); + assertThat(actual, contains(expected.get(0), expected.get(1))); + } + + @Test + void when_processNestedReaderDataFromReaderArray_then_OK() { + List expected = Arrays.asList( + "Milan Kundera", + "Charles Dickens", + "J.R.R. Tolkien", + "Douglas Adams"); + + List actual = tested.processNestedReaderDataFromReaderArray(); + assertThat(actual, contains(expected.get(0), expected.get(1), expected.get(2), expected.get(3))); + } + + @Test + void when_processNestedReaderDataFromReaderList_then_OK() { + List expected = Arrays.asList( + "Milan Kundera", + "Charles Dickens", + "J.R.R. Tolkien", + "Douglas Adams"); + + List actual = tested.processNestedReaderDataFromReaderList(); + assertThat(actual, contains(expected.get(0), expected.get(1), expected.get(2), expected.get(3))); + } +} \ No newline at end of file diff --git a/spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/UserConsumerServiceImplUnitTest.java b/spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/UserConsumerServiceImplUnitTest.java deleted file mode 100644 index 151554efde..0000000000 --- a/spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/UserConsumerServiceImplUnitTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.webclient.json; - -import org.junit.jupiter.api.Test; -import org.springframework.http.HttpStatus; -import org.springframework.web.reactive.function.client.ClientResponse; -import org.springframework.web.reactive.function.client.WebClient; -import reactor.core.publisher.Mono; - -import java.util.Arrays; -import java.util.List; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; - -public class UserConsumerServiceImplUnitTest { - - private static String USER_JSON = "[{\"id\":1,\"name\":\"user1\",\"addressList\":[{\"addressLine1\":\"address1_addressLine1\",\"addressLine2\":\"address1_addressLine2\",\"town\":\"address1_town\",\"postCode\":\"user1_address1_postCode\"}," + - "{\"addressLine1\":\"address2_addressLine1\",\"addressLine2\":\"address2_addressLine2\",\"town\":\"address2_town\",\"postCode\":\"user1_address2_postCode\"}]}," + - "{\"id\":2,\"name\":\"user2\",\"addressList\":[{\"addressLine1\":\"address1_addressLine1\",\"addressLine2\":\"address1_addressLine2\",\"town\":\"address1_town\",\"postCode\":\"user2_address1_postCode\"}]}]"; - - private static String BASE_URL = "http://localhost:8080"; - - WebClient webClientMock = WebClient.builder() - .exchangeFunction(clientRequest -> Mono.just(ClientResponse.create(HttpStatus.OK) - .header("content-type", "application/json") - .body(USER_JSON) - .build())) - .build(); - - private final UserConsumerService tested = new UserConsumerServiceImpl(webClientMock); - - @Test - void when_processUserDataFromObjectArray_then_OK() { - List expected = Arrays.asList("user1", "user2"); - List actual = tested.processUserDataFromObjectArray(); - assertThat(actual, contains(expected.get(0), expected.get(1))); - } - - @Test - void when_processUserDataFromUserArray_then_OK() { - List expected = Arrays.asList("user1", "user2"); - List actual = tested.processUserDataFromUserArray(); - assertThat(actual, contains(expected.get(0), expected.get(1))); - } - - @Test - void when_processUserDataFromUserList_then_OK() { - List expected = Arrays.asList("user1", "user2"); - List actual = tested.processUserDataFromUserList(); - assertThat(actual, contains(expected.get(0), expected.get(1))); - } - - @Test - void when_processNestedUserDataFromUserArray_then_OK() { - List expected = Arrays.asList( - "user1_address1_postCode", - "user1_address2_postCode", - "user2_address1_postCode"); - - List actual = tested.processNestedUserDataFromUserArray(); - assertThat(actual, contains(expected.get(0), expected.get(1), expected.get(2))); - } - - @Test - void when_processNestedUserDataFromUserList_then_OK() { - List expected = Arrays.asList( - "user1_address1_postCode", - "user1_address2_postCode", - "user2_address1_postCode"); - - List actual = tested.processNestedUserDataFromUserList(); - assertThat(actual, contains(expected.get(0), expected.get(1), expected.get(2))); - } -} \ No newline at end of file From a0425afd1b8710216221e0c16ba4a473f1cac373 Mon Sep 17 00:00:00 2001 From: Trixi Turny Date: Sat, 23 Jan 2021 11:25:11 +0000 Subject: [PATCH 07/51] MASH-4748 fix Reader object and url with WebClient --- .../baeldung/webclient/json/model/Reader.java | 30 +++++++++++++++++++ .../ReaderConsumerServiceImplUnitTest.java | 4 +-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Reader.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Reader.java index e69de29bb2..9fc480c3df 100644 --- a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Reader.java +++ b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Reader.java @@ -0,0 +1,30 @@ +package com.baeldung.webclient.json.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class Reader { + private final int id; + private final String name; + private final List favouriteBooks; + + @JsonCreator + public Reader( + @JsonProperty("id") int id, + @JsonProperty("name") String name, + @JsonProperty("favouriteBooks") List favoriteBooks) { + this.id = id; + this.name = name; + this.favouriteBooks = favoriteBooks; + } + + public String getName() { + return name; + } + + public List getFavouriteBooks() { return favouriteBooks; } +} diff --git a/spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/ReaderConsumerServiceImplUnitTest.java b/spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/ReaderConsumerServiceImplUnitTest.java index 92f7bf4f3f..065f1dc11a 100644 --- a/spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/ReaderConsumerServiceImplUnitTest.java +++ b/spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/ReaderConsumerServiceImplUnitTest.java @@ -19,9 +19,9 @@ public class ReaderConsumerServiceImplUnitTest { "{\"id\":2,\"name\":\"reader2\",\"favouriteBooks\":[{\"author\":\"J.R.R. Tolkien\",\"title\":\"Lord of the Rings\"}, " + "{\"author\":\"Douglas Adams\",\"title\":\"The Hitchhiker\'s Guide to the Galaxy\"}]}]"; - private static String BASE_URL = "http://localhost:8080"; + private static String BASE_URL = "http://localhost:8080/readers"; - WebClient webClientMock = WebClient.builder() + WebClient webClientMock = WebClient.builder().baseUrl(BASE_URL) .exchangeFunction(clientRequest -> Mono.just(ClientResponse.create(HttpStatus.OK) .header("content-type", "application/json") .body(READER_JSON) From c3741487d89705dc28eac515330d9e4adb301c1f Mon Sep 17 00:00:00 2001 From: Trixi Turny Date: Sat, 23 Jan 2021 12:56:18 +0000 Subject: [PATCH 08/51] BAEL-4748 update examples with favouriteBook --- .../webclient/json/ReaderConsumerService.java | 8 ++-- .../json/ReaderConsumerServiceImpl.java | 16 ++++---- .../baeldung/webclient/json/model/Reader.java | 15 ++++--- .../ReaderConsumerServiceImplUnitTest.java | 41 ++++++++++++------- 4 files changed, 48 insertions(+), 32 deletions(-) diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/ReaderConsumerService.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/ReaderConsumerService.java index b0bc71d2ed..17676b3f33 100644 --- a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/ReaderConsumerService.java +++ b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/ReaderConsumerService.java @@ -1,14 +1,16 @@ package com.baeldung.webclient.json; +import com.baeldung.webclient.json.model.Book; + import java.util.List; public interface ReaderConsumerService { - List processReaderDataFromObjectArray(); + List processReaderDataFromObjectArray(); - List processReaderDataFromReaderArray(); + List processReaderDataFromReaderArray(); - List processReaderDataFromReaderList(); + List processReaderDataFromReaderList(); List processNestedReaderDataFromReaderArray(); diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/ReaderConsumerServiceImpl.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/ReaderConsumerServiceImpl.java index d1800a7f65..8f1a4c019a 100644 --- a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/ReaderConsumerServiceImpl.java +++ b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/ReaderConsumerServiceImpl.java @@ -21,7 +21,7 @@ public class ReaderConsumerServiceImpl implements ReaderConsumerService { this.webClient = webClient; } @Override - public List processReaderDataFromObjectArray() { + public List processReaderDataFromObjectArray() { Mono response = webClient.get() .accept(MediaType.APPLICATION_JSON) .retrieve() @@ -29,12 +29,12 @@ public class ReaderConsumerServiceImpl implements ReaderConsumerService { Object[] objects = response.block(); return Arrays.stream(objects) .map(object -> mapper.convertValue(object, Reader.class)) - .map(Reader::getName) + .map(Reader::getFavouriteBook) .collect(Collectors.toList()); } @Override - public List processReaderDataFromReaderArray() { + public List processReaderDataFromReaderArray() { Mono response = webClient.get() .accept(MediaType.APPLICATION_JSON) @@ -43,12 +43,12 @@ public class ReaderConsumerServiceImpl implements ReaderConsumerService { Reader[] readers = response.block(); return Arrays.stream(readers) - .map(Reader::getName) + .map(Reader::getFavouriteBook) .collect(Collectors.toList()); } @Override - public List processReaderDataFromReaderList() { + public List processReaderDataFromReaderList() { Mono> response = webClient.get() .accept(MediaType.APPLICATION_JSON) .retrieve() @@ -56,7 +56,7 @@ public class ReaderConsumerServiceImpl implements ReaderConsumerService { List readers = response.block(); return readers.stream() - .map(Reader::getName) + .map(Reader::getFavouriteBook) .collect(Collectors.toList()); } @@ -69,7 +69,7 @@ public class ReaderConsumerServiceImpl implements ReaderConsumerService { Reader[] readers = response.block(); return Arrays.stream(readers) - .flatMap(reader -> reader.getFavouriteBooks().stream()) + .flatMap(reader -> reader.getBooksRead().stream()) .map(Book::getAuthor) .collect(Collectors.toList()); } @@ -83,7 +83,7 @@ public class ReaderConsumerServiceImpl implements ReaderConsumerService { List readers = response.block(); return readers.stream() - .flatMap(reader -> reader.getFavouriteBooks().stream()) + .flatMap(reader -> reader.getBooksRead().stream()) .map(Book::getAuthor) .collect(Collectors.toList()); } diff --git a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Reader.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Reader.java index 9fc480c3df..7d02853ea1 100644 --- a/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Reader.java +++ b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/json/model/Reader.java @@ -10,21 +10,24 @@ import java.util.List; public class Reader { private final int id; private final String name; - private final List favouriteBooks; + private final Book favouriteBook; + private final List booksRead; @JsonCreator public Reader( @JsonProperty("id") int id, @JsonProperty("name") String name, - @JsonProperty("favouriteBooks") List favoriteBooks) { + @JsonProperty("favouriteBook") Book favouriteBook, + @JsonProperty("booksRead") List booksRead) { this.id = id; this.name = name; - this.favouriteBooks = favoriteBooks; + this.favouriteBook = favouriteBook; + this.booksRead =booksRead; } - public String getName() { - return name; + public Book getFavouriteBook() { + return favouriteBook; } - public List getFavouriteBooks() { return favouriteBooks; } + public List getBooksRead() { return booksRead; } } diff --git a/spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/ReaderConsumerServiceImplUnitTest.java b/spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/ReaderConsumerServiceImplUnitTest.java index 065f1dc11a..51f0a5c1bb 100644 --- a/spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/ReaderConsumerServiceImplUnitTest.java +++ b/spring-5-reactive-client/src/test/java/com/baeldung/webclient/json/ReaderConsumerServiceImplUnitTest.java @@ -1,5 +1,6 @@ package com.baeldung.webclient.json; +import com.baeldung.webclient.json.model.Book; import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.web.reactive.function.client.ClientResponse; @@ -10,13 +11,16 @@ import java.util.Arrays; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; +import static org.hamcrest.CoreMatchers.hasItems; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.hasProperty; public class ReaderConsumerServiceImplUnitTest { - private static String READER_JSON = "[{\"id\":1,\"name\":\"reader1\",\"favouriteBooks\":[{\"author\":\"Milan Kundera\",\"title\":\"The Unbearable Lightness of Being\"}," + - "{\"author\":\"Charles Dickens\",\"title\":\"Oliver Twist\"}]}," + - "{\"id\":2,\"name\":\"reader2\",\"favouriteBooks\":[{\"author\":\"J.R.R. Tolkien\",\"title\":\"Lord of the Rings\"}, " + + private static String READER_JSON = "[{\"id\":1,\"name\":\"reader1\",\"favouriteBook\":{\"author\":\"Milan Kundera\",\"title\":\"The Unbearable Lightness of Being\"}," + + "\"booksRead\":[{\"author\":\"Charles Dickens\",\"title\":\"Oliver Twist\"},{\"author\":\"Milan Kundera\",\"title\":\"The Unbearable Lightness of Being\"}]}," + + "{\"id\":2,\"name\":\"reader2\",\"favouriteBook\":{\"author\":\"Douglas Adams\",\"title\":\"The Hitchhiker\'s Guide to the Galaxy\"}," + + "\"booksRead\":[{\"author\":\"J.R.R. Tolkien\",\"title\":\"Lord of the Rings\"}, " + "{\"author\":\"Douglas Adams\",\"title\":\"The Hitchhiker\'s Guide to the Galaxy\"}]}]"; private static String BASE_URL = "http://localhost:8080/readers"; @@ -32,23 +36,30 @@ public class ReaderConsumerServiceImplUnitTest { @Test void when_processReaderDataFromObjectArray_then_OK() { - List expected = Arrays.asList("reader1", "reader2"); - List actual = tested.processReaderDataFromObjectArray(); - assertThat(actual, contains(expected.get(0), expected.get(1))); + String expectedAuthor1 = "Milan Kundera"; + String expectedAuthor2 = "Douglas Adams"; + List actual = tested.processReaderDataFromObjectArray(); + assertThat(actual, hasItems(hasProperty("author", is(expectedAuthor1)), + hasProperty("author", is(expectedAuthor2)))); } @Test void when_processReaderDataFromReaderArray_then_OK() { - List expected = Arrays.asList("reader1", "reader2"); - List actual = tested.processReaderDataFromReaderArray(); - assertThat(actual, contains(expected.get(0), expected.get(1))); + String expectedAuthor1 = "Milan Kundera"; + String expectedAuthor2 = "Douglas Adams"; + List actual = tested.processReaderDataFromReaderArray(); + assertThat(actual, hasItems(hasProperty("author", is(expectedAuthor1)), + hasProperty("author", is(expectedAuthor2)))); } @Test void when_processReaderDataFromReaderList_then_OK() { - List expected = Arrays.asList("reader1", "reader2"); - List actual = tested.processReaderDataFromReaderList(); - assertThat(actual, contains(expected.get(0), expected.get(1))); + String expectedAuthor1 = "Milan Kundera"; + String expectedAuthor2 = "Douglas Adams"; + List actual = tested.processReaderDataFromReaderList(); + assertThat(actual, hasItems(hasProperty("author", is(expectedAuthor1)), + hasProperty("author", is(expectedAuthor2)))); + } @Test @@ -60,7 +71,7 @@ public class ReaderConsumerServiceImplUnitTest { "Douglas Adams"); List actual = tested.processNestedReaderDataFromReaderArray(); - assertThat(actual, contains(expected.get(0), expected.get(1), expected.get(2), expected.get(3))); + assertThat(actual, hasItems(expected.get(0), expected.get(1), expected.get(2), expected.get(3))); } @Test @@ -72,6 +83,6 @@ public class ReaderConsumerServiceImplUnitTest { "Douglas Adams"); List actual = tested.processNestedReaderDataFromReaderList(); - assertThat(actual, contains(expected.get(0), expected.get(1), expected.get(2), expected.get(3))); + assertThat(actual, hasItems(expected.get(0), expected.get(1), expected.get(2), expected.get(3))); } } \ No newline at end of file From 0de9172dc6035454d7b923d5cf40aef327544e83 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Sat, 23 Jan 2021 11:36:58 -0300 Subject: [PATCH 09/51] Moved spring-5-webclient example code to new test class, to verify everything is working as expected --- .../reactive/client/WebClientController.java | 95 --------------- .../web/client/WebClientIntegrationTest.java | 110 ++++++++++++++++++ 2 files changed, 110 insertions(+), 95 deletions(-) create mode 100644 spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java index 2d42e848b2..765cd561d8 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java +++ b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java @@ -1,36 +1,12 @@ package com.baeldung.web.reactive.client; -import java.net.URI; -import java.nio.charset.Charset; -import java.time.ZonedDateTime; -import java.util.Collections; import java.util.HashMap; import java.util.Map; -import java.util.concurrent.TimeUnit; -import org.reactivestreams.Publisher; -import org.reactivestreams.Subscriber; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ReactiveHttpOutputMessage; -import org.springframework.http.client.reactive.ClientHttpRequest; -import org.springframework.http.client.reactive.ReactorClientHttpConnector; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.reactive.function.BodyInserter; -import org.springframework.web.reactive.function.BodyInserters; -import org.springframework.web.reactive.function.client.WebClient; - -import io.netty.channel.ChannelOption; -import io.netty.handler.timeout.ReadTimeoutHandler; -import io.netty.handler.timeout.WriteTimeoutHandler; -import reactor.core.publisher.Mono; -import reactor.netty.http.client.HttpClient; @RestController public class WebClientController { @@ -42,75 +18,4 @@ public class WebClientController { response.put("field", "value"); return response; } - - public void demonstrateWebClient() { - // request - WebClient.UriSpec request1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST); - WebClient.UriSpec request2 = createWebClientWithServerURLAndDefaultValues().post(); - - // request body specifications - WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST) - .uri("/resource"); - WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post() - .uri(URI.create("/resource")); - - // request header specification - WebClient.RequestHeadersSpec requestSpec1 = uri1.body(BodyInserters.fromPublisher(Mono.just("data"), String.class)); - WebClient.RequestHeadersSpec requestSpec2 = uri2.body(BodyInserters.fromValue("data")); - - // inserters - BodyInserter, ReactiveHttpOutputMessage> inserter1 = BodyInserters.fromPublisher(Subscriber::onComplete, String.class); - - LinkedMultiValueMap map = new LinkedMultiValueMap<>(); - map.add("key1", "value1"); - map.add("key2", "value2"); - - BodyInserter, ClientHttpRequest> inserter2 = BodyInserters.fromMultipartData(map); - BodyInserter inserter3 = BodyInserters.fromValue(new Object()); - BodyInserter inserter4 = BodyInserters.fromValue("body"); - - // responses - WebClient.ResponseSpec response1 = uri1.body(inserter3) - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) - .acceptCharset(Charset.forName("UTF-8")) - .ifNoneMatch("*") - .ifModifiedSince(ZonedDateTime.now()) - .retrieve(); - String response2 = uri1.exchangeToMono(response -> response.bodyToMono(String.class)) - .block(); - String response3 = uri2.retrieve() - .bodyToMono(String.class) - .block(); - WebClient.ResponseSpec response4 = requestSpec2.retrieve(); - } - - private WebClient createWebClient() { - return WebClient.create(); - } - - private WebClient createWebClientWithServerURL() { - return WebClient.create("http://localhost:8081"); - } - - private WebClient createWebClientConfiguringTimeout() { - HttpClient httpClient = HttpClient.create() - .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) - .doOnConnected(conn -> conn.addHandlerLast(new ReadTimeoutHandler(5000, TimeUnit.MILLISECONDS)) - .addHandlerLast(new WriteTimeoutHandler(5000, TimeUnit.MILLISECONDS))); - - return WebClient.builder() - .clientConnector(new ReactorClientHttpConnector(httpClient)) - .build(); - } - - private WebClient createWebClientWithServerURLAndDefaultValues() { - return WebClient.builder() - .baseUrl("http://localhost:8081") - .defaultCookie("cookieKey", "cookieValue") - .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080")) - .build(); - } - } diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java new file mode 100644 index 0000000000..df873c618d --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java @@ -0,0 +1,110 @@ +package com.baeldung.web.client; + +import java.net.URI; +import java.nio.charset.Charset; +import java.time.ZonedDateTime; +import java.util.Collections; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.Test; +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ReactiveHttpOutputMessage; +import org.springframework.http.client.reactive.ClientHttpRequest; +import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.reactive.function.BodyInserter; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.WebClient; + +import com.baeldung.web.reactive.client.WebClientApplication; + +import io.netty.channel.ChannelOption; +import io.netty.handler.timeout.ReadTimeoutHandler; +import io.netty.handler.timeout.WriteTimeoutHandler; +import reactor.core.publisher.Mono; +import reactor.netty.http.client.HttpClient; + +@SpringBootTest(classes = WebClientApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class WebClientIntegrationTest { + + @LocalServerPort + private int port; + + @Test + public void demonstrateWebClient() { + // request + WebClient.UriSpec request1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST); + WebClient.UriSpec request2 = createWebClientWithServerURLAndDefaultValues().post(); + + // request body specifications + WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST) + .uri("/resource"); + WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post() + .uri(URI.create("/resource")); + + // request header specification + WebClient.RequestHeadersSpec requestSpec1 = uri1.body(BodyInserters.fromPublisher(Mono.just("data"), String.class)); + WebClient.RequestHeadersSpec requestSpec2 = uri2.body(BodyInserters.fromValue("data")); + + // inserters + BodyInserter, ReactiveHttpOutputMessage> inserter1 = BodyInserters.fromPublisher(Subscriber::onComplete, String.class); + + LinkedMultiValueMap map = new LinkedMultiValueMap<>(); + map.add("key1", "value1"); + map.add("key2", "value2"); + + BodyInserter, ClientHttpRequest> inserter2 = BodyInserters.fromMultipartData(map); + BodyInserter inserter3 = BodyInserters.fromValue(new Object()); + BodyInserter inserter4 = BodyInserters.fromValue("body"); + + // responses + WebClient.ResponseSpec response1 = uri1.body(inserter3) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) + .acceptCharset(Charset.forName("UTF-8")) + .ifNoneMatch("*") + .ifModifiedSince(ZonedDateTime.now()) + .retrieve(); + String response2 = uri1.exchangeToMono(response -> response.bodyToMono(String.class)) + .block(); + String response3 = uri2.retrieve() + .bodyToMono(String.class) + .block(); + WebClient.ResponseSpec response4 = requestSpec2.retrieve(); + } + + private WebClient createWebClient() { + return WebClient.create(); + } + + private WebClient createWebClientWithServerURL() { + return WebClient.create("http://localhost:8081"); + } + + private WebClient createWebClientConfiguringTimeout() { + HttpClient httpClient = HttpClient.create() + .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) + .doOnConnected(conn -> conn.addHandlerLast(new ReadTimeoutHandler(5000, TimeUnit.MILLISECONDS)) + .addHandlerLast(new WriteTimeoutHandler(5000, TimeUnit.MILLISECONDS))); + + return WebClient.builder() + .clientConnector(new ReactorClientHttpConnector(httpClient)) + .build(); + } + + private WebClient createWebClientWithServerURLAndDefaultValues() { + return WebClient.builder() + .baseUrl("http://localhost:8081") + .defaultCookie("cookieKey", "cookieValue") + .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080")) + .build(); + } +} From 3e5a1f3e50c4d18ee4e7a7be34c8aa9821aa31c8 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Sat, 23 Jan 2021 12:40:28 -0300 Subject: [PATCH 10/51] added endpoints to test functionality properly --- .../web/reactive/client/WebClientController.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java index 765cd561d8..2dfcd7533b 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java +++ b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java @@ -4,7 +4,11 @@ import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; @@ -18,4 +22,14 @@ public class WebClientController { response.put("field", "value"); return response; } + + @PostMapping("/resource") + public String postResource(@RequestBody String bodyString) { + return "processed-" + bodyString; + } + + @PostMapping(value = "/resource-multipart", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public String handleFormUpload(@RequestPart("key1") String value1, @RequestPart("key2") String value2) { + return "processed-" + value1 + value2; + } } From 725465b0b6e42202a5f66498773ced8b00ec5355 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Sat, 23 Jan 2021 12:41:13 -0300 Subject: [PATCH 11/51] disabled security for WebClient codebase application --- .../baeldung/web/reactive/client/WebClientApplication.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientApplication.java b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientApplication.java index f104ad30f1..aa9b81de4f 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientApplication.java @@ -2,9 +2,10 @@ package com.baeldung.web.reactive.client; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration; -@SpringBootApplication -public class WebClientApplication{ +@SpringBootApplication(exclude = { ReactiveSecurityAutoConfiguration.class }) +public class WebClientApplication { public static void main(String[] args) { SpringApplication.run(WebClientApplication.class, args); From 268fe2dfe65da6315c59b1e84bcb7d88e357f3cd Mon Sep 17 00:00:00 2001 From: Daniel Strmecki Date: Sun, 24 Jan 2021 12:33:05 +0100 Subject: [PATCH 12/51] BASE-4535: Example for overriding compareTo --- .../com/baeldung/compareto/BankAccount.java | 16 ++++++++ .../baeldung/compareto/BankAccountFix.java | 16 ++++++++ .../baeldung/compareto/FootballPlayer.java | 28 +++++++++++++ .../baeldung/compareto/HandballPlayer.java | 12 ++++++ .../compareto/ArraysSortingUnitTest.java | 25 ++++++++++++ .../compareto/BankAccountFixUnitTest.java | 25 ++++++++++++ .../compareto/BankAccountUnitTest.java | 25 ++++++++++++ .../compareto/FootballPlayerUnitTest.java | 40 +++++++++++++++++++ .../compareto/HandballPlayerUnitTest.java | 26 ++++++++++++ 9 files changed, 213 insertions(+) create mode 100644 core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/BankAccount.java create mode 100644 core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/BankAccountFix.java create mode 100644 core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/FootballPlayer.java create mode 100644 core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/HandballPlayer.java create mode 100644 core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/ArraysSortingUnitTest.java create mode 100644 core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/BankAccountFixUnitTest.java create mode 100644 core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/BankAccountUnitTest.java create mode 100644 core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/FootballPlayerUnitTest.java create mode 100644 core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/HandballPlayerUnitTest.java diff --git a/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/BankAccount.java b/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/BankAccount.java new file mode 100644 index 0000000000..db1f41e6df --- /dev/null +++ b/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/BankAccount.java @@ -0,0 +1,16 @@ +package com.baeldung.compareto; + +public class BankAccount implements Comparable { + + private final int balance; + + public BankAccount(int balance) { + this.balance = balance; + } + + @Override + public int compareTo(BankAccount anotherAccount) { + return this.balance - anotherAccount.balance; + } + +} diff --git a/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/BankAccountFix.java b/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/BankAccountFix.java new file mode 100644 index 0000000000..95e55fdf22 --- /dev/null +++ b/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/BankAccountFix.java @@ -0,0 +1,16 @@ +package com.baeldung.compareto; + +public class BankAccountFix implements Comparable { + + private final int balance; + + public BankAccountFix(int balance) { + this.balance = balance; + } + + @Override + public int compareTo(BankAccountFix anotherAccount) { + return Integer.compare(this.balance, anotherAccount.balance); + } + +} diff --git a/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/FootballPlayer.java b/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/FootballPlayer.java new file mode 100644 index 0000000000..5d065aa298 --- /dev/null +++ b/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/FootballPlayer.java @@ -0,0 +1,28 @@ +package com.baeldung.compareto; + +public class FootballPlayer implements Comparable { + + private final String name; + private final int goalsScored; + + public FootballPlayer(String name, int goalsScored) { + this.name = name; + this.goalsScored = goalsScored; + } + + @Override + public int compareTo(FootballPlayer anotherPlayer) { + return this.goalsScored - anotherPlayer.goalsScored; + } + + @Override + public boolean equals(Object object) { + if (this == object) + return true; + if (object == null || getClass() != object.getClass()) + return false; + FootballPlayer player = (FootballPlayer) object; + return name.equals(player.name); + } + +} diff --git a/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/HandballPlayer.java b/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/HandballPlayer.java new file mode 100644 index 0000000000..022155ccae --- /dev/null +++ b/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/HandballPlayer.java @@ -0,0 +1,12 @@ +package com.baeldung.compareto; + +public class HandballPlayer { + + private final String name; + private final int height; + + public HandballPlayer(String name, int height) { + this.name = name; + this.height = height; + } +} diff --git a/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/ArraysSortingUnitTest.java b/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/ArraysSortingUnitTest.java new file mode 100644 index 0000000000..2082386dba --- /dev/null +++ b/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/ArraysSortingUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.compareto; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ArraysSortingUnitTest { + + @Test + public void givenArrayOfNumbers_whenSortingArray_thenNumbersAreSortedAscending() { + int[] numbers = new int[] {5, 3, 9, 11, 1, 7}; + Arrays.sort(numbers); + assertThat(numbers).containsExactly(1, 3, 5, 7, 9, 11); + } + + @Test + public void givenArrayOfStrings_whenSortingArray_thenStringsAreSortedAlphabetically() { + String[] players = new String[] {"ronaldo", "modric", "ramos", "messi"}; + Arrays.sort(players); + assertThat(players).containsExactly("messi", "modric", "ramos", "ronaldo"); + } + +} diff --git a/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/BankAccountFixUnitTest.java b/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/BankAccountFixUnitTest.java new file mode 100644 index 0000000000..9ca16d1372 --- /dev/null +++ b/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/BankAccountFixUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.compareto; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class BankAccountFixUnitTest { + + @Test + public void givenComparisonBasedImpl_whenUsingSmallIntegers_thenComparisonWorks() { + BankAccountFix accountOne = new BankAccountFix(5000); + BankAccountFix accountTwo = new BankAccountFix(1000); + int comparison = accountOne.compareTo(accountTwo); + assertThat(comparison).isPositive(); + } + + @Test + public void givenComparisonBasedImpl_whenUsingLargeIntegers_thenComparisonWorks() { + BankAccountFix accountOne = new BankAccountFix(1900000000); + BankAccountFix accountTwo = new BankAccountFix(-2000000000); + int comparison = accountOne.compareTo(accountTwo); + assertThat(comparison).isPositive(); + } + +} diff --git a/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/BankAccountUnitTest.java b/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/BankAccountUnitTest.java new file mode 100644 index 0000000000..6ef9372ff9 --- /dev/null +++ b/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/BankAccountUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.compareto; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.*; + +public class BankAccountUnitTest { + + @Test + public void givenSubtractionBasedImpl_whenUsingSmallIntegers_thenComparisonWorks() { + BankAccount accountOne = new BankAccount(5000); + BankAccount accountTwo = new BankAccount(1000); + int comparison = accountOne.compareTo(accountTwo); + assertThat(comparison).isPositive(); + } + + @Test + public void givenSubtractionBasedImpl_whenUsingLargeIntegers_thenComparisonBreaks() { + BankAccount accountOne = new BankAccount(1900000000); + BankAccount accountTwo = new BankAccount(-2000000000); + int comparison = accountOne.compareTo(accountTwo); + assertThat(comparison).isNegative(); + } + +} diff --git a/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/FootballPlayerUnitTest.java b/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/FootballPlayerUnitTest.java new file mode 100644 index 0000000000..11a8a10585 --- /dev/null +++ b/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/FootballPlayerUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.compareto; + +import org.junit.jupiter.api.Test; + +import java.util.Map; +import java.util.TreeMap; +import java.util.TreeSet; + +import static org.assertj.core.api.Assertions.assertThat; + +public class FootballPlayerUnitTest { + + @Test + public void givenInconsistentCompareToAndEqualsImpl_whenUsingSortedSet_thenElementsAreNotAdded() { + FootballPlayer messi = new FootballPlayer("Messi", 800); + FootballPlayer ronaldo = new FootballPlayer("Ronaldo", 800); + + TreeSet set = new TreeSet<>(); + set.add(messi); + set.add(ronaldo); + + assertThat(set).hasSize(1); + assertThat(set).doesNotContain(ronaldo); + } + + @Test + public void givenCompareToImpl_whenSavingElementsInTreeMap_thenKeysAreSortedUsingCompareTo() { + FootballPlayer ronaldo = new FootballPlayer("Ronaldo", 900); + FootballPlayer messi = new FootballPlayer("Messi", 800); + FootballPlayer modric = new FootballPlayer("modric", 100); + + Map players = new TreeMap<>(); + players.put(ronaldo, "forward"); + players.put(messi, "forward"); + players.put(modric, "midfielder"); + + assertThat(players.keySet()).containsExactly(modric, messi, ronaldo); + } + +} diff --git a/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/HandballPlayerUnitTest.java b/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/HandballPlayerUnitTest.java new file mode 100644 index 0000000000..cd017a5c0c --- /dev/null +++ b/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/HandballPlayerUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.compareto; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.TreeSet; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class HandballPlayerUnitTest { + + @Test + public void givenComparableIsNotImplemented_whenSortingArray_thenExceptionIsThrown() { + HandballPlayer duvnjak = new HandballPlayer("Duvnjak", 197); + HandballPlayer hansen = new HandballPlayer("Hansen", 196); + + HandballPlayer[] players = new HandballPlayer[] {duvnjak, hansen}; + + assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> Arrays.sort(players)); + } + +} From 51e2fe20b1132c9e6262d03fedaee1b92f335596 Mon Sep 17 00:00:00 2001 From: Daniel Strmecki Date: Sun, 24 Jan 2021 16:37:24 +0100 Subject: [PATCH 13/51] BASE-4535: Update examples for overriding compareTo --- .../baeldung/compareto/FootballPlayer.java | 6 +++++- .../compareto/FootballPlayerUnitTest.java | 21 +++++++++++++++++-- .../compareto/HandballPlayerUnitTest.java | 6 ------ 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/FootballPlayer.java b/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/FootballPlayer.java index 5d065aa298..173ee32434 100644 --- a/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/FootballPlayer.java +++ b/core-java-modules/core-java-lang-3/src/main/java/com/baeldung/compareto/FootballPlayer.java @@ -10,9 +10,13 @@ public class FootballPlayer implements Comparable { this.goalsScored = goalsScored; } + public String getName() { + return name; + } + @Override public int compareTo(FootballPlayer anotherPlayer) { - return this.goalsScored - anotherPlayer.goalsScored; + return Integer.compare(this.goalsScored, anotherPlayer.goalsScored); } @Override diff --git a/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/FootballPlayerUnitTest.java b/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/FootballPlayerUnitTest.java index 11a8a10585..6abd1e113b 100644 --- a/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/FootballPlayerUnitTest.java +++ b/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/FootballPlayerUnitTest.java @@ -2,6 +2,10 @@ package com.baeldung.compareto; import org.junit.jupiter.api.Test; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; @@ -11,7 +15,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class FootballPlayerUnitTest { @Test - public void givenInconsistentCompareToAndEqualsImpl_whenUsingSortedSet_thenElementsAreNotAdded() { + public void givenInconsistentCompareToAndEqualsImpl_whenUsingSortedSet_thenSomeElementsAreNotAdded() { FootballPlayer messi = new FootballPlayer("Messi", 800); FootballPlayer ronaldo = new FootballPlayer("Ronaldo", 800); @@ -23,11 +27,24 @@ public class FootballPlayerUnitTest { assertThat(set).doesNotContain(ronaldo); } + @Test + public void givenCompareToImpl_whenUsingCustomComparator_thenComparatorLogicIsApplied() { + FootballPlayer ronaldo = new FootballPlayer("Ronaldo", 900); + FootballPlayer messi = new FootballPlayer("Messi", 800); + FootballPlayer modric = new FootballPlayer("Modric", 100); + + List players = Arrays.asList(ronaldo, messi, modric); + Comparator nameComparator = Comparator.comparing(FootballPlayer::getName); + Collections.sort(players, nameComparator); + + assertThat(players).containsExactly(messi, modric, ronaldo); + } + @Test public void givenCompareToImpl_whenSavingElementsInTreeMap_thenKeysAreSortedUsingCompareTo() { FootballPlayer ronaldo = new FootballPlayer("Ronaldo", 900); FootballPlayer messi = new FootballPlayer("Messi", 800); - FootballPlayer modric = new FootballPlayer("modric", 100); + FootballPlayer modric = new FootballPlayer("Modric", 100); Map players = new TreeMap<>(); players.put(ronaldo, "forward"); diff --git a/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/HandballPlayerUnitTest.java b/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/HandballPlayerUnitTest.java index cd017a5c0c..143286f15f 100644 --- a/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/HandballPlayerUnitTest.java +++ b/core-java-modules/core-java-lang-3/src/test/java/com/baeldung/compareto/HandballPlayerUnitTest.java @@ -2,13 +2,7 @@ package com.baeldung.compareto; import org.junit.jupiter.api.Test; -import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.TreeSet; - -import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class HandballPlayerUnitTest { From 2bc7dbc70868ac34ac8d3e7edb8113338fa991d4 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Sun, 24 Jan 2021 15:18:29 -0300 Subject: [PATCH 14/51] added and ordered tests in WebClientIntegrationTest to match article - test not passing (reusing specs) --- .../web/client/WebClientIntegrationTest.java | 82 +++++++++++++------ 1 file changed, 58 insertions(+), 24 deletions(-) diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java index df873c618d..837ea679d2 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java @@ -1,7 +1,7 @@ package com.baeldung.web.client; import java.net.URI; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.time.ZonedDateTime; import java.util.Collections; import java.util.concurrent.TimeUnit; @@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; @@ -22,6 +23,10 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.reactive.function.BodyInserter; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.reactive.function.client.WebClient.RequestBodySpec; +import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec; +import org.springframework.web.reactive.function.client.WebClient.ResponseSpec; +import org.springframework.web.reactive.function.client.WebClient.UriSpec; import com.baeldung.web.reactive.client.WebClientApplication; @@ -31,7 +36,7 @@ import io.netty.handler.timeout.WriteTimeoutHandler; import reactor.core.publisher.Mono; import reactor.netty.http.client.HttpClient; -@SpringBootTest(classes = WebClientApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = WebClientApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class WebClientIntegrationTest { @LocalServerPort @@ -40,44 +45,73 @@ public class WebClientIntegrationTest { @Test public void demonstrateWebClient() { // request - WebClient.UriSpec request1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST); - WebClient.UriSpec request2 = createWebClientWithServerURLAndDefaultValues().post(); + UriSpec requestPost1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST); + UriSpec requestPost2 = createWebClientWithServerURLAndDefaultValues().post(); + UriSpec requestGet = createWebClientWithServerURLAndDefaultValues().get(); // request body specifications - WebClient.RequestBodySpec uri1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST) - .uri("/resource"); - WebClient.RequestBodySpec uri2 = createWebClientWithServerURLAndDefaultValues().post() - .uri(URI.create("/resource")); + RequestBodySpec bodySpecPost = requestPost1.uri("/resource"); + RequestBodySpec bodySpecPostMultipart = requestPost2.uri(uriBuilder -> uriBuilder.pathSegment("resource-multipart") + .build()); + RequestBodySpec bodySpecOverridenBaseUri = requestPost2.uri(URI.create("/resource")); // request header specification - WebClient.RequestHeadersSpec requestSpec1 = uri1.body(BodyInserters.fromPublisher(Mono.just("data"), String.class)); - WebClient.RequestHeadersSpec requestSpec2 = uri2.body(BodyInserters.fromValue("data")); + String bodyValue = "bodyValue"; + RequestHeadersSpec headerSpecPost1 = bodySpecPost.body(BodyInserters.fromPublisher(Mono.just(bodyValue), String.class)); + RequestHeadersSpec headerSpecPost2 = bodySpecPost.body(BodyInserters.fromValue(bodyValue)); + RequestHeadersSpec headerSpecGet = requestGet.uri("/resource"); - // inserters - BodyInserter, ReactiveHttpOutputMessage> inserter1 = BodyInserters.fromPublisher(Subscriber::onComplete, String.class); + // request header specification using inserters + BodyInserter, ReactiveHttpOutputMessage> inserterCompleteSuscriber = BodyInserters.fromPublisher(Subscriber::onComplete, String.class); LinkedMultiValueMap map = new LinkedMultiValueMap<>(); - map.add("key1", "value1"); - map.add("key2", "value2"); + map.add("key1", "multipartValue1"); + map.add("key2", "multipartValue2"); - BodyInserter, ClientHttpRequest> inserter2 = BodyInserters.fromMultipartData(map); - BodyInserter inserter3 = BodyInserters.fromValue(new Object()); - BodyInserter inserter4 = BodyInserters.fromValue("body"); + BodyInserter, ClientHttpRequest> inserterMultipart = BodyInserters.fromMultipartData(map); + BodyInserter inserterObject = BodyInserters.fromValue(new Object()); + BodyInserter inserterString = BodyInserters.fromValue(bodyValue); + + RequestHeadersSpec headerSpecInserterCompleteSuscriber = bodySpecPost.body(inserterCompleteSuscriber); + RequestHeadersSpec headerSpecInserterMultipart = bodySpecPostMultipart.body(inserterMultipart); + RequestHeadersSpec headerSpecInserterObject = bodySpecPost.body(inserterObject); + RequestHeadersSpec headerSpecInserterString = bodySpecPost.body(inserterString); // responses - WebClient.ResponseSpec response1 = uri1.body(inserter3) - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + ResponseSpec responsePostObject = headerSpecInserterObject.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) - .acceptCharset(Charset.forName("UTF-8")) + .acceptCharset(StandardCharsets.UTF_8) .ifNoneMatch("*") .ifModifiedSince(ZonedDateTime.now()) .retrieve(); - String response2 = uri1.exchangeToMono(response -> response.bodyToMono(String.class)) + String responsePostString = headerSpecInserterString.exchangeToMono(response -> response.bodyToMono(String.class)) .block(); - String response3 = uri2.retrieve() + String responsePostMultipart = headerSpecInserterMultipart.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .retrieve() .bodyToMono(String.class) .block(); - WebClient.ResponseSpec response4 = requestSpec2.retrieve(); + String responsePostCompleteSubsciber = headerSpecInserterCompleteSuscriber.retrieve() + .bodyToMono(String.class) + .block(); + String responsePostWithBody1 = headerSpecPost1.retrieve() + .bodyToMono(String.class) + .block(); + String responsePostWithBody3 = headerSpecPost2.retrieve() + .bodyToMono(String.class) + .block(); + String responseGet = headerSpecGet.retrieve() + .bodyToMono(String.class) + .block(); + String responsePostWithNoBody = bodySpecPost.retrieve() + .bodyToMono(String.class) + .block(); + try { + bodySpecOverridenBaseUri.retrieve() + .bodyToMono(String.class) + .block(); + } catch (Exception ex) { + System.out.println(ex.getClass()); + } } private WebClient createWebClient() { @@ -101,7 +135,7 @@ public class WebClientIntegrationTest { private WebClient createWebClientWithServerURLAndDefaultValues() { return WebClient.builder() - .baseUrl("http://localhost:8081") + .baseUrl("http://localhost:" + port) .defaultCookie("cookieKey", "cookieValue") .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080")) From 84737e1056097486bdce4f7b6bc65cfafd930065 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Sun, 24 Jan 2021 17:41:34 -0300 Subject: [PATCH 15/51] added Foo for post Object scenario, removed Subscriber::onComplete scenario, fixed some other errors in examples --- .../com/baeldung/web/reactive/client/Foo.java | 20 +++ .../reactive/client/WebClientController.java | 7 +- .../web/client/WebClientIntegrationTest.java | 141 +++++++++++------- 3 files changed, 116 insertions(+), 52 deletions(-) create mode 100644 spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/Foo.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/Foo.java b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/Foo.java new file mode 100644 index 0000000000..1fc4834cfa --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/Foo.java @@ -0,0 +1,20 @@ +package com.baeldung.web.reactive.client; + +public class Foo { + + private String name; + + public Foo(String name) { + super(); + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java index 2dfcd7533b..4c7941ac35 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java +++ b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java @@ -28,8 +28,13 @@ public class WebClientController { return "processed-" + bodyString; } + @PostMapping("/resource-foo") + public String postResource(@RequestBody Foo bodyFoo) { + return "processedFoo-" + bodyFoo.getName(); + } + @PostMapping(value = "/resource-multipart", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public String handleFormUpload(@RequestPart("key1") String value1, @RequestPart("key2") String value2) { - return "processed-" + value1 + value2; + return "processed-" + value1 + "-" + value2; } } diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java index 837ea679d2..b49aff9575 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java @@ -1,9 +1,13 @@ package com.baeldung.web.client; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.net.URI; import java.nio.charset.StandardCharsets; import java.time.ZonedDateTime; import java.util.Collections; +import java.util.Map; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; @@ -12,6 +16,7 @@ import org.reactivestreams.Subscriber; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; @@ -24,13 +29,17 @@ import org.springframework.web.reactive.function.BodyInserter; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.reactive.function.client.WebClient.RequestBodySpec; +import org.springframework.web.reactive.function.client.WebClient.RequestBodyUriSpec; import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec; import org.springframework.web.reactive.function.client.WebClient.ResponseSpec; import org.springframework.web.reactive.function.client.WebClient.UriSpec; +import org.springframework.web.reactive.function.client.WebClientRequestException; +import com.baeldung.web.reactive.client.Foo; import com.baeldung.web.reactive.client.WebClientApplication; import io.netty.channel.ChannelOption; +import io.netty.channel.ConnectTimeoutException; import io.netty.handler.timeout.ReadTimeoutHandler; import io.netty.handler.timeout.WriteTimeoutHandler; import reactor.core.publisher.Mono; @@ -43,27 +52,37 @@ public class WebClientIntegrationTest { private int port; @Test - public void demonstrateWebClient() { - // request - UriSpec requestPost1 = createWebClientWithServerURLAndDefaultValues().method(HttpMethod.POST); - UriSpec requestPost2 = createWebClientWithServerURLAndDefaultValues().post(); - UriSpec requestGet = createWebClientWithServerURLAndDefaultValues().get(); + public void givenDifferentScenarios_whenRequestsSent_thenObtainExpectedResponses() { + // WebClient + WebClient client1 = WebClient.create(); + WebClient client2 = WebClient.create("http://localhost:" + port); + WebClient client3 = WebClient.builder() + .baseUrl("http://localhost:" + port) + .defaultCookie("cookieKey", "cookieValue") + .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080")) + .build(); + + // request specification + UriSpec uriSpecPost1 = client1.method(HttpMethod.POST); + UriSpec uriSpecPost2 = client2.post(); + UriSpec requestGet = client3.get(); + + // uri specification + RequestBodySpec bodySpecPost = uriSpecPost1.uri("http://localhost:" + port + "/resource"); + RequestBodySpec bodySpecPostMultipart = uriSpecPost2.uri(uriBuilder -> uriBuilder.pathSegment("resource-multipart") + .build()); + RequestBodySpec bodySpecOverridenBaseUri = createDefaultPostRequest().uri(URI.create("/resource")); + RequestBodySpec fooBodySpecPost = createDefaultPostRequest().uri(URI.create("/resource-foo")); // request body specifications - RequestBodySpec bodySpecPost = requestPost1.uri("/resource"); - RequestBodySpec bodySpecPostMultipart = requestPost2.uri(uriBuilder -> uriBuilder.pathSegment("resource-multipart") - .build()); - RequestBodySpec bodySpecOverridenBaseUri = requestPost2.uri(URI.create("/resource")); - - // request header specification String bodyValue = "bodyValue"; RequestHeadersSpec headerSpecPost1 = bodySpecPost.body(BodyInserters.fromPublisher(Mono.just(bodyValue), String.class)); - RequestHeadersSpec headerSpecPost2 = bodySpecPost.body(BodyInserters.fromValue(bodyValue)); + RequestHeadersSpec headerSpecPost2 = createDefaultPostResourceRequest().body(BodyInserters.fromValue(bodyValue)); + RequestHeadersSpec headerSpecFooPost = fooBodySpecPost.body(BodyInserters.fromValue(new Foo("fooName"))); RequestHeadersSpec headerSpecGet = requestGet.uri("/resource"); - // request header specification using inserters - BodyInserter, ReactiveHttpOutputMessage> inserterCompleteSuscriber = BodyInserters.fromPublisher(Subscriber::onComplete, String.class); - + // request body specifications - using inserters LinkedMultiValueMap map = new LinkedMultiValueMap<>(); map.add("key1", "multipartValue1"); map.add("key2", "multipartValue2"); @@ -72,73 +91,93 @@ public class WebClientIntegrationTest { BodyInserter inserterObject = BodyInserters.fromValue(new Object()); BodyInserter inserterString = BodyInserters.fromValue(bodyValue); - RequestHeadersSpec headerSpecInserterCompleteSuscriber = bodySpecPost.body(inserterCompleteSuscriber); RequestHeadersSpec headerSpecInserterMultipart = bodySpecPostMultipart.body(inserterMultipart); - RequestHeadersSpec headerSpecInserterObject = bodySpecPost.body(inserterObject); - RequestHeadersSpec headerSpecInserterString = bodySpecPost.body(inserterString); + RequestHeadersSpec headerSpecInserterObject = createDefaultPostResourceRequest().body(inserterObject); + RequestHeadersSpec headerSpecInserterString = createDefaultPostResourceRequest().body(inserterString); - // responses - ResponseSpec responsePostObject = headerSpecInserterObject.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + // request header specification + RequestHeadersSpec headerSpecInserterStringWithHeaders = headerSpecInserterString.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .acceptCharset(StandardCharsets.UTF_8) .ifNoneMatch("*") - .ifModifiedSince(ZonedDateTime.now()) - .retrieve(); - String responsePostString = headerSpecInserterString.exchangeToMono(response -> response.bodyToMono(String.class)) + .ifModifiedSince(ZonedDateTime.now()); + + // request + ResponseSpec responseSpecPostString = headerSpecInserterStringWithHeaders.retrieve(); + String responsePostString = responseSpecPostString.bodyToMono(String.class) .block(); String responsePostMultipart = headerSpecInserterMultipart.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .retrieve() .bodyToMono(String.class) .block(); - String responsePostCompleteSubsciber = headerSpecInserterCompleteSuscriber.retrieve() - .bodyToMono(String.class) - .block(); String responsePostWithBody1 = headerSpecPost1.retrieve() .bodyToMono(String.class) .block(); String responsePostWithBody3 = headerSpecPost2.retrieve() .bodyToMono(String.class) .block(); - String responseGet = headerSpecGet.retrieve() + String responsePostFoo = headerSpecFooPost.retrieve() .bodyToMono(String.class) .block(); + ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { + }; + Map responseGet = headerSpecGet.retrieve() + .bodyToMono(ref) + .block(); String responsePostWithNoBody = bodySpecPost.retrieve() .bodyToMono(String.class) .block(); - try { + + // response assertions + assertThat(responsePostString).isEqualTo("processed-bodyValue"); + assertThat(responsePostMultipart).isEqualTo("processed-multipartValue1-multipartValue2"); + assertThat(responsePostWithBody1).isEqualTo("processed-"); + assertThat(responsePostWithBody3).isEqualTo("processed-"); + assertThat(responseGet).containsEntry("field", "value"); + assertThat(responsePostWithNoBody).isEqualTo("processed-"); + assertThat(responsePostFoo).isEqualTo("processed-fooName"); + + assertThrows(WebClientRequestException.class, () -> { + String responsePostObject = headerSpecInserterObject.exchangeToMono(response -> response.bodyToMono(String.class)) + .block(); + }); + assertThrows(WebClientRequestException.class, () -> { bodySpecOverridenBaseUri.retrieve() .bodyToMono(String.class) .block(); - } catch (Exception ex) { - System.out.println(ex.getClass()); - } + }); + } - private WebClient createWebClient() { - return WebClient.create(); - } - - private WebClient createWebClientWithServerURL() { - return WebClient.create("http://localhost:8081"); - } - - private WebClient createWebClientConfiguringTimeout() { + @Test + public void givenWebClientWithTimeoutConfigurations_whenRequestUsingWronglyConfiguredPublisher_thenObtainTimeout() { HttpClient httpClient = HttpClient.create() - .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) - .doOnConnected(conn -> conn.addHandlerLast(new ReadTimeoutHandler(5000, TimeUnit.MILLISECONDS)) - .addHandlerLast(new WriteTimeoutHandler(5000, TimeUnit.MILLISECONDS))); + .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000) + .doOnConnected(conn -> conn.addHandlerLast(new ReadTimeoutHandler(1000, TimeUnit.MILLISECONDS)) + .addHandlerLast(new WriteTimeoutHandler(1000, TimeUnit.MILLISECONDS))); - return WebClient.builder() + WebClient timeoutClient = WebClient.builder() .clientConnector(new ReactorClientHttpConnector(httpClient)) .build(); + + BodyInserter, ReactiveHttpOutputMessage> inserterCompleteSuscriber = BodyInserters.fromPublisher(Subscriber::onComplete, String.class); + RequestHeadersSpec headerSpecInserterCompleteSuscriber = timeoutClient.post() + .uri("/resource") + .body(inserterCompleteSuscriber); + WebClientRequestException exception = assertThrows(WebClientRequestException.class, () -> { + headerSpecInserterCompleteSuscriber.retrieve() + .bodyToMono(String.class) + .block(); + }); + assertThat(exception.getCause()).isInstanceOf(ConnectTimeoutException.class); } - private WebClient createWebClientWithServerURLAndDefaultValues() { - return WebClient.builder() - .baseUrl("http://localhost:" + port) - .defaultCookie("cookieKey", "cookieValue") - .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080")) - .build(); + private RequestBodyUriSpec createDefaultPostRequest() { + return WebClient.create("http://localhost:" + port) + .post(); + } + + private RequestBodySpec createDefaultPostResourceRequest() { + return createDefaultPostRequest().uri("/resource"); } } From 431442e3cab7bd575b1f136f362517aecab0d279 Mon Sep 17 00:00:00 2001 From: Anshul BANSAL Date: Mon, 25 Jan 2021 12:29:01 +0200 Subject: [PATCH 16/51] BAEL-4499 - Synchronization bad practice and solution example --- .../AnimalBadPractice.java | 35 +++++++++++++ .../AnimalSolution.java | 42 +++++++++++++++ .../SynchronizationBadPracticeExample.java | 51 +++++++++++++++++++ .../SynchronizationSolutionExample.java | 30 +++++++++++ 4 files changed, 158 insertions(+) create mode 100644 core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/synchronizationbadpractices/AnimalBadPractice.java create mode 100644 core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/synchronizationbadpractices/AnimalSolution.java create mode 100644 core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/synchronizationbadpractices/SynchronizationBadPracticeExample.java create mode 100644 core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/synchronizationbadpractices/SynchronizationSolutionExample.java diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/synchronizationbadpractices/AnimalBadPractice.java b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/synchronizationbadpractices/AnimalBadPractice.java new file mode 100644 index 0000000000..ca6b7db765 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/synchronizationbadpractices/AnimalBadPractice.java @@ -0,0 +1,35 @@ +package com.baeldung.synchronizationbadpractices; + +public class AnimalBadPractice { + + private String name; + private String owner; + + public String getName() { + return name; + } + + public String getOwner() { + return owner; + } + + public synchronized void setName(String name) { + this.name = name; + } + + public void setOwner(String owner) { + synchronized(this) { + this.owner = owner; + } + } + + public AnimalBadPractice() { + + } + + public AnimalBadPractice(String name, String owner) { + this.name = name; + this.owner = owner; + } + +} diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/synchronizationbadpractices/AnimalSolution.java b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/synchronizationbadpractices/AnimalSolution.java new file mode 100644 index 0000000000..b49cfa05d4 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/synchronizationbadpractices/AnimalSolution.java @@ -0,0 +1,42 @@ +package com.baeldung.synchronizationbadpractices; + +public class AnimalSolution { + + private final Object objLock1 = new Object(); + private final Object objLock2 = new Object(); + + private String name; + private String owner; + + public String getName() { + return name; + } + + public String getOwner() { + return owner; + } + + + public void setName(String name) { + synchronized(objLock1) { + this.name = name; + } + } + + public void setOwner(String owner) { + synchronized(objLock2) { + this.owner = owner; + } + } + + public AnimalSolution() { + + } + + public AnimalSolution(String name, String owner) { + this.name = name; + this.owner = owner; + } + + +} \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/synchronizationbadpractices/SynchronizationBadPracticeExample.java b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/synchronizationbadpractices/SynchronizationBadPracticeExample.java new file mode 100644 index 0000000000..84d2e1cbb6 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/synchronizationbadpractices/SynchronizationBadPracticeExample.java @@ -0,0 +1,51 @@ +package com.baeldung.synchronizationbadpractices; + +public class SynchronizationBadPracticeExample { + + public void stringBadPractice1() { + String stringLock = "LOCK_STRING"; + synchronized (stringLock) { + // ... + } + } + + private final String stringLock = "LOCK_STRING"; + public void stringBadPractice2() { + synchronized (stringLock) { + // ... + } + } + + private final String internedStringLock = new String("LOCK_STRING").intern(); + public void stringBadPractice3() { + synchronized (internedStringLock) { + // ... + } + } + + private final Boolean booleanLock = Boolean.FALSE; + public void booleanBadPractice() { + synchronized (booleanLock) { + // ... + } + } + + private int count = 0; + private final Integer intLock = count; + public void boxedPrimitiveBadPractice() { + synchronized (intLock) { + count++; + // ... + } + } + + public void classBadPractice() throws InterruptedException { + AnimalBadPractice animalObj = new AnimalBadPractice("Tommy", "John"); + synchronized(animalObj) { + while (true) { + Thread.sleep(Integer.MAX_VALUE); + } + } + } + +} diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/synchronizationbadpractices/SynchronizationSolutionExample.java b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/synchronizationbadpractices/SynchronizationSolutionExample.java new file mode 100644 index 0000000000..a3ab8a2cee --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/synchronizationbadpractices/SynchronizationSolutionExample.java @@ -0,0 +1,30 @@ +package com.baeldung.synchronizationbadpractices; + +public class SynchronizationSolutionExample { + + private final String stringLock = new String("LOCK_STRING"); + public void stringSolution() { + synchronized (stringLock) { + // ... + } + } + + private int count = 0; + private final Integer intLock = new Integer(count); + public void boxedPrimitiveSolution() { + synchronized(intLock) { + count++; + // ... + } + } + + private static int staticCount = 0; + private static final Object staticObjLock = new Object(); + public void staticVariableSolution() { + synchronized(staticObjLock) { + staticCount++; + // ... + } + } + +} From cfe47f772a434eb3b1c462144c9a2301e3418cf4 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 25 Jan 2021 11:37:12 -0300 Subject: [PATCH 17/51] fixed rest of tests --- .../com/baeldung/web/reactive/client/Foo.java | 4 ++++ .../reactive/client/WebClientController.java | 10 ++++---- .../web/client/WebClientIntegrationTest.java | 24 ++++++++++++------- 3 files changed, 25 insertions(+), 13 deletions(-) diff --git a/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/Foo.java b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/Foo.java index 1fc4834cfa..c6e3678832 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/Foo.java +++ b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/Foo.java @@ -4,6 +4,10 @@ public class Foo { private String name; + public Foo() { + super(); + } + public Foo(String name) { super(); this.name = name; diff --git a/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java index 4c7941ac35..1a91001807 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java +++ b/spring-5-reactive/src/main/java/com/baeldung/web/reactive/client/WebClientController.java @@ -12,6 +12,8 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; +import reactor.core.publisher.Mono; + @RestController public class WebClientController { @@ -24,13 +26,13 @@ public class WebClientController { } @PostMapping("/resource") - public String postResource(@RequestBody String bodyString) { - return "processed-" + bodyString; + public Mono postStringResource(@RequestBody Mono bodyString) { + return bodyString.map(body -> "processed-" + body); } @PostMapping("/resource-foo") - public String postResource(@RequestBody Foo bodyFoo) { - return "processedFoo-" + bodyFoo.getName(); + public Mono postFooResource(@RequestBody Mono bodyFoo) { + return bodyFoo.map(foo -> "processedFoo-" + foo.getName()); } @PostMapping(value = "/resource-multipart", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java index b49aff9575..04a4031c62 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java @@ -17,8 +17,10 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.codec.CodecException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ReactiveHttpOutputMessage; import org.springframework.http.client.reactive.ClientHttpRequest; @@ -72,8 +74,8 @@ public class WebClientIntegrationTest { RequestBodySpec bodySpecPost = uriSpecPost1.uri("http://localhost:" + port + "/resource"); RequestBodySpec bodySpecPostMultipart = uriSpecPost2.uri(uriBuilder -> uriBuilder.pathSegment("resource-multipart") .build()); + RequestBodySpec fooBodySpecPost = createDefaultPostRequest().uri("/resource-foo"); RequestBodySpec bodySpecOverridenBaseUri = createDefaultPostRequest().uri(URI.create("/resource")); - RequestBodySpec fooBodySpecPost = createDefaultPostRequest().uri(URI.create("/resource-foo")); // request body specifications String bodyValue = "bodyValue"; @@ -124,23 +126,27 @@ public class WebClientIntegrationTest { Map responseGet = headerSpecGet.retrieve() .bodyToMono(ref) .block(); - String responsePostWithNoBody = bodySpecPost.retrieve() - .bodyToMono(String.class) + Map responsePostWithNoBody = createDefaultPostResourceRequest().exchangeToMono(responseHandler -> { + assertThat(responseHandler.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + return responseHandler.bodyToMono(ref); + }) .block(); // response assertions assertThat(responsePostString).isEqualTo("processed-bodyValue"); assertThat(responsePostMultipart).isEqualTo("processed-multipartValue1-multipartValue2"); - assertThat(responsePostWithBody1).isEqualTo("processed-"); - assertThat(responsePostWithBody3).isEqualTo("processed-"); + assertThat(responsePostWithBody1).isEqualTo("processed-bodyValue"); + assertThat(responsePostWithBody3).isEqualTo("processed-bodyValue"); assertThat(responseGet).containsEntry("field", "value"); - assertThat(responsePostWithNoBody).isEqualTo("processed-"); - assertThat(responsePostFoo).isEqualTo("processed-fooName"); + assertThat(responsePostFoo).isEqualTo("processedFoo-fooName"); + assertThat(responsePostWithNoBody).containsEntry("error", "Bad Request"); - assertThrows(WebClientRequestException.class, () -> { - String responsePostObject = headerSpecInserterObject.exchangeToMono(response -> response.bodyToMono(String.class)) + // assert sending plain `new Object()` as request body + assertThrows(CodecException.class, () -> { + headerSpecInserterObject.exchangeToMono(response -> response.bodyToMono(String.class)) .block(); }); + // assert sending request overriding base uri assertThrows(WebClientRequestException.class, () -> { bodySpecOverridenBaseUri.retrieve() .bodyToMono(String.class) From 0cda08a95e6326c4e5dfec76c54e2a865974b1d5 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 25 Jan 2021 11:41:57 -0300 Subject: [PATCH 18/51] replaced existing scenario to use an alternative body method --- .../java/com/baeldung/web/client/WebClientIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java index 04a4031c62..34627b00ed 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java @@ -81,7 +81,7 @@ public class WebClientIntegrationTest { String bodyValue = "bodyValue"; RequestHeadersSpec headerSpecPost1 = bodySpecPost.body(BodyInserters.fromPublisher(Mono.just(bodyValue), String.class)); RequestHeadersSpec headerSpecPost2 = createDefaultPostResourceRequest().body(BodyInserters.fromValue(bodyValue)); - RequestHeadersSpec headerSpecFooPost = fooBodySpecPost.body(BodyInserters.fromValue(new Foo("fooName"))); + RequestHeadersSpec headerSpecFooPost = fooBodySpecPost.body(Mono.just(new Foo("fooName")), Foo.class); RequestHeadersSpec headerSpecGet = requestGet.uri("/resource"); // request body specifications - using inserters From a37812ce04cb20c7a1a76deabbe15137c6fb5c26 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 25 Jan 2021 11:44:44 -0300 Subject: [PATCH 19/51] added additional scenario using bodyValue method --- .../com/baeldung/web/client/WebClientIntegrationTest.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java index 34627b00ed..032d62b04d 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java @@ -81,6 +81,7 @@ public class WebClientIntegrationTest { String bodyValue = "bodyValue"; RequestHeadersSpec headerSpecPost1 = bodySpecPost.body(BodyInserters.fromPublisher(Mono.just(bodyValue), String.class)); RequestHeadersSpec headerSpecPost2 = createDefaultPostResourceRequest().body(BodyInserters.fromValue(bodyValue)); + RequestHeadersSpec headerSpecPost3 = createDefaultPostResourceRequest().bodyValue(bodyValue); RequestHeadersSpec headerSpecFooPost = fooBodySpecPost.body(Mono.just(new Foo("fooName")), Foo.class); RequestHeadersSpec headerSpecGet = requestGet.uri("/resource"); @@ -115,6 +116,9 @@ public class WebClientIntegrationTest { String responsePostWithBody1 = headerSpecPost1.retrieve() .bodyToMono(String.class) .block(); + String responsePostWithBody2 = headerSpecPost2.retrieve() + .bodyToMono(String.class) + .block(); String responsePostWithBody3 = headerSpecPost2.retrieve() .bodyToMono(String.class) .block(); @@ -136,6 +140,7 @@ public class WebClientIntegrationTest { assertThat(responsePostString).isEqualTo("processed-bodyValue"); assertThat(responsePostMultipart).isEqualTo("processed-multipartValue1-multipartValue2"); assertThat(responsePostWithBody1).isEqualTo("processed-bodyValue"); + assertThat(responsePostWithBody2).isEqualTo("processed-bodyValue"); assertThat(responsePostWithBody3).isEqualTo("processed-bodyValue"); assertThat(responseGet).containsEntry("field", "value"); assertThat(responsePostFoo).isEqualTo("processedFoo-fooName"); From 615322468ecf4093d2e96c453b6c389dac7e9e5c Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Mon, 25 Jan 2021 12:26:37 -0300 Subject: [PATCH 20/51] made tests assertions non-blocking --- spring-5-reactive/pom.xml | 11 ++- .../web/client/WebClientIntegrationTest.java | 68 ++++++++++--------- 2 files changed, 45 insertions(+), 34 deletions(-) diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index 60c8b90e16..40791faaaf 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -1,6 +1,7 @@ - + 4.0.0 spring-5-reactive 0.0.1-SNAPSHOT @@ -73,6 +74,12 @@ spring-security-test test + + io.projectreactor + reactor-test + test + + diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java index 032d62b04d..01de550a9c 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java @@ -46,6 +46,7 @@ import io.netty.handler.timeout.ReadTimeoutHandler; import io.netty.handler.timeout.WriteTimeoutHandler; import reactor.core.publisher.Mono; import reactor.netty.http.client.HttpClient; +import reactor.test.StepVerifier; @SpringBootTest(classes = WebClientApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class WebClientIntegrationTest { @@ -107,44 +108,46 @@ public class WebClientIntegrationTest { // request ResponseSpec responseSpecPostString = headerSpecInserterStringWithHeaders.retrieve(); - String responsePostString = responseSpecPostString.bodyToMono(String.class) - .block(); - String responsePostMultipart = headerSpecInserterMultipart.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + Mono responsePostString = responseSpecPostString.bodyToMono(String.class); + Mono responsePostMultipart = headerSpecInserterMultipart.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .retrieve() - .bodyToMono(String.class) - .block(); - String responsePostWithBody1 = headerSpecPost1.retrieve() - .bodyToMono(String.class) - .block(); - String responsePostWithBody2 = headerSpecPost2.retrieve() - .bodyToMono(String.class) - .block(); - String responsePostWithBody3 = headerSpecPost2.retrieve() - .bodyToMono(String.class) - .block(); - String responsePostFoo = headerSpecFooPost.retrieve() - .bodyToMono(String.class) - .block(); + .bodyToMono(String.class); + Mono responsePostWithBody1 = headerSpecPost1.retrieve() + .bodyToMono(String.class); + Mono responsePostWithBody2 = headerSpecPost2.retrieve() + .bodyToMono(String.class); + Mono responsePostWithBody3 = headerSpecPost2.retrieve() + .bodyToMono(String.class); + Mono responsePostFoo = headerSpecFooPost.retrieve() + .bodyToMono(String.class); ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { }; - Map responseGet = headerSpecGet.retrieve() - .bodyToMono(ref) - .block(); - Map responsePostWithNoBody = createDefaultPostResourceRequest().exchangeToMono(responseHandler -> { + Mono> responseGet = headerSpecGet.retrieve() + .bodyToMono(ref); + Mono> responsePostWithNoBody = createDefaultPostResourceRequest().exchangeToMono(responseHandler -> { assertThat(responseHandler.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST); return responseHandler.bodyToMono(ref); - }) - .block(); + }); // response assertions - assertThat(responsePostString).isEqualTo("processed-bodyValue"); - assertThat(responsePostMultipart).isEqualTo("processed-multipartValue1-multipartValue2"); - assertThat(responsePostWithBody1).isEqualTo("processed-bodyValue"); - assertThat(responsePostWithBody2).isEqualTo("processed-bodyValue"); - assertThat(responsePostWithBody3).isEqualTo("processed-bodyValue"); - assertThat(responseGet).containsEntry("field", "value"); - assertThat(responsePostFoo).isEqualTo("processedFoo-fooName"); - assertThat(responsePostWithNoBody).containsEntry("error", "Bad Request"); + StepVerifier.create(responsePostString) + .expectNext("processed-bodyValue"); + StepVerifier.create(responsePostMultipart) + .expectNext("processed-multipartValue1-multipartValue2"); + StepVerifier.create(responsePostWithBody1) + .expectNext("processed-bodyValue"); + StepVerifier.create(responsePostWithBody2) + .expectNext("processed-bodyValue"); + StepVerifier.create(responsePostWithBody3) + .expectNext("processed-bodyValue"); + StepVerifier.create(responseGet) + .expectNextMatches(nextMap -> nextMap.get("field") + .equals("value")); + StepVerifier.create(responsePostFoo) + .expectNext("processedFoo-fooName"); + StepVerifier.create(responsePostWithNoBody) + .expectNextMatches(nextMap -> nextMap.get("error") + .equals("Bad Request")); // assert sending plain `new Object()` as request body assertThrows(CodecException.class, () -> { @@ -152,11 +155,12 @@ public class WebClientIntegrationTest { .block(); }); // assert sending request overriding base uri - assertThrows(WebClientRequestException.class, () -> { + Exception exception = assertThrows(WebClientRequestException.class, () -> { bodySpecOverridenBaseUri.retrieve() .bodyToMono(String.class) .block(); }); + assertThat(exception.getMessage()).contains("Connection refused"); } From b018825dc40e2b0a2d0e242bcf88ed4d6253a488 Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Tue, 26 Jan 2021 20:36:04 +0530 Subject: [PATCH 21/51] BAEL-4710 - Hiding endpoints using @Hidden (#10431) * Added code for checking if a class is abstract or not. * Renamed test name as per review comments. * BAEL-4695 - Added code to evaluate math expressions. * BAEL-4695 - Added test case for math function. * BAEL-4695 Added consistent examples and entry in parent pom. * BAEL-4695 - Added more examples * BAEL-4710 - Hiding endpoints using @Hidden --- .../controller/RegularRestController.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/RegularRestController.java diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/RegularRestController.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/RegularRestController.java new file mode 100644 index 0000000000..f3135229d6 --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/RegularRestController.java @@ -0,0 +1,31 @@ +package com.baeldung.springdoc.controller; + +import java.time.LocalDate; +import java.time.LocalTime; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.v3.oas.annotations.Hidden; + +@Hidden +@RestController +public class RegularRestController { + + @Hidden + @GetMapping("/getAuthor") + public String getAuthor() { + return "Umang Budhwar"; + } + + @GetMapping("/getDate") + public LocalDate getDate() { + return LocalDate.now(); + } + + @GetMapping("/getTime") + public LocalTime getTime() { + return LocalTime.now(); + } + +} From 609c4db4fba6764034ea94394ed4ec8c4413a3c5 Mon Sep 17 00:00:00 2001 From: Yavuz Tas <12643010+yavuztas@users.noreply.github.com> Date: Tue, 26 Jan 2021 16:10:30 +0100 Subject: [PATCH 22/51] BAEL-3828 Where Should @Service Annotation Be Kept? (#10430) * BAEL-3828 add code samples and tests for the article * BAEL-3828 fix maven test folder structure and test executions * BAEL-3828 fix indentation in continuation lines --- .../annotations/service/AuthApplication.java | 22 ++++++++ .../AbstractAuthenticationService.java | 12 +++++ .../InMemoryAuthenticationService.java | 14 +++++ .../concretes/LdapAuthenticationService.java | 14 +++++ .../interfaces/AuthenticationService.java | 10 ++++ .../EmployeeApplicationUnitTest.java} | 2 +- .../service/AuthApplicationUnitTest.java | 51 +++++++++++++++++++ .../AbstractsAnnotatedTestConfiguration.java | 10 ++++ ...reteClassesAnnotatedTestConfiguration.java | 10 ++++ .../InterfacesAnnotatedTestConfiguration.java | 10 ++++ 10 files changed, 154 insertions(+), 1 deletion(-) create mode 100644 spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/AuthApplication.java create mode 100644 spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/abstracts/AbstractAuthenticationService.java create mode 100644 spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/concretes/InMemoryAuthenticationService.java create mode 100644 spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/concretes/LdapAuthenticationService.java create mode 100644 spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/interfaces/AuthenticationService.java rename spring-boot-modules/spring-boot-annotations/src/{main/test/com.baeldung.annotations/EmployeeApplicationTest.java => test/java/com.baeldung.annotations/EmployeeApplicationUnitTest.java} (96%) create mode 100644 spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/service/AuthApplicationUnitTest.java create mode 100644 spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/service/config/AbstractsAnnotatedTestConfiguration.java create mode 100644 spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/service/config/ConcreteClassesAnnotatedTestConfiguration.java create mode 100644 spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/service/config/InterfacesAnnotatedTestConfiguration.java diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/AuthApplication.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/AuthApplication.java new file mode 100644 index 0000000000..fa5770b08e --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/AuthApplication.java @@ -0,0 +1,22 @@ +package com.baeldung.annotations.service; + +import com.baeldung.annotations.service.abstracts.AbstractAuthenticationService; +import com.baeldung.annotations.service.interfaces.AuthenticationService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AuthApplication { + + @Autowired + private AuthenticationService inMemoryAuthService; + + @Autowired + private AbstractAuthenticationService ldapAuthService; + + public static void main(String[] args) { + SpringApplication.run(AuthApplication.class, args); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/abstracts/AbstractAuthenticationService.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/abstracts/AbstractAuthenticationService.java new file mode 100644 index 0000000000..47fac229f7 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/abstracts/AbstractAuthenticationService.java @@ -0,0 +1,12 @@ +package com.baeldung.annotations.service.abstracts; + +import org.springframework.stereotype.Service; + +@Service +public abstract class AbstractAuthenticationService { + + public boolean authenticate(String username, String password) { + return false; + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/concretes/InMemoryAuthenticationService.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/concretes/InMemoryAuthenticationService.java new file mode 100644 index 0000000000..8f80cb8593 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/concretes/InMemoryAuthenticationService.java @@ -0,0 +1,14 @@ +package com.baeldung.annotations.service.concretes; + +import com.baeldung.annotations.service.interfaces.AuthenticationService; +import org.springframework.stereotype.Service; + +@Service +public class InMemoryAuthenticationService implements AuthenticationService { + + @Override + public boolean authenticate(String username, String password) { + return false; + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/concretes/LdapAuthenticationService.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/concretes/LdapAuthenticationService.java new file mode 100644 index 0000000000..af93ea13be --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/concretes/LdapAuthenticationService.java @@ -0,0 +1,14 @@ +package com.baeldung.annotations.service.concretes; + +import com.baeldung.annotations.service.abstracts.AbstractAuthenticationService; +import org.springframework.stereotype.Service; + +@Service +public class LdapAuthenticationService extends AbstractAuthenticationService { + + @Override + public boolean authenticate(String username, String password) { + return true; + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/interfaces/AuthenticationService.java b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/interfaces/AuthenticationService.java new file mode 100644 index 0000000000..0537343266 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/main/java/com/baeldung/annotations/service/interfaces/AuthenticationService.java @@ -0,0 +1,10 @@ +package com.baeldung.annotations.service.interfaces; + +import org.springframework.stereotype.Service; + +@Service +public interface AuthenticationService { + + boolean authenticate(String username, String password); + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-annotations/src/main/test/com.baeldung.annotations/EmployeeApplicationTest.java b/spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/EmployeeApplicationUnitTest.java similarity index 96% rename from spring-boot-modules/spring-boot-annotations/src/main/test/com.baeldung.annotations/EmployeeApplicationTest.java rename to spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/EmployeeApplicationUnitTest.java index 66700cf781..8dfc743f3d 100644 --- a/spring-boot-modules/spring-boot-annotations/src/main/test/com.baeldung.annotations/EmployeeApplicationTest.java +++ b/spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/EmployeeApplicationUnitTest.java @@ -6,7 +6,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertAll; -public class EmployeeApplicationTest { +public class EmployeeApplicationUnitTest { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withUserConfiguration(EmployeeApplication.class); diff --git a/spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/service/AuthApplicationUnitTest.java b/spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/service/AuthApplicationUnitTest.java new file mode 100644 index 0000000000..ecbf1b38e5 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/service/AuthApplicationUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.annotations.service; + +import com.baeldung.annotations.service.abstracts.AbstractAuthenticationService; +import com.baeldung.annotations.service.config.AbstractsAnnotatedTestConfiguration; +import com.baeldung.annotations.service.config.ConcreteClassesAnnotatedTestConfiguration; +import com.baeldung.annotations.service.config.InterfacesAnnotatedTestConfiguration; +import com.baeldung.annotations.service.interfaces.AuthenticationService; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +public class AuthApplicationUnitTest { + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner(); + + @Test + void whenOnlyInterfacesAnnotated_noSuchBeanDefinitionExceptionThrown() { + contextRunner + .withUserConfiguration(InterfacesAnnotatedTestConfiguration.class) + .run(context -> { + Assertions.assertThrows(NoSuchBeanDefinitionException.class, () -> { + context.getBean(AuthenticationService.class); + }); + }); + } + + @Test + void whenOnlyAbstractClassesAnnotated_noSuchBeanDefinitionExceptionThrown() { + contextRunner + .withUserConfiguration(AbstractsAnnotatedTestConfiguration.class) + .run(context -> { + Assertions.assertThrows(NoSuchBeanDefinitionException.class, () -> { + context.getBean(AbstractAuthenticationService.class); + }); + }); + } + + @Test + void whenConcreteClassesAnnotated_noExceptionThrown() { + contextRunner + .withUserConfiguration(ConcreteClassesAnnotatedTestConfiguration.class) + .run(context -> { + AuthenticationService inMemoryAuthService = context.getBean(AuthenticationService.class); + AbstractAuthenticationService ldapAuthService = context.getBean(AbstractAuthenticationService.class); + + Assertions.assertNotNull(inMemoryAuthService); + Assertions.assertNotNull(ldapAuthService); + }); + } +} diff --git a/spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/service/config/AbstractsAnnotatedTestConfiguration.java b/spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/service/config/AbstractsAnnotatedTestConfiguration.java new file mode 100644 index 0000000000..4c52401a06 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/service/config/AbstractsAnnotatedTestConfiguration.java @@ -0,0 +1,10 @@ +package com.baeldung.annotations.service.config; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.ComponentScan; + +@TestConfiguration +@ComponentScan("com.baeldung.annotations.service.abstracts") +public class AbstractsAnnotatedTestConfiguration { + +} diff --git a/spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/service/config/ConcreteClassesAnnotatedTestConfiguration.java b/spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/service/config/ConcreteClassesAnnotatedTestConfiguration.java new file mode 100644 index 0000000000..baf7fb970c --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/service/config/ConcreteClassesAnnotatedTestConfiguration.java @@ -0,0 +1,10 @@ +package com.baeldung.annotations.service.config; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.ComponentScan; + +@TestConfiguration +@ComponentScan("com.baeldung.annotations.service.concretes") +public class ConcreteClassesAnnotatedTestConfiguration { + +} diff --git a/spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/service/config/InterfacesAnnotatedTestConfiguration.java b/spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/service/config/InterfacesAnnotatedTestConfiguration.java new file mode 100644 index 0000000000..94659902a1 --- /dev/null +++ b/spring-boot-modules/spring-boot-annotations/src/test/java/com.baeldung.annotations/service/config/InterfacesAnnotatedTestConfiguration.java @@ -0,0 +1,10 @@ +package com.baeldung.annotations.service.config; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.ComponentScan; + +@TestConfiguration +@ComponentScan("com.baeldung.annotations.service.interfaces") +public class InterfacesAnnotatedTestConfiguration { + +} From 384b89d3ea78c39568fadf8e6a051f670952e398 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Tue, 26 Jan 2021 12:57:49 -0300 Subject: [PATCH 23/51] added response timeout to timeout configuration --- .../com/baeldung/web/client/WebClientIntegrationTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java index 01de550a9c..f54d8a6c3d 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java @@ -5,6 +5,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.net.URI; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.time.ZonedDateTime; import java.util.Collections; import java.util.Map; @@ -116,7 +117,7 @@ public class WebClientIntegrationTest { .bodyToMono(String.class); Mono responsePostWithBody2 = headerSpecPost2.retrieve() .bodyToMono(String.class); - Mono responsePostWithBody3 = headerSpecPost2.retrieve() + Mono responsePostWithBody3 = headerSpecPost3.retrieve() .bodyToMono(String.class); Mono responsePostFoo = headerSpecFooPost.retrieve() .bodyToMono(String.class); @@ -168,6 +169,7 @@ public class WebClientIntegrationTest { public void givenWebClientWithTimeoutConfigurations_whenRequestUsingWronglyConfiguredPublisher_thenObtainTimeout() { HttpClient httpClient = HttpClient.create() .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000) + .responseTimeout(Duration.ofMillis(1000)) .doOnConnected(conn -> conn.addHandlerLast(new ReadTimeoutHandler(1000, TimeUnit.MILLISECONDS)) .addHandlerLast(new WriteTimeoutHandler(1000, TimeUnit.MILLISECONDS))); From f8ca77bc71323ac704fb138db497e05b4bd11562 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Tue, 26 Jan 2021 16:05:31 -0300 Subject: [PATCH 24/51] fixed and improved reactive tests not getting verified --- .../web/client/WebClientIntegrationTest.java | 60 ++++++++++--------- 1 file changed, 31 insertions(+), 29 deletions(-) diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java index f54d8a6c3d..cbf11766e1 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java @@ -1,7 +1,6 @@ package com.baeldung.web.client; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; import java.net.URI; import java.nio.charset.StandardCharsets; @@ -42,7 +41,6 @@ import com.baeldung.web.reactive.client.Foo; import com.baeldung.web.reactive.client.WebClientApplication; import io.netty.channel.ChannelOption; -import io.netty.channel.ConnectTimeoutException; import io.netty.handler.timeout.ReadTimeoutHandler; import io.netty.handler.timeout.WriteTimeoutHandler; import reactor.core.publisher.Mono; @@ -129,40 +127,45 @@ public class WebClientIntegrationTest { assertThat(responseHandler.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST); return responseHandler.bodyToMono(ref); }); + Mono responsePostOverridenBaseUri = bodySpecOverridenBaseUri.retrieve() + .bodyToMono(String.class); // response assertions StepVerifier.create(responsePostString) - .expectNext("processed-bodyValue"); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(responsePostMultipart) - .expectNext("processed-multipartValue1-multipartValue2"); + .expectNext("processed-multipartValue1-multipartValue2") + .verifyComplete(); StepVerifier.create(responsePostWithBody1) - .expectNext("processed-bodyValue"); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(responsePostWithBody2) - .expectNext("processed-bodyValue"); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(responsePostWithBody3) - .expectNext("processed-bodyValue"); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(responseGet) .expectNextMatches(nextMap -> nextMap.get("field") - .equals("value")); + .equals("value")) + .verifyComplete(); StepVerifier.create(responsePostFoo) - .expectNext("processedFoo-fooName"); + .expectNext("processedFoo-fooName") + .verifyComplete(); StepVerifier.create(responsePostWithNoBody) .expectNextMatches(nextMap -> nextMap.get("error") - .equals("Bad Request")); - - // assert sending plain `new Object()` as request body - assertThrows(CodecException.class, () -> { - headerSpecInserterObject.exchangeToMono(response -> response.bodyToMono(String.class)) - .block(); - }); + .equals("Bad Request")) + .verifyComplete(); // assert sending request overriding base uri - Exception exception = assertThrows(WebClientRequestException.class, () -> { - bodySpecOverridenBaseUri.retrieve() - .bodyToMono(String.class) - .block(); - }); - assertThat(exception.getMessage()).contains("Connection refused"); - + StepVerifier.create(responsePostOverridenBaseUri) + .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() + .contains("Connection refused")) + .verify(); + // assert error plain `new Object()` as request body + StepVerifier.create(headerSpecInserterObject.exchangeToMono(response -> response.bodyToMono(String.class))) + .expectError(CodecException.class) + .verify(); } @Test @@ -181,12 +184,11 @@ public class WebClientIntegrationTest { RequestHeadersSpec headerSpecInserterCompleteSuscriber = timeoutClient.post() .uri("/resource") .body(inserterCompleteSuscriber); - WebClientRequestException exception = assertThrows(WebClientRequestException.class, () -> { - headerSpecInserterCompleteSuscriber.retrieve() - .bodyToMono(String.class) - .block(); - }); - assertThat(exception.getCause()).isInstanceOf(ConnectTimeoutException.class); + + StepVerifier.create(headerSpecInserterCompleteSuscriber.retrieve() + .bodyToMono(String.class)) + .expectTimeout(Duration.ofMillis(2000)) + .verify(); } private RequestBodyUriSpec createDefaultPostRequest() { From d87cd065aa9ecb87dd080cce8b9b4dc14203a341 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Tue, 26 Jan 2021 16:31:14 -0300 Subject: [PATCH 25/51] cleaned WebClient. definition for spec, for consistency and simplicity --- .../com/baeldung/web/client/WebClientIntegrationTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java index cbf11766e1..c8a306c4bc 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java @@ -66,8 +66,8 @@ public class WebClientIntegrationTest { .build(); // request specification - UriSpec uriSpecPost1 = client1.method(HttpMethod.POST); - UriSpec uriSpecPost2 = client2.post(); + UriSpec uriSpecPost1 = client1.method(HttpMethod.POST); + UriSpec uriSpecPost2 = client2.post(); UriSpec requestGet = client3.get(); // uri specification From 32f35285754fc004ad48e08a645dc2759b0b851a Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Tue, 26 Jan 2021 17:41:44 -0300 Subject: [PATCH 26/51] added more common exchangeToMono example for article --- .../web/client/WebClientIntegrationTest.java | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java index c8a306c4bc..9116ff3e63 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java @@ -115,8 +115,18 @@ public class WebClientIntegrationTest { .bodyToMono(String.class); Mono responsePostWithBody2 = headerSpecPost2.retrieve() .bodyToMono(String.class); - Mono responsePostWithBody3 = headerSpecPost3.retrieve() - .bodyToMono(String.class); + Mono responsePostWithBody3 = headerSpecPost3.exchangeToMono(response -> { + if (response.statusCode() + .equals(HttpStatus.OK)) { + return response.bodyToMono(String.class); + } else if (response.statusCode() + .is4xxClientError()) { + return Mono.just("Error response"); + } else { + return response.createException() + .flatMap(Mono::error); + } + }); Mono responsePostFoo = headerSpecFooPost.retrieve() .bodyToMono(String.class); ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { From 0f668a63b91dadf4a9e5dc479a38f1d8c954a33b Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Tue, 26 Jan 2021 17:53:48 -0300 Subject: [PATCH 27/51] renamed headersSpec to match article --- .../web/client/WebClientIntegrationTest.java | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java index 9116ff3e63..49edf422b0 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java @@ -79,11 +79,11 @@ public class WebClientIntegrationTest { // request body specifications String bodyValue = "bodyValue"; - RequestHeadersSpec headerSpecPost1 = bodySpecPost.body(BodyInserters.fromPublisher(Mono.just(bodyValue), String.class)); - RequestHeadersSpec headerSpecPost2 = createDefaultPostResourceRequest().body(BodyInserters.fromValue(bodyValue)); - RequestHeadersSpec headerSpecPost3 = createDefaultPostResourceRequest().bodyValue(bodyValue); - RequestHeadersSpec headerSpecFooPost = fooBodySpecPost.body(Mono.just(new Foo("fooName")), Foo.class); - RequestHeadersSpec headerSpecGet = requestGet.uri("/resource"); + RequestHeadersSpec headersSpecPost1 = bodySpecPost.body(BodyInserters.fromPublisher(Mono.just(bodyValue), String.class)); + RequestHeadersSpec headersSpecPost2 = createDefaultPostResourceRequest().body(BodyInserters.fromValue(bodyValue)); + RequestHeadersSpec headersSpecPost3 = createDefaultPostResourceRequest().bodyValue(bodyValue); + RequestHeadersSpec headersSpecFooPost = fooBodySpecPost.body(Mono.just(new Foo("fooName")), Foo.class); + RequestHeadersSpec headersSpecGet = requestGet.uri("/resource"); // request body specifications - using inserters LinkedMultiValueMap map = new LinkedMultiValueMap<>(); @@ -94,28 +94,28 @@ public class WebClientIntegrationTest { BodyInserter inserterObject = BodyInserters.fromValue(new Object()); BodyInserter inserterString = BodyInserters.fromValue(bodyValue); - RequestHeadersSpec headerSpecInserterMultipart = bodySpecPostMultipart.body(inserterMultipart); - RequestHeadersSpec headerSpecInserterObject = createDefaultPostResourceRequest().body(inserterObject); - RequestHeadersSpec headerSpecInserterString = createDefaultPostResourceRequest().body(inserterString); + RequestHeadersSpec headersSpecInserterMultipart = bodySpecPostMultipart.body(inserterMultipart); + RequestHeadersSpec headersSpecInserterObject = createDefaultPostResourceRequest().body(inserterObject); + RequestHeadersSpec headersSpecInserterString = createDefaultPostResourceRequest().body(inserterString); // request header specification - RequestHeadersSpec headerSpecInserterStringWithHeaders = headerSpecInserterString.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + RequestHeadersSpec headersSpecInserterStringWithHeaders = headersSpecInserterString.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .acceptCharset(StandardCharsets.UTF_8) .ifNoneMatch("*") .ifModifiedSince(ZonedDateTime.now()); // request - ResponseSpec responseSpecPostString = headerSpecInserterStringWithHeaders.retrieve(); + ResponseSpec responseSpecPostString = headersSpecInserterStringWithHeaders.retrieve(); Mono responsePostString = responseSpecPostString.bodyToMono(String.class); - Mono responsePostMultipart = headerSpecInserterMultipart.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + Mono responsePostMultipart = headersSpecInserterMultipart.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .retrieve() .bodyToMono(String.class); - Mono responsePostWithBody1 = headerSpecPost1.retrieve() + Mono responsePostWithBody1 = headersSpecPost1.retrieve() .bodyToMono(String.class); - Mono responsePostWithBody2 = headerSpecPost2.retrieve() + Mono responsePostWithBody2 = headersSpecPost2.retrieve() .bodyToMono(String.class); - Mono responsePostWithBody3 = headerSpecPost3.exchangeToMono(response -> { + Mono responsePostWithBody3 = headersSpecPost3.exchangeToMono(response -> { if (response.statusCode() .equals(HttpStatus.OK)) { return response.bodyToMono(String.class); @@ -127,11 +127,11 @@ public class WebClientIntegrationTest { .flatMap(Mono::error); } }); - Mono responsePostFoo = headerSpecFooPost.retrieve() + Mono responsePostFoo = headersSpecFooPost.retrieve() .bodyToMono(String.class); ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { }; - Mono> responseGet = headerSpecGet.retrieve() + Mono> responseGet = headersSpecGet.retrieve() .bodyToMono(ref); Mono> responsePostWithNoBody = createDefaultPostResourceRequest().exchangeToMono(responseHandler -> { assertThat(responseHandler.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST); @@ -173,7 +173,7 @@ public class WebClientIntegrationTest { .contains("Connection refused")) .verify(); // assert error plain `new Object()` as request body - StepVerifier.create(headerSpecInserterObject.exchangeToMono(response -> response.bodyToMono(String.class))) + StepVerifier.create(headersSpecInserterObject.exchangeToMono(response -> response.bodyToMono(String.class))) .expectError(CodecException.class) .verify(); } @@ -191,11 +191,11 @@ public class WebClientIntegrationTest { .build(); BodyInserter, ReactiveHttpOutputMessage> inserterCompleteSuscriber = BodyInserters.fromPublisher(Subscriber::onComplete, String.class); - RequestHeadersSpec headerSpecInserterCompleteSuscriber = timeoutClient.post() + RequestHeadersSpec headersSpecInserterCompleteSuscriber = timeoutClient.post() .uri("/resource") .body(inserterCompleteSuscriber); - StepVerifier.create(headerSpecInserterCompleteSuscriber.retrieve() + StepVerifier.create(headersSpecInserterCompleteSuscriber.retrieve() .bodyToMono(String.class)) .expectTimeout(Duration.ofMillis(2000)) .verify(); From c477f22f27fbe4c3900fa5e5ea79223e9dc255b6 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Tue, 26 Jan 2021 18:17:17 -0300 Subject: [PATCH 28/51] modified url override example, to use the client3 (the one defining the baseUrl) --- .../java/com/baeldung/web/client/WebClientIntegrationTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java index 49edf422b0..eddbf74868 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java @@ -75,7 +75,8 @@ public class WebClientIntegrationTest { RequestBodySpec bodySpecPostMultipart = uriSpecPost2.uri(uriBuilder -> uriBuilder.pathSegment("resource-multipart") .build()); RequestBodySpec fooBodySpecPost = createDefaultPostRequest().uri("/resource-foo"); - RequestBodySpec bodySpecOverridenBaseUri = createDefaultPostRequest().uri(URI.create("/resource")); + RequestBodySpec bodySpecOverridenBaseUri = client3.post() + .uri(URI.create("/resource")); // request body specifications String bodyValue = "bodyValue"; From 047dfdef258719a8c91bde81329075f2dc5dc589 Mon Sep 17 00:00:00 2001 From: Gerardo Roza Date: Wed, 27 Jan 2021 12:28:41 -0300 Subject: [PATCH 29/51] split integration test into different test scenarios, one for each step in the webclient process --- .../web/client/WebClientIntegrationTest.java | 266 +++++++++++++----- 1 file changed, 192 insertions(+), 74 deletions(-) diff --git a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java index eddbf74868..39adf0b5c0 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/web/client/WebClientIntegrationTest.java @@ -33,8 +33,8 @@ import org.springframework.web.reactive.function.client.WebClient; import org.springframework.web.reactive.function.client.WebClient.RequestBodySpec; import org.springframework.web.reactive.function.client.WebClient.RequestBodyUriSpec; import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec; +import org.springframework.web.reactive.function.client.WebClient.RequestHeadersUriSpec; import org.springframework.web.reactive.function.client.WebClient.ResponseSpec; -import org.springframework.web.reactive.function.client.WebClient.UriSpec; import org.springframework.web.reactive.function.client.WebClientRequestException; import com.baeldung.web.reactive.client.Foo; @@ -53,9 +53,13 @@ public class WebClientIntegrationTest { @LocalServerPort private int port; + private static final String BODY_VALUE = "bodyValue"; + private static final ParameterizedTypeReference> MAP_RESPONSE_REF = new ParameterizedTypeReference>() { + }; + @Test - public void givenDifferentScenarios_whenRequestsSent_thenObtainExpectedResponses() { - // WebClient + public void givenDifferentWebClientCreationMethods_whenUsed_thenObtainExpectedResponse() { + // WebClient creation WebClient client1 = WebClient.create(); WebClient client2 = WebClient.create("http://localhost:" + port); WebClient client3 = WebClient.builder() @@ -65,58 +69,149 @@ public class WebClientIntegrationTest { .defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080")) .build(); - // request specification - UriSpec uriSpecPost1 = client1.method(HttpMethod.POST); - UriSpec uriSpecPost2 = client2.post(); - UriSpec requestGet = client3.get(); + // response assertions + StepVerifier.create(retrieveResponse(client1.post() + .uri("http://localhost:" + port + "/resource"))) + .expectNext("processed-bodyValue") + .verifyComplete(); + StepVerifier.create(retrieveResponse(client2)) + .expectNext("processed-bodyValue") + .verifyComplete(); + StepVerifier.create(retrieveResponse(client3)) + .expectNext("processed-bodyValue") + .verifyComplete(); + // assert response without specifying URI + StepVerifier.create(retrieveResponse(client1)) + .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() + .contains("Connection refused")) + .verify(); + } + @Test + public void givenDifferentMethodSpecifications_whenUsed_thenObtainExpectedResponse() { + // request specification + RequestBodyUriSpec uriSpecPost1 = createDefaultClient().method(HttpMethod.POST); + RequestBodyUriSpec uriSpecPost2 = createDefaultClient().post(); + RequestHeadersUriSpec requestGet = createDefaultClient().get(); + + // response assertions + StepVerifier.create(retrieveResponse(uriSpecPost1)) + .expectNext("processed-bodyValue") + .verifyComplete(); + StepVerifier.create(retrieveResponse(uriSpecPost2)) + .expectNext("processed-bodyValue") + .verifyComplete(); + StepVerifier.create(retrieveGetResponse(requestGet)) + .expectNextMatches(nextMap -> nextMap.get("field") + .equals("value")) + .verifyComplete(); + } + + @Test + public void givenDifferentUriSpecifications_whenUsed_thenObtainExpectedResponse() { // uri specification - RequestBodySpec bodySpecPost = uriSpecPost1.uri("http://localhost:" + port + "/resource"); - RequestBodySpec bodySpecPostMultipart = uriSpecPost2.uri(uriBuilder -> uriBuilder.pathSegment("resource-multipart") + RequestBodySpec bodySpecUsingString = createDefaultPostRequest().uri("/resource"); + RequestBodySpec bodySpecUsingUriBuilder = createDefaultPostRequest().uri(uriBuilder -> uriBuilder.pathSegment("resource") .build()); - RequestBodySpec fooBodySpecPost = createDefaultPostRequest().uri("/resource-foo"); - RequestBodySpec bodySpecOverridenBaseUri = client3.post() + RequestBodySpec bodySpecusingURI = createDefaultPostRequest().uri(URI.create("http://localhost:" + port + "/resource")); + RequestBodySpec bodySpecOverridenBaseUri = createDefaultPostRequest().uri(URI.create("/resource")); + RequestBodySpec bodySpecOverridenBaseUri2 = WebClient.builder() + .baseUrl("http://localhost:" + port) + .build() + .post() .uri(URI.create("/resource")); - // request body specifications - String bodyValue = "bodyValue"; - RequestHeadersSpec headersSpecPost1 = bodySpecPost.body(BodyInserters.fromPublisher(Mono.just(bodyValue), String.class)); - RequestHeadersSpec headersSpecPost2 = createDefaultPostResourceRequest().body(BodyInserters.fromValue(bodyValue)); - RequestHeadersSpec headersSpecPost3 = createDefaultPostResourceRequest().bodyValue(bodyValue); - RequestHeadersSpec headersSpecFooPost = fooBodySpecPost.body(Mono.just(new Foo("fooName")), Foo.class); - RequestHeadersSpec headersSpecGet = requestGet.uri("/resource"); + // response assertions + StepVerifier.create(retrieveResponse(bodySpecUsingString)) + .expectNext("processed-bodyValue") + .verifyComplete(); + StepVerifier.create(retrieveResponse(bodySpecUsingUriBuilder)) + .expectNext("processed-bodyValue") + .verifyComplete(); + StepVerifier.create(retrieveResponse(bodySpecusingURI)) + .expectNext("processed-bodyValue") + .verifyComplete(); + // assert sending request overriding base URI + StepVerifier.create(retrieveResponse(bodySpecOverridenBaseUri)) + .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() + .contains("Connection refused")) + .verify(); + StepVerifier.create(retrieveResponse(bodySpecOverridenBaseUri2)) + .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() + .contains("Connection refused")) + .verify(); + } - // request body specifications - using inserters + @Test + public void givenDifferentBodySpecifications_whenUsed_thenObtainExpectedResponse() { + // request body specifications + RequestHeadersSpec headersSpecPost1 = createDefaultPostResourceRequest().body(BodyInserters.fromPublisher(Mono.just(BODY_VALUE), String.class)); + RequestHeadersSpec headersSpecPost2 = createDefaultPostResourceRequest().body(BodyInserters.fromValue(BODY_VALUE)); + RequestHeadersSpec headersSpecPost3 = createDefaultPostResourceRequest().bodyValue(BODY_VALUE); + RequestHeadersSpec headersSpecFooPost = createDefaultPostRequest().uri("/resource-foo") + .body(Mono.just(new Foo("fooName")), Foo.class); + BodyInserter inserterPlainObject = BodyInserters.fromValue(new Object()); + RequestHeadersSpec headersSpecPlainObject = createDefaultPostResourceRequest().body(inserterPlainObject); + + // request body specifications - using other inserter method (multipart request) LinkedMultiValueMap map = new LinkedMultiValueMap<>(); map.add("key1", "multipartValue1"); map.add("key2", "multipartValue2"); - BodyInserter, ClientHttpRequest> inserterMultipart = BodyInserters.fromMultipartData(map); - BodyInserter inserterObject = BodyInserters.fromValue(new Object()); - BodyInserter inserterString = BodyInserters.fromValue(bodyValue); + RequestHeadersSpec headersSpecInserterMultipart = createDefaultPostRequest().uri("/resource-multipart") + .body(inserterMultipart); - RequestHeadersSpec headersSpecInserterMultipart = bodySpecPostMultipart.body(inserterMultipart); - RequestHeadersSpec headersSpecInserterObject = createDefaultPostResourceRequest().body(inserterObject); - RequestHeadersSpec headersSpecInserterString = createDefaultPostResourceRequest().body(inserterString); + // response assertions + StepVerifier.create(retrieveResponse(headersSpecPost1)) + .expectNext("processed-bodyValue") + .verifyComplete(); + StepVerifier.create(retrieveResponse(headersSpecPost2)) + .expectNext("processed-bodyValue") + .verifyComplete(); + StepVerifier.create(retrieveResponse(headersSpecPost3)) + .expectNext("processed-bodyValue") + .verifyComplete(); + StepVerifier.create(retrieveResponse(headersSpecFooPost)) + .expectNext("processedFoo-fooName") + .verifyComplete(); + StepVerifier.create(retrieveResponse(headersSpecInserterMultipart)) + .expectNext("processed-multipartValue1-multipartValue2") + .verifyComplete(); + // assert error plain `new Object()` as request body + StepVerifier.create(retrieveResponse(headersSpecPlainObject)) + .expectError(CodecException.class) + .verify(); + // assert response for request with no body + Mono> responsePostWithNoBody = createDefaultPostResourceRequest().exchangeToMono(responseHandler -> { + assertThat(responseHandler.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + return responseHandler.bodyToMono(MAP_RESPONSE_REF); + }); + StepVerifier.create(responsePostWithNoBody) + .expectNextMatches(nextMap -> nextMap.get("error") + .equals("Bad Request")) + .verifyComplete(); + } + @Test + public void givenPostSpecifications_whenHeadersAdded_thenObtainExpectedResponse() { // request header specification - RequestHeadersSpec headersSpecInserterStringWithHeaders = headersSpecInserterString.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + RequestHeadersSpec headersSpecInserterStringWithHeaders = createDefaultPostResourceRequestResponse().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .acceptCharset(StandardCharsets.UTF_8) .ifNoneMatch("*") .ifModifiedSince(ZonedDateTime.now()); - // request - ResponseSpec responseSpecPostString = headersSpecInserterStringWithHeaders.retrieve(); + // response assertions + StepVerifier.create(retrieveResponse(headersSpecInserterStringWithHeaders)) + .expectNext("processed-bodyValue") + .verifyComplete(); + } + + @Test + public void givenDifferentResponseSpecifications_whenUsed_thenObtainExpectedResponse() { + ResponseSpec responseSpecPostString = createDefaultPostResourceRequestResponse().retrieve(); Mono responsePostString = responseSpecPostString.bodyToMono(String.class); - Mono responsePostMultipart = headersSpecInserterMultipart.header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .retrieve() - .bodyToMono(String.class); - Mono responsePostWithBody1 = headersSpecPost1.retrieve() - .bodyToMono(String.class); - Mono responsePostWithBody2 = headersSpecPost2.retrieve() - .bodyToMono(String.class); - Mono responsePostWithBody3 = headersSpecPost3.exchangeToMono(response -> { + Mono responsePostString2 = createDefaultPostResourceRequestResponse().exchangeToMono(response -> { if (response.statusCode() .equals(HttpStatus.OK)) { return response.bodyToMono(String.class); @@ -128,55 +223,37 @@ public class WebClientIntegrationTest { .flatMap(Mono::error); } }); - Mono responsePostFoo = headersSpecFooPost.retrieve() - .bodyToMono(String.class); - ParameterizedTypeReference> ref = new ParameterizedTypeReference>() { - }; - Mono> responseGet = headersSpecGet.retrieve() - .bodyToMono(ref); - Mono> responsePostWithNoBody = createDefaultPostResourceRequest().exchangeToMono(responseHandler -> { - assertThat(responseHandler.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST); - return responseHandler.bodyToMono(ref); + Mono responsePostNoBody = createDefaultPostResourceRequest().exchangeToMono(response -> { + if (response.statusCode() + .equals(HttpStatus.OK)) { + return response.bodyToMono(String.class); + } else if (response.statusCode() + .is4xxClientError()) { + return Mono.just("Error response"); + } else { + return response.createException() + .flatMap(Mono::error); + } }); - Mono responsePostOverridenBaseUri = bodySpecOverridenBaseUri.retrieve() - .bodyToMono(String.class); + Mono> responseGet = createDefaultClient().get() + .uri("/resource") + .retrieve() + .bodyToMono(MAP_RESPONSE_REF); // response assertions StepVerifier.create(responsePostString) .expectNext("processed-bodyValue") .verifyComplete(); - StepVerifier.create(responsePostMultipart) - .expectNext("processed-multipartValue1-multipartValue2") - .verifyComplete(); - StepVerifier.create(responsePostWithBody1) + StepVerifier.create(responsePostString2) .expectNext("processed-bodyValue") .verifyComplete(); - StepVerifier.create(responsePostWithBody2) - .expectNext("processed-bodyValue") - .verifyComplete(); - StepVerifier.create(responsePostWithBody3) - .expectNext("processed-bodyValue") + StepVerifier.create(responsePostNoBody) + .expectNext("Error response") .verifyComplete(); StepVerifier.create(responseGet) .expectNextMatches(nextMap -> nextMap.get("field") .equals("value")) .verifyComplete(); - StepVerifier.create(responsePostFoo) - .expectNext("processedFoo-fooName") - .verifyComplete(); - StepVerifier.create(responsePostWithNoBody) - .expectNextMatches(nextMap -> nextMap.get("error") - .equals("Bad Request")) - .verifyComplete(); - // assert sending request overriding base uri - StepVerifier.create(responsePostOverridenBaseUri) - .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() - .contains("Connection refused")) - .verify(); - // assert error plain `new Object()` as request body - StepVerifier.create(headersSpecInserterObject.exchangeToMono(response -> response.bodyToMono(String.class))) - .expectError(CodecException.class) - .verify(); } @Test @@ -202,12 +279,53 @@ public class WebClientIntegrationTest { .verify(); } + // helper methods to create default instances + private WebClient createDefaultClient() { + return WebClient.create("http://localhost:" + port); + } + private RequestBodyUriSpec createDefaultPostRequest() { - return WebClient.create("http://localhost:" + port) - .post(); + return createDefaultClient().post(); } private RequestBodySpec createDefaultPostResourceRequest() { return createDefaultPostRequest().uri("/resource"); } + + private RequestHeadersSpec createDefaultPostResourceRequestResponse() { + return createDefaultPostResourceRequest().bodyValue(BODY_VALUE); + } + + // helper methods to retrieve a response based on different steps of the process (specs) + private Mono retrieveResponse(WebClient client) { + return client.post() + .uri("/resource") + .bodyValue(BODY_VALUE) + .retrieve() + .bodyToMono(String.class); + } + + private Mono retrieveResponse(RequestBodyUriSpec spec) { + return spec.uri("/resource") + .bodyValue(BODY_VALUE) + .retrieve() + .bodyToMono(String.class); + } + + private Mono> retrieveGetResponse(RequestHeadersUriSpec spec) { + return spec.uri("/resource") + .retrieve() + .bodyToMono(MAP_RESPONSE_REF); + } + + private Mono retrieveResponse(RequestBodySpec spec) { + return spec.bodyValue(BODY_VALUE) + .retrieve() + .bodyToMono(String.class); + } + + private Mono retrieveResponse(RequestHeadersSpec spec) { + return spec.retrieve() + .bodyToMono(String.class); + } } From b6570de6379a1818164aa401ddce8c12f787306c Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 28 Jan 2021 01:11:32 +0800 Subject: [PATCH 30/51] Update README.md --- testing-modules/mockito-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/testing-modules/mockito-2/README.md b/testing-modules/mockito-2/README.md index c7b62182b5..4bd2ff9759 100644 --- a/testing-modules/mockito-2/README.md +++ b/testing-modules/mockito-2/README.md @@ -9,3 +9,4 @@ - [Mockito – Using Spies](https://www.baeldung.com/mockito-spy) - [Using Mockito ArgumentCaptor](https://www.baeldung.com/mockito-argumentcaptor) - [Difference Between when() and doXxx() Methods in Mockito](https://www.baeldung.com/java-mockito-when-vs-do) +- [Overview of Mockito MockSettings](https://www.baeldung.com/mockito-mocksettings) From fe2aab7fb9ccfbd53c54f4e867111f187d357ed4 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 28 Jan 2021 01:21:00 +0800 Subject: [PATCH 31/51] Update README.md --- spring-web-modules/spring-rest-http-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-web-modules/spring-rest-http-2/README.md b/spring-web-modules/spring-rest-http-2/README.md index 97cdc2d068..b5358f888f 100644 --- a/spring-web-modules/spring-rest-http-2/README.md +++ b/spring-web-modules/spring-rest-http-2/README.md @@ -8,3 +8,4 @@ The "REST With Spring 2" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [How to Turn Off Swagger-ui in Production](https://www.baeldung.com/swagger-ui-turn-off-in-production) +- [Setting a Request Timeout for a Spring REST API](https://www.baeldung.com/spring-rest-timeout) From 7634f6a6bd281294188f5056f048477659d3bfd2 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 28 Jan 2021 01:23:32 +0800 Subject: [PATCH 32/51] Update README.md --- performance-tests/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/performance-tests/README.md b/performance-tests/README.md index 27c0363010..09bf6dba1f 100644 --- a/performance-tests/README.md +++ b/performance-tests/README.md @@ -6,6 +6,7 @@ This module contains articles about performance testing. - [Performance of Java Mapping Frameworks](https://www.baeldung.com/java-performance-mapping-frameworks) - [Performance Effects of Exceptions in Java](https://www.baeldung.com/java-exceptions-performance) +- [Is Java a Compiled or Interpreted Language?](https://www.baeldung.com/java-compiled-interpreted) ### Running From a65de428fd776ed6fd10849b172ca2001834fdce Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 28 Jan 2021 01:26:15 +0800 Subject: [PATCH 33/51] Update README.md --- spring-boot-modules/spring-boot-annotations/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-modules/spring-boot-annotations/README.md b/spring-boot-modules/spring-boot-annotations/README.md index 6ead94de86..1b2bca435c 100644 --- a/spring-boot-modules/spring-boot-annotations/README.md +++ b/spring-boot-modules/spring-boot-annotations/README.md @@ -10,3 +10,4 @@ This module contains articles about Spring Boot annotations - [Spring Core Annotations](https://www.baeldung.com/spring-core-annotations) - [Spring Bean Annotations](https://www.baeldung.com/spring-bean-annotations) - [Difference Between @ComponentScan and @EnableAutoConfiguration in Spring Boot](https://www.baeldung.com/spring-componentscan-vs-enableautoconfiguration) +- [Where Should the Spring @Service Annotation Be Kept?](https://www.baeldung.com/spring-service-annotation-placement) From d11f1163abe40a87787fed5c6d0e31ee26357adf Mon Sep 17 00:00:00 2001 From: dvyshd <34768329+dvyshd@users.noreply.github.com> Date: Thu, 28 Jan 2021 23:53:49 +0000 Subject: [PATCH 34/51] BAEL-4719 - Using the Map.Entry Java Class (#10428) * BAEL-4719 Using the Map.Entry Java Class * BAEL-4719 Using the Map.Entry Java Class * BAEL-4719 Change description * BAEL-4719 Feedback from first draft --- .../java/com/baeldung/map/entry/Book.java | 35 +++++++++++++++++++ .../map/entry/MapEntryEfficiencyExample.java | 34 ++++++++++++++++++ .../map/entry/MapEntryTupleExample.java | 25 +++++++++++++ .../baeldung/map/entry/MapEntryUnitTest.java | 33 +++++++++++++++++ 4 files changed, 127 insertions(+) create mode 100644 java-collections-maps-3/src/main/java/com/baeldung/map/entry/Book.java create mode 100644 java-collections-maps-3/src/main/java/com/baeldung/map/entry/MapEntryEfficiencyExample.java create mode 100644 java-collections-maps-3/src/main/java/com/baeldung/map/entry/MapEntryTupleExample.java create mode 100644 java-collections-maps-3/src/test/java/com/baeldung/map/entry/MapEntryUnitTest.java diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/entry/Book.java b/java-collections-maps-3/src/main/java/com/baeldung/map/entry/Book.java new file mode 100644 index 0000000000..7e47e22908 --- /dev/null +++ b/java-collections-maps-3/src/main/java/com/baeldung/map/entry/Book.java @@ -0,0 +1,35 @@ +package com.baeldung.map.entry; + +public class Book { + private String title; + private String author; + + public Book(String title, String author) { + this.title = title; + this.author = author; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + @Override + public String toString() { + return "Book{" + + "title='" + title + '\'' + + ", author='" + author + '\'' + + '}'; + } +} diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/entry/MapEntryEfficiencyExample.java b/java-collections-maps-3/src/main/java/com/baeldung/map/entry/MapEntryEfficiencyExample.java new file mode 100644 index 0000000000..d64bcb38df --- /dev/null +++ b/java-collections-maps-3/src/main/java/com/baeldung/map/entry/MapEntryEfficiencyExample.java @@ -0,0 +1,34 @@ +package com.baeldung.map.entry; + +import java.util.HashMap; +import java.util.Map; + +public class MapEntryEfficiencyExample { + + public static void main(String[] args) { + MapEntryEfficiencyExample mapEntryEfficiencyExample = new MapEntryEfficiencyExample(); + Map map = new HashMap<>(); + + map.put("Robert C. Martin", "Clean Code"); + map.put("Joshua Bloch", "Effective Java"); + + System.out.println("Iterating Using Map.KeySet - 2 operations"); + mapEntryEfficiencyExample.usingKeySet(map); + + System.out.println("Iterating Using Map.Entry - 1 operation"); + mapEntryEfficiencyExample.usingEntrySet(map); + + } + + public void usingKeySet(Map bookMap) { + for (String key : bookMap.keySet()) { + System.out.println("key: " + key + " value: " + bookMap.get(key)); + } + } + + public void usingEntrySet(Map bookMap) { + for (Map.Entry book: bookMap.entrySet()) { + System.out.println("key: " + book.getKey() + " value: " + book.getValue()); + } + } +} diff --git a/java-collections-maps-3/src/main/java/com/baeldung/map/entry/MapEntryTupleExample.java b/java-collections-maps-3/src/main/java/com/baeldung/map/entry/MapEntryTupleExample.java new file mode 100644 index 0000000000..edcbd263fe --- /dev/null +++ b/java-collections-maps-3/src/main/java/com/baeldung/map/entry/MapEntryTupleExample.java @@ -0,0 +1,25 @@ +package com.baeldung.map.entry; + +import java.util.*; + +public class MapEntryTupleExample { + + public static void main(String[] args) { + Map.Entry tuple1; + Map.Entry tuple2; + Map.Entry tuple3; + + tuple1 = new AbstractMap.SimpleEntry<>("9780134685991", new Book("Effective Java 3d Edition", "Joshua Bloch")); + tuple2 = new AbstractMap.SimpleEntry<>("9780132350884", new Book("Clean Code", "Robert C Martin")); + tuple3 = new AbstractMap.SimpleEntry<>("9780132350884", new Book("Clean Code", "Robert C Martin")); + + List> orderedTuples = new ArrayList<>(); + orderedTuples.add(tuple1); + orderedTuples.add(tuple2); + orderedTuples.add(tuple3); + + for (Map.Entry tuple : orderedTuples) { + System.out.println("key: " + tuple.getKey() + " value: " + tuple.getValue()); + } + } +} diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/entry/MapEntryUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/entry/MapEntryUnitTest.java new file mode 100644 index 0000000000..7340558023 --- /dev/null +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/entry/MapEntryUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.map.entry; + +import org.junit.Test; + +import java.util.*; + +import static org.junit.Assert.assertEquals; + +public class MapEntryUnitTest { + + @Test + public void givenSimpleEntryList_whenAddDuplicateKey_thenDoesNotOverwriteExistingKey() { + List> orderedTuples = new ArrayList<>(); + orderedTuples.add(new AbstractMap.SimpleEntry<>("9780134685991", new Book("Effective Java 3d Edition", "Joshua Bloch"))); + orderedTuples.add(new AbstractMap.SimpleEntry<>("9780132350884", new Book("Clean Code", "Robert C Martin"))); + orderedTuples.add(new AbstractMap.SimpleEntry<>("9780132350884", new Book("Clean Code", "Robert C Martin"))); + + assertEquals(3, orderedTuples.size()); + assertEquals("9780134685991", orderedTuples.get(0).getKey()); + assertEquals("9780132350884", orderedTuples.get(1).getKey()); + assertEquals("9780132350884", orderedTuples.get(2).getKey()); + } + + @Test + public void givenRegularMap_whenAddDuplicateKey_thenOverwritesExistingKey() { + Map entries = new HashMap<>(); + entries.put("9780134685991", new Book("Effective Java 3d Edition", "Joshua Bloch")); + entries.put("9780132350884", new Book("Clean Code", "Robert C Martin")); + entries.put("9780132350884", new Book("Clean Code", "Robert C Martin")); + + assertEquals(2, entries.size()); + } +} From 28fe37cac435bc65feef7fac44c7cc1336762658 Mon Sep 17 00:00:00 2001 From: sampada07 <46674082+sampada07@users.noreply.github.com> Date: Sun, 31 Jan 2021 23:09:23 +0530 Subject: [PATCH 35/51] BAEL-3820: Multiple submit button to a Form (#10457) --- .../springmvcforms/controller/EmployeeController.java | 8 +++++++- .../src/main/webapp/WEB-INF/views/employeeHome.jsp | 4 +++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java b/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java index 3ece77bb18..478b3532fe 100644 --- a/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java +++ b/spring-web-modules/spring-mvc-forms-jsp/src/main/java/com/baeldung/springmvcforms/controller/EmployeeController.java @@ -26,7 +26,7 @@ public class EmployeeController { return employeeMap.get(Id); } - @RequestMapping(value = "/addEmployee", method = RequestMethod.POST) + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST, params = "submit") public String submit(@Valid @ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { if (result.hasErrors()) { return "error"; @@ -37,5 +37,11 @@ public class EmployeeController { employeeMap.put(employee.getId(), employee); return "employeeView"; } + + @RequestMapping(value = "/addEmployee", method = RequestMethod.POST, params = "cancel") + public String cancel(@Valid @ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) { + model.addAttribute("message", "You clicked cancel, please re-enter employee details:"); + return "employeeHome"; + } } diff --git a/spring-web-modules/spring-mvc-forms-jsp/src/main/webapp/WEB-INF/views/employeeHome.jsp b/spring-web-modules/spring-mvc-forms-jsp/src/main/webapp/WEB-INF/views/employeeHome.jsp index 5ed572000a..82f2cbae00 100644 --- a/spring-web-modules/spring-mvc-forms-jsp/src/main/webapp/WEB-INF/views/employeeHome.jsp +++ b/spring-web-modules/spring-mvc-forms-jsp/src/main/webapp/WEB-INF/views/employeeHome.jsp @@ -7,6 +7,7 @@

Welcome, Enter The Employee Details

+

${message}

@@ -23,7 +24,8 @@ - + +
From f5bb8ab648a19a0214e88858e00b2bef27943f75 Mon Sep 17 00:00:00 2001 From: "Kent@lhind.hp.g5" Date: Sun, 31 Jan 2021 16:40:50 +0100 Subject: [PATCH 36/51] improvement --- .../check/abstractclass/InterfaceExample.java | 4 +++ .../AbstractExampleUnitTest.java | 26 ++++++++++++++++--- 2 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/check/abstractclass/InterfaceExample.java diff --git a/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/check/abstractclass/InterfaceExample.java b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/check/abstractclass/InterfaceExample.java new file mode 100644 index 0000000000..d226611084 --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/check/abstractclass/InterfaceExample.java @@ -0,0 +1,4 @@ +package com.baeldung.reflection.check.abstractclass; + +public interface InterfaceExample { +} diff --git a/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/check/abstractclass/AbstractExampleUnitTest.java b/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/check/abstractclass/AbstractExampleUnitTest.java index cb5d927c23..d9a955ca6d 100644 --- a/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/check/abstractclass/AbstractExampleUnitTest.java +++ b/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/check/abstractclass/AbstractExampleUnitTest.java @@ -1,16 +1,36 @@ package com.baeldung.reflection.check.abstractclass; -import java.lang.reflect.Modifier; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import java.lang.reflect.Modifier; +import java.util.Date; + class AbstractExampleUnitTest { @Test - void givenAbstractClass_whenCheckModifierIsAbstract_thenTrue() throws Exception { + void givenAbstractClass_whenCheckModifierIsAbstract_thenTrue() { Class clazz = AbstractExample.class; Assertions.assertTrue(Modifier.isAbstract(clazz.getModifiers())); } + @Test + void givenInterface_whenCheckModifierIsAbstract_thenTrue() { + Class clazz = InterfaceExample.class; + Assertions.assertTrue(Modifier.isAbstract(clazz.getModifiers())); + } + + @Test + void givenAbstractClass_whenCheckIsAbstractClass_thenTrue() { + Class clazz = AbstractExample.class; + int mod = clazz.getModifiers(); + Assertions.assertTrue(Modifier.isAbstract(mod) && !Modifier.isInterface(mod)); + } + + @Test + void givenConcreteClass_whenCheckIsAbstractClass_thenFalse() { + Class clazz = Date.class; + int mod = clazz.getModifiers(); + Assertions.assertFalse(Modifier.isAbstract(mod) && !Modifier.isInterface(mod)); + } } From b689760b0752e9e3f6697ec699eee59313a5578d Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Mon, 1 Feb 2021 11:04:42 +0530 Subject: [PATCH 37/51] JAVA-4312: Update deprecations in spring-5-reactive module --- .../main/java/com/baeldung/functional/FormHandler.java | 4 ++-- .../functional/FunctionalSpringBootApplication.java | 4 ++-- .../baeldung/functional/FunctionalWebApplication.java | 4 ++-- .../main/java/com/baeldung/functional/RootServlet.java | 6 +++--- .../errorhandling/GlobalErrorWebExceptionHandler.java | 10 ++++++---- .../reactive/errorhandling/handlers/Handler1.java | 2 +- .../reactive/errorhandling/handlers/Handler2.java | 4 ++-- .../reactive/errorhandling/handlers/Handler3.java | 4 ++-- .../ExploreSpring5URLPatternUsingRouterFunctions.java | 10 +++++----- .../com/baeldung/reactive/urlmatch/FormHandler.java | 4 ++-- .../reactive/urlmatch/FunctionalWebApplication.java | 4 ++-- .../FunctionalWebApplicationIntegrationTest.java | 6 ++---- .../errorhandling/ErrorHandlingIntegrationTest.java | 4 ++-- 13 files changed, 33 insertions(+), 33 deletions(-) diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/FormHandler.java b/spring-5-reactive/src/main/java/com/baeldung/functional/FormHandler.java index c4f8c9f41f..2b415d5f1e 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/functional/FormHandler.java +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/FormHandler.java @@ -11,7 +11,7 @@ import java.util.concurrent.atomic.AtomicLong; import static org.springframework.web.reactive.function.BodyExtractors.toDataBuffers; import static org.springframework.web.reactive.function.BodyExtractors.toFormData; -import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.BodyInserters.fromValue; import static org.springframework.web.reactive.function.server.ServerResponse.ok; public class FormHandler { @@ -29,7 +29,7 @@ public class FormHandler { Mono handleUpload(ServerRequest request) { return request.body(toDataBuffers()) .collectList() - .flatMap(dataBuffers -> ok().body(fromObject(extractData(dataBuffers).toString()))); + .flatMap(dataBuffers -> ok().body(fromValue(extractData(dataBuffers).toString()))); } private AtomicLong extractData(List dataBuffers) { diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java index 9cbc1b7669..9bfd0afe7e 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalSpringBootApplication.java @@ -1,6 +1,6 @@ package com.baeldung.functional; -import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.BodyInserters.fromValue; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RequestPredicates.POST; import static org.springframework.web.reactive.function.server.RequestPredicates.path; @@ -44,7 +44,7 @@ public class FunctionalSpringBootApplication { .doOnNext(actors::add) .then(ok().build())); - return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))) + return route(GET("/test"), serverRequest -> ok().body(fromValue("helloworld"))) .andRoute(POST("/login"), formHandler::handleLogin) .andRoute(POST("/upload"), formHandler::handleUpload) .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java index b89f74ad92..9930ffb474 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/FunctionalWebApplication.java @@ -1,6 +1,6 @@ package com.baeldung.functional; -import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.BodyInserters.fromValue; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RequestPredicates.POST; import static org.springframework.web.reactive.function.server.RequestPredicates.accept; @@ -42,7 +42,7 @@ public class FunctionalWebApplication { .doOnNext(actors::add) .then(ok().build())); - return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin) + return route(GET("/test"), serverRequest -> ok().body(fromValue("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin) .andRoute(POST("/upload"), formHandler::handleUpload) .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) .andNest(accept(MediaType.APPLICATION_JSON), restfulRouter) diff --git a/spring-5-reactive/src/main/java/com/baeldung/functional/RootServlet.java b/spring-5-reactive/src/main/java/com/baeldung/functional/RootServlet.java index 8fe24821de..6c36b7fa03 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/functional/RootServlet.java +++ b/spring-5-reactive/src/main/java/com/baeldung/functional/RootServlet.java @@ -2,7 +2,7 @@ package com.baeldung.functional; import static org.springframework.web.reactive.function.BodyExtractors.toDataBuffers; import static org.springframework.web.reactive.function.BodyExtractors.toFormData; -import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.BodyInserters.fromValue; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RequestPredicates.POST; import static org.springframework.web.reactive.function.server.RequestPredicates.path; @@ -46,7 +46,7 @@ public class RootServlet extends ServletHttpHandlerAdapter { private static RouterFunction routingFunction() { - return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), serverRequest -> serverRequest.body(toFormData()) + return route(GET("/test"), serverRequest -> ok().body(fromValue("helloworld"))).andRoute(POST("/login"), serverRequest -> serverRequest.body(toFormData()) .map(MultiValueMap::toSingleValueMap) .map(formData -> { System.out.println("form data: " + formData.toString()); @@ -65,7 +65,7 @@ public class RootServlet extends ServletHttpHandlerAdapter { dataBuffers.forEach(d -> atomicLong.addAndGet(d.asByteBuffer() .array().length)); System.out.println("data length:" + atomicLong.get()); - return ok().body(fromObject(atomicLong.toString())) + return ok().body(fromValue(atomicLong.toString())) .block(); })) .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/GlobalErrorWebExceptionHandler.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/GlobalErrorWebExceptionHandler.java index 051e4b8df5..4f3f1795da 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/GlobalErrorWebExceptionHandler.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/GlobalErrorWebExceptionHandler.java @@ -2,7 +2,8 @@ package com.baeldung.reactive.errorhandling; import java.util.Map; -import org.springframework.boot.autoconfigure.web.ResourceProperties; + +import org.springframework.boot.autoconfigure.web.WebProperties; import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler; import org.springframework.boot.web.error.ErrorAttributeOptions; import org.springframework.boot.web.reactive.error.ErrorAttributes; @@ -18,6 +19,7 @@ import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; + import reactor.core.publisher.Mono; @Component @@ -26,7 +28,7 @@ public class GlobalErrorWebExceptionHandler extends AbstractErrorWebExceptionHan public GlobalErrorWebExceptionHandler(GlobalErrorAttributes g, ApplicationContext applicationContext, ServerCodecConfigurer serverCodecConfigurer) { - super(g, new ResourceProperties(), applicationContext); + super(g, new WebProperties.Resources(), applicationContext); super.setMessageWriters(serverCodecConfigurer.getWriters()); super.setMessageReaders(serverCodecConfigurer.getReaders()); } @@ -41,8 +43,8 @@ public class GlobalErrorWebExceptionHandler extends AbstractErrorWebExceptionHan final Map errorPropertiesMap = getErrorAttributes(request, ErrorAttributeOptions.defaults()); return ServerResponse.status(HttpStatus.BAD_REQUEST) - .contentType(MediaType.APPLICATION_JSON_UTF8) - .body(BodyInserters.fromObject(errorPropertiesMap)); + .contentType(MediaType.APPLICATION_JSON) + .body(BodyInserters.fromValue(errorPropertiesMap)); } } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler1.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler1.java index 87b78a4654..c71c8ecac0 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler1.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler1.java @@ -14,7 +14,7 @@ public class Handler1 { return sayHello(request).onErrorReturn("Hello, Stranger") .flatMap(s -> ServerResponse.ok() .contentType(MediaType.TEXT_PLAIN) - .syncBody(s)); + .bodyValue(s)); } private Mono sayHello(ServerRequest request) { diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler2.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler2.java index 12172a0f54..92e881543e 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler2.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler2.java @@ -15,11 +15,11 @@ public Mono handleRequest2(ServerRequest request) { sayHello(request) .flatMap(s -> ServerResponse.ok() .contentType(MediaType.TEXT_PLAIN) - .syncBody(s)) + .bodyValue(s)) .onErrorResume(e -> sayHelloFallback() .flatMap(s -> ServerResponse.ok() .contentType(MediaType.TEXT_PLAIN) - .syncBody(s))); + .bodyValue(s))); } private Mono sayHello(ServerRequest request) { diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler3.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler3.java index e95b039cce..8c988a6633 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler3.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/errorhandling/handlers/Handler3.java @@ -15,11 +15,11 @@ public class Handler3 { sayHello(request) .flatMap(s -> ServerResponse.ok() .contentType(MediaType.TEXT_PLAIN) - .syncBody(s)) + .bodyValue(s)) .onErrorResume(e -> (Mono.just("Hi, I looked around for your name but found: " + e.getMessage())).flatMap(s -> ServerResponse.ok() .contentType(MediaType.TEXT_PLAIN) - .syncBody(s))); + .bodyValue(s))); } private Mono sayHello(ServerRequest request) { diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java index 115a057915..34abada2f1 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/ExploreSpring5URLPatternUsingRouterFunctions.java @@ -1,6 +1,6 @@ package com.baeldung.reactive.urlmatch; -import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.BodyInserters.fromValue; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RouterFunctions.route; import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler; @@ -24,10 +24,10 @@ public class ExploreSpring5URLPatternUsingRouterFunctions { private RouterFunction routingFunction() { - return route(GET("/p?ths"), serverRequest -> ok().body(fromObject("/p?ths"))).andRoute(GET("/test/{*id}"), serverRequest -> ok().body(fromObject(serverRequest.pathVariable("id")))) - .andRoute(GET("/*card"), serverRequest -> ok().body(fromObject("/*card path was accessed"))) - .andRoute(GET("/{var1}_{var2}"), serverRequest -> ok().body(fromObject(serverRequest.pathVariable("var1") + " , " + serverRequest.pathVariable("var2")))) - .andRoute(GET("/{baeldung:[a-z]+}"), serverRequest -> ok().body(fromObject("/{baeldung:[a-z]+} was accessed and baeldung=" + serverRequest.pathVariable("baeldung")))) + return route(GET("/p?ths"), serverRequest -> ok().body(fromValue("/p?ths"))).andRoute(GET("/test/{*id}"), serverRequest -> ok().body(fromValue(serverRequest.pathVariable("id")))) + .andRoute(GET("/*card"), serverRequest -> ok().body(fromValue("/*card path was accessed"))) + .andRoute(GET("/{var1}_{var2}"), serverRequest -> ok().body(fromValue(serverRequest.pathVariable("var1") + " , " + serverRequest.pathVariable("var2")))) + .andRoute(GET("/{baeldung:[a-z]+}"), serverRequest -> ok().body(fromValue("/{baeldung:[a-z]+} was accessed and baeldung=" + serverRequest.pathVariable("baeldung")))) .and(RouterFunctions.resources("/files/{*filepaths}", new ClassPathResource("files/"))); } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java index 0781230379..7b1fb06459 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FormHandler.java @@ -11,7 +11,7 @@ import java.util.concurrent.atomic.AtomicLong; import static org.springframework.web.reactive.function.BodyExtractors.toDataBuffers; import static org.springframework.web.reactive.function.BodyExtractors.toFormData; -import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.BodyInserters.fromValue; import static org.springframework.web.reactive.function.server.ServerResponse.ok; public class FormHandler { @@ -29,7 +29,7 @@ public class FormHandler { Mono handleUpload(ServerRequest request) { return request.body(toDataBuffers()) .collectList() - .flatMap(dataBuffers -> ok().body(fromObject(extractData(dataBuffers).toString()))); + .flatMap(dataBuffers -> ok().body(fromValue(extractData(dataBuffers).toString()))); } private AtomicLong extractData(List dataBuffers) { diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FunctionalWebApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FunctionalWebApplication.java index 2ea5420a2b..6cec902a0d 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FunctionalWebApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/urlmatch/FunctionalWebApplication.java @@ -1,6 +1,6 @@ package com.baeldung.reactive.urlmatch; -import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.BodyInserters.fromValue; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RequestPredicates.POST; import static org.springframework.web.reactive.function.server.RequestPredicates.path; @@ -40,7 +40,7 @@ public class FunctionalWebApplication { .doOnNext(actors::add) .then(ok().build())); - return route(GET("/test"), serverRequest -> ok().body(fromObject("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin) + return route(GET("/test"), serverRequest -> ok().body(fromValue("helloworld"))).andRoute(POST("/login"), formHandler::handleLogin) .andRoute(POST("/upload"), formHandler::handleUpload) .and(RouterFunctions.resources("/files/**", new ClassPathResource("files/"))) .andNest(path("/actor"), restfulRouter) diff --git a/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java index 5c0b4f69d0..3164adbe4a 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/functional/FunctionalWebApplicationIntegrationTest.java @@ -1,17 +1,15 @@ package com.baeldung.functional; -import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import static org.springframework.web.reactive.function.BodyInserters.fromValue; import static org.springframework.web.reactive.function.BodyInserters.fromResource; import org.junit.AfterClass; import org.junit.BeforeClass; -import org.junit.Ignore; import org.junit.Test; import org.springframework.boot.web.server.WebServer; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.MediaType; -import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; @@ -115,7 +113,7 @@ public class FunctionalWebApplicationIntegrationTest { client.post() .uri("/actor") - .body(fromObject(new Actor("Clint", "Eastwood"))) + .body(fromValue(new Actor("Clint", "Eastwood"))) .exchange() .expectStatus() .isOk(); diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java index 3bbbed0d77..38443a4eac 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/errorhandling/ErrorHandlingIntegrationTest.java @@ -133,7 +133,7 @@ public class ErrorHandlingIntegrationTest { .expectStatus() .isBadRequest() .expectHeader() - .contentType(MediaType.APPLICATION_JSON_UTF8) + .contentType(MediaType.APPLICATION_JSON) .expectBody() .jsonPath("$.message") .isNotEmpty() @@ -164,7 +164,7 @@ public class ErrorHandlingIntegrationTest { .expectStatus() .isBadRequest() .expectHeader() - .contentType(MediaType.APPLICATION_JSON_UTF8) + .contentType(MediaType.APPLICATION_JSON) .expectBody() .jsonPath("$.message") .isNotEmpty() From e07bcb53153e8d8929c75d4979958fc1823f7fbe Mon Sep 17 00:00:00 2001 From: Jonathan Cook Date: Mon, 1 Feb 2021 17:44:05 +0100 Subject: [PATCH 38/51] BAEL-2674 - Upgrade the Okhttp article (#10462) * BAEL-4706 - Spring Boot with Spring Batch * BAEL-3948 - Fix test(s) in spring-batch which leaves repository.sqlite changed * BAEL-4736 - Convert JSONArray to List of Object using camel-jackson * BAEL-4756 - Mockito MockSettings * BAEL-4756 - Mockito MockSettings - fix spelling * BAEL-2674 - Upgrade the Okhttp article Co-authored-by: Jonathan Cook --- libraries-http/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries-http/pom.xml b/libraries-http/pom.xml index 74e00a7291..257cb988d6 100644 --- a/libraries-http/pom.xml +++ b/libraries-http/pom.xml @@ -120,7 +120,7 @@ 4.5.3 3.6.2 - 3.14.2 + 4.9.1 1.23.0 2.2.0 2.3.0 From 387ee88c2d3b5f746b062065f062751db418060e Mon Sep 17 00:00:00 2001 From: "Kent@lhind.hp.g5" Date: Tue, 2 Feb 2021 10:32:22 +0100 Subject: [PATCH 39/51] upgrade to springboot 2.3.2 and fix application properties --- spring-boot-modules/spring-boot-actuator/pom.xml | 2 +- .../src/main/resources/application.properties | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/spring-boot-modules/spring-boot-actuator/pom.xml b/spring-boot-modules/spring-boot-actuator/pom.xml index 18da6d3a9a..a808b8cb1b 100644 --- a/spring-boot-modules/spring-boot-actuator/pom.xml +++ b/spring-boot-modules/spring-boot-actuator/pom.xml @@ -11,7 +11,7 @@ org.springframework.boot spring-boot-starter-parent - 2.3.0.RELEASE + 2.3.2.RELEASE diff --git a/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties b/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties index 00100d6d97..de7be417a8 100644 --- a/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties @@ -1,4 +1,6 @@ -management.health.probes.enabled=true +management.endpoint.health.probes.enabled=true +management.health.livenessState.enabled=true +management.health.readinessState.enabled=true management.endpoint.health.show-details=always management.endpoint.health.status.http-mapping.down=500 management.endpoint.health.status.http-mapping.out_of_service=503 @@ -8,4 +10,4 @@ management.endpoint.health.status.http-mapping.warning=500 info.app.name=Spring Sample Application info.app.description=This is my first spring boot application G1 info.app.version=1.0.0 -info.java-vendor = ${java.specification.vendor} \ No newline at end of file +info.java-vendor = ${java.specification.vendor} From 7d78e63edfdd759800d1b9e25605db0cd87c0b1a Mon Sep 17 00:00:00 2001 From: osser-sam <46674082+osser-sam@users.noreply.github.com> Date: Wed, 3 Feb 2021 01:12:29 +0530 Subject: [PATCH 40/51] JAVA-4277: Fix tests in spring-resttemplate module (#10447) * JAVA-4277: Fix tests in spring-resttemplate module * JAVA-4277: Moved article from spring-resttemplate to spring-resttemplate-2 --- .../spring-resttemplate-2/README.md | 1 + .../spring-resttemplate-2/pom.xml | 2 +- .../redirect/RedirectController.java | 0 .../src/main/webapp/WEB-INF/api-servlet.xml | 36 +++++++++++++++++++ .../src/main/webapp/WEB-INF/spring-views.xml | 10 ++++++ .../RedirectControllerIntegrationTest.java | 0 .../spring-resttemplate/pom.xml | 4 +-- .../web/service => mock}/EmployeeService.java | 2 +- .../client/TestRestTemplateBasicLiveTest.java | 1 + ...eServiceMockRestServiceServerUnitTest.java | 5 +-- .../EmployeeServiceUnitTest.java | 5 +-- .../RestTemplateBasicLiveTest.java | 1 + 12 files changed, 59 insertions(+), 8 deletions(-) rename spring-web-modules/{spring-resttemplate => spring-resttemplate-2}/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java (100%) create mode 100644 spring-web-modules/spring-resttemplate-2/src/main/webapp/WEB-INF/api-servlet.xml create mode 100644 spring-web-modules/spring-resttemplate-2/src/main/webapp/WEB-INF/spring-views.xml rename spring-web-modules/{spring-resttemplate => spring-resttemplate-2}/src/test/java/com/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java (100%) rename spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/{resttemplate/web/service => mock}/EmployeeService.java (95%) rename spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/{web/service => mock}/EmployeeServiceMockRestServiceServerUnitTest.java (96%) rename spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/{web/service => mock}/EmployeeServiceUnitTest.java (92%) diff --git a/spring-web-modules/spring-resttemplate-2/README.md b/spring-web-modules/spring-resttemplate-2/README.md index a903757bb4..b2000e0481 100644 --- a/spring-web-modules/spring-resttemplate-2/README.md +++ b/spring-web-modules/spring-resttemplate-2/README.md @@ -10,3 +10,4 @@ This module contains articles about Spring RestTemplate - [RestTemplate Post Request with JSON](https://www.baeldung.com/spring-resttemplate-post-json) - [How to Compress Requests Using the Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-compressing-requests) - [Get list of JSON objects with Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-json-list) +- [A Guide To Spring Redirects](https://www.baeldung.com/spring-redirect-and-forward) diff --git a/spring-web-modules/spring-resttemplate-2/pom.xml b/spring-web-modules/spring-resttemplate-2/pom.xml index 04be058638..158380b403 100644 --- a/spring-web-modules/spring-resttemplate-2/pom.xml +++ b/spring-web-modules/spring-resttemplate-2/pom.xml @@ -11,7 +11,7 @@ com.baeldung parent-boot-2 0.0.1-SNAPSHOT - parent-boot-2/pom.xml + ../../parent-boot-2/pom.xml diff --git a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java b/spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java similarity index 100% rename from spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java rename to spring-web-modules/spring-resttemplate-2/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java diff --git a/spring-web-modules/spring-resttemplate-2/src/main/webapp/WEB-INF/api-servlet.xml b/spring-web-modules/spring-resttemplate-2/src/main/webapp/WEB-INF/api-servlet.xml new file mode 100644 index 0000000000..ed37a962e9 --- /dev/null +++ b/spring-web-modules/spring-resttemplate-2/src/main/webapp/WEB-INF/api-servlet.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + /WEB-INF/spring-views.xml + + + + + + + + + + + + + diff --git a/spring-web-modules/spring-resttemplate-2/src/main/webapp/WEB-INF/spring-views.xml b/spring-web-modules/spring-resttemplate-2/src/main/webapp/WEB-INF/spring-views.xml new file mode 100644 index 0000000000..2944828d6d --- /dev/null +++ b/spring-web-modules/spring-resttemplate-2/src/main/webapp/WEB-INF/spring-views.xml @@ -0,0 +1,10 @@ + + + + + + + \ No newline at end of file diff --git a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java b/spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java similarity index 100% rename from spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java rename to spring-web-modules/spring-resttemplate-2/src/test/java/com/baeldung/web/controller/redirect/RedirectControllerIntegrationTest.java diff --git a/spring-web-modules/spring-resttemplate/pom.xml b/spring-web-modules/spring-resttemplate/pom.xml index c0f266fd62..1db6b5db57 100644 --- a/spring-web-modules/spring-resttemplate/pom.xml +++ b/spring-web-modules/spring-resttemplate/pom.xml @@ -188,7 +188,7 @@ cargo-maven2-plugin ${cargo-maven2-plugin.version} - + true tomcat8x embedded @@ -297,7 +297,7 @@ 20.0 - 1.6.0 + 1.6.1 3.0.4 diff --git a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/EmployeeService.java b/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/mock/EmployeeService.java similarity index 95% rename from spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/EmployeeService.java rename to spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/mock/EmployeeService.java index 18dff3db1b..16180a3640 100644 --- a/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/EmployeeService.java +++ b/spring-web-modules/spring-resttemplate/src/main/java/com/baeldung/mock/EmployeeService.java @@ -1,4 +1,4 @@ -package com.baeldung.resttemplate.web.service; +package com.baeldung.mock; import com.baeldung.resttemplate.web.model.Employee; import org.slf4j.Logger; diff --git a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/client/TestRestTemplateBasicLiveTest.java b/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/client/TestRestTemplateBasicLiveTest.java index 9f4b3c9b35..406dd5979b 100644 --- a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/client/TestRestTemplateBasicLiveTest.java +++ b/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/client/TestRestTemplateBasicLiveTest.java @@ -18,6 +18,7 @@ import org.springframework.web.client.RestTemplate; import okhttp3.Request; import okhttp3.RequestBody; +// This test needs RestTemplateConfigurationApplication to be up and running public class TestRestTemplateBasicLiveTest { private RestTemplate restTemplate; diff --git a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java b/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/mock/EmployeeServiceMockRestServiceServerUnitTest.java similarity index 96% rename from spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java rename to spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/mock/EmployeeServiceMockRestServiceServerUnitTest.java index ee01cb6a50..309e0635a4 100644 --- a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceMockRestServiceServerUnitTest.java +++ b/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/mock/EmployeeServiceMockRestServiceServerUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.web.service; +package com.baeldung.mock; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; @@ -7,8 +7,9 @@ import static org.springframework.test.web.client.response.MockRestResponseCreat import java.net.URI; import com.baeldung.SpringTestConfig; +import com.baeldung.mock.EmployeeService; import com.baeldung.resttemplate.web.model.Employee; -import com.baeldung.resttemplate.web.service.EmployeeService; + import org.junit.Assert; import org.junit.Before; import org.junit.Test; diff --git a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceUnitTest.java b/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/mock/EmployeeServiceUnitTest.java similarity index 92% rename from spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceUnitTest.java rename to spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/mock/EmployeeServiceUnitTest.java index 6eb040414b..9a992f390a 100644 --- a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/web/service/EmployeeServiceUnitTest.java +++ b/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/mock/EmployeeServiceUnitTest.java @@ -1,7 +1,8 @@ -package com.baeldung.web.service; +package com.baeldung.mock; +import com.baeldung.mock.EmployeeService; import com.baeldung.resttemplate.web.model.Employee; -import com.baeldung.resttemplate.web.service.EmployeeService; + import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateBasicLiveTest.java b/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateBasicLiveTest.java index 0dab124316..8d52394dd1 100644 --- a/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateBasicLiveTest.java +++ b/spring-web-modules/spring-resttemplate/src/test/java/com/baeldung/resttemplate/RestTemplateBasicLiveTest.java @@ -38,6 +38,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.google.common.base.Charsets; +// This test needs RestTemplateConfigurationApplication to be up and running public class RestTemplateBasicLiveTest { private RestTemplate restTemplate; From cfbdbe1001aa330905eb15c0c60c0b27d80fcc54 Mon Sep 17 00:00:00 2001 From: osser-sam <46674082+osser-sam@users.noreply.github.com> Date: Wed, 3 Feb 2021 01:16:00 +0530 Subject: [PATCH 41/51] JAVA-4012: fix failing test (#10455) --- .../zoneddatetime/config/MongoConfig.java | 22 ------------------- .../src/main/resources/mongoConfig.xml | 4 ++-- 2 files changed, 2 insertions(+), 24 deletions(-) diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/zoneddatetime/config/MongoConfig.java b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/zoneddatetime/config/MongoConfig.java index 3cfefa099c..4eb3872e34 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/zoneddatetime/config/MongoConfig.java +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/zoneddatetime/config/MongoConfig.java @@ -1,11 +1,8 @@ package com.baeldung.zoneddatetime.config; import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; import java.util.List; -import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.converter.Converter; import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration; import org.springframework.data.mongodb.core.convert.MongoCustomConversions; @@ -13,12 +10,7 @@ import org.springframework.data.mongodb.repository.config.EnableMongoRepositorie import com.baeldung.zoneddatetime.converter.ZonedDateTimeReadConverter; import com.baeldung.zoneddatetime.converter.ZonedDateTimeWriteConverter; -import com.mongodb.ConnectionString; -import com.mongodb.MongoClientSettings; -import com.mongodb.client.MongoClient; -import com.mongodb.client.MongoClients; -@Configuration @EnableMongoRepositories(basePackages = { "com.baeldung" }) public class MongoConfig extends AbstractMongoClientConfiguration { @@ -29,20 +21,6 @@ public class MongoConfig extends AbstractMongoClientConfiguration { return "test"; } - @Override - public MongoClient mongoClient() { - final ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test"); - final MongoClientSettings mongoClientSettings = MongoClientSettings.builder() - .applyConnectionString(connectionString) - .build(); - return MongoClients.create(mongoClientSettings); - } - - @Override - public Collection getMappingBasePackages() { - return Collections.singleton("com.baeldung"); - } - @Override public MongoCustomConversions customConversions() { converters.add(new ZonedDateTimeReadConverter()); diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/mongoConfig.xml b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/mongoConfig.xml index c5b9068de3..7a10ef6a69 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/mongoConfig.xml +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/mongoConfig.xml @@ -24,8 +24,8 @@ - - + + \ No newline at end of file From 6f2e23e1665ce746d66ca779ba74e3f70b37193f Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 3 Feb 2021 23:59:04 +0800 Subject: [PATCH 42/51] Update README.md --- core-java-modules/core-java-jvm-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-jvm-2/README.md b/core-java-modules/core-java-jvm-2/README.md index 36cafd3288..ccca3a11ac 100644 --- a/core-java-modules/core-java-jvm-2/README.md +++ b/core-java-modules/core-java-jvm-2/README.md @@ -11,4 +11,5 @@ This module contains articles about working with the Java Virtual Machine (JVM). - [Where Is the Array Length Stored in JVM?](https://www.baeldung.com/java-jvm-array-length) - [Memory Address of Objects in Java](https://www.baeldung.com/java-object-memory-address) - [List All Classes Loaded in a Specific Class Loader](https://www.baeldung.com/java-list-classes-class-loader) +- [An Introduction to the Constant Pool in the JVM](https://www.baeldung.com/jvm-constant-pool) - More articles: [[<-- prev]](/core-java-modules/core-java-jvm) From 5774d53d0b5f45937ed26166ce0856dc791bb5b7 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 4 Feb 2021 00:02:05 +0800 Subject: [PATCH 43/51] Update README.md --- java-collections-maps-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/java-collections-maps-3/README.md b/java-collections-maps-3/README.md index 39ac8575fa..bd1029c9cf 100644 --- a/java-collections-maps-3/README.md +++ b/java-collections-maps-3/README.md @@ -2,3 +2,4 @@ - [Java Map With Case-Insensitive Keys](https://www.baeldung.com/java-map-with-case-insensitive-keys) - [Using a Byte Array as Map Key in Java](https://www.baeldung.com/java-map-key-byte-array) +- [Using the Map.Entry Java Class](https://www.baeldung.com/java-map-entry) From 3ff1ba2185ac0571764d0e148ebc933cb4ba1652 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 4 Feb 2021 00:03:53 +0800 Subject: [PATCH 44/51] Update README.md --- core-java-modules/core-java-lang-oop-generics/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-lang-oop-generics/README.md b/core-java-modules/core-java-lang-oop-generics/README.md index 74b9df7c65..9c9080ece3 100644 --- a/core-java-modules/core-java-lang-oop-generics/README.md +++ b/core-java-modules/core-java-lang-oop-generics/README.md @@ -7,3 +7,4 @@ This module contains articles about generics in Java - [Type Erasure in Java Explained](https://www.baeldung.com/java-type-erasure) - [Raw Types in Java](https://www.baeldung.com/raw-types-java) - [Super Type Tokens in Java Generics](https://www.baeldung.com/java-super-type-tokens) +- [Java Warning “unchecked conversion”](https://www.baeldung.com/java-unchecked-conversion) From 2a365df31834bb042f9039cb3fb082a478e5a7f9 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 4 Feb 2021 00:07:17 +0800 Subject: [PATCH 45/51] Update README.md --- spring-aop/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-aop/README.md b/spring-aop/README.md index 91cccbd114..c92e132d1e 100644 --- a/spring-aop/README.md +++ b/spring-aop/README.md @@ -11,3 +11,4 @@ This module contains articles about Spring aspect oriented programming (AOP) - [Introduction to Pointcut Expressions in Spring](https://www.baeldung.com/spring-aop-pointcut-tutorial) - [Introduction to Advice Types in Spring](https://www.baeldung.com/spring-aop-advice-tutorial) - [When Does Java Throw UndeclaredThrowableException?](https://www.baeldung.com/java-undeclaredthrowableexception) +- [Get Advised Method Info in Spring AOP](https://www.baeldung.com/spring-aop-get-advised-method-info) From 1bc84889aa660fce20c3ad2f6835e193eb4727e0 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 4 Feb 2021 00:09:00 +0800 Subject: [PATCH 46/51] Update README.md --- core-java-modules/core-java-concurrency-advanced-4/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-concurrency-advanced-4/README.md b/core-java-modules/core-java-concurrency-advanced-4/README.md index 98f2894515..5b93cec0dd 100644 --- a/core-java-modules/core-java-concurrency-advanced-4/README.md +++ b/core-java-modules/core-java-concurrency-advanced-4/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Binary Semaphore vs Reentrant Lock](https://www.baeldung.com/java-binary-semaphore-vs-reentrant-lock) +- [Bad Practices With Synchronization](https://www.baeldung.com/java-synchronization-bad-practices) From 44552d1fa42f1413194a0af1a09a505655c6fe87 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 4 Feb 2021 00:10:36 +0800 Subject: [PATCH 47/51] Update README.md --- spring-5-reactive-client/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-5-reactive-client/README.md b/spring-5-reactive-client/README.md index eebdc23aed..b247a1669b 100644 --- a/spring-5-reactive-client/README.md +++ b/spring-5-reactive-client/README.md @@ -11,3 +11,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Logging Spring WebClient Calls](https://www.baeldung.com/spring-log-webclient-calls) - [Mocking a WebClient in Spring](https://www.baeldung.com/spring-mocking-webclient) - [Spring WebClient Filters](https://www.baeldung.com/spring-webclient-filters) +- [Get List of JSON Objects with WebClient](https://www.baeldung.com/spring-webclient-json-list) From d779223e57296fab6c8895baaaa46c54f7c874a6 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 4 Feb 2021 00:13:24 +0800 Subject: [PATCH 48/51] Update README.md --- spring-web-modules/spring-resttemplate-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-web-modules/spring-resttemplate-2/README.md b/spring-web-modules/spring-resttemplate-2/README.md index b2000e0481..54fad5e01b 100644 --- a/spring-web-modules/spring-resttemplate-2/README.md +++ b/spring-web-modules/spring-resttemplate-2/README.md @@ -11,3 +11,4 @@ This module contains articles about Spring RestTemplate - [How to Compress Requests Using the Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-compressing-requests) - [Get list of JSON objects with Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-json-list) - [A Guide To Spring Redirects](https://www.baeldung.com/spring-redirect-and-forward) +- [Spring RestTemplate Exception: “Not enough variables available to expand”](https://www.baeldung.com/spring-not-enough-variables-available) From bb5c2386317c533b759b8bbb4015ec5fe50c8495 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 4 Feb 2021 00:14:49 +0800 Subject: [PATCH 49/51] Update README.md --- spring-web-modules/spring-mvc-forms-jsp/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-web-modules/spring-mvc-forms-jsp/README.md b/spring-web-modules/spring-mvc-forms-jsp/README.md index 2c077f5171..afbf7afe40 100644 --- a/spring-web-modules/spring-mvc-forms-jsp/README.md +++ b/spring-web-modules/spring-mvc-forms-jsp/README.md @@ -7,3 +7,4 @@ This module contains articles about Spring MVC Forms using JSP - [Getting Started with Forms in Spring MVC](https://www.baeldung.com/spring-mvc-form-tutorial) - [Form Validation with AngularJS and Spring MVC](https://www.baeldung.com/validation-angularjs-spring-mvc) - [A Guide to the JSTL Library](https://www.baeldung.com/jstl) +- [Multiple Submit Buttons on a Form](https://www.baeldung.com/spring-form-multiple-submit-buttons) From 23ee2df79e36362ea7aced96489afbaccb3158e9 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Mon, 8 Feb 2021 22:48:54 +0100 Subject: [PATCH 50/51] JAVA-4395: Fix typo in addTagsOfOtherProduct method --- .../src/main/java/com/baeldung/map/Product.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/Product.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/Product.java index 5559895730..09b1a8847d 100644 --- a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/Product.java +++ b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/Product.java @@ -26,7 +26,7 @@ public class Product { return tags; } - public Product addTagsOfOtherProdcut(Product product) { + public Product addTagsOfOtherProduct(Product product) { this.tags.addAll(product.getTags()); return this; } @@ -100,11 +100,11 @@ public class Product { HashMap productsByName = new HashMap<>(); Product eBike2 = new Product("E-Bike", "A bike with a battery"); eBike2.getTags().add("sport"); - productsByName.merge("E-Bike", eBike2, Product::addTagsOfOtherProdcut); + productsByName.merge("E-Bike", eBike2, Product::addTagsOfOtherProduct); //Prior to Java 8: if(productsByName.containsKey("E-Bike")) { - productsByName.get("E-Bike").addTagsOfOtherProdcut(eBike2); + productsByName.get("E-Bike").addTagsOfOtherProduct(eBike2); } else { productsByName.put("E-Bike", eBike2); } @@ -117,7 +117,7 @@ public class Product { productsByName.compute("E-Bike", (k,v) -> { if(v != null) { - return v.addTagsOfOtherProdcut(eBike2); + return v.addTagsOfOtherProduct(eBike2); } else { return eBike2; } @@ -125,7 +125,7 @@ public class Product { //Prior to Java 8: if(productsByName.containsKey("E-Bike")) { - productsByName.get("E-Bike").addTagsOfOtherProdcut(eBike2); + productsByName.get("E-Bike").addTagsOfOtherProduct(eBike2); } else { productsByName.put("E-Bike", eBike2); } From 6c5c6fe3174e4a70a9049e6157401c7f7a4cfbbd Mon Sep 17 00:00:00 2001 From: Amy DeGregorio Date: Mon, 8 Feb 2021 21:11:25 -0500 Subject: [PATCH 51/51] BAEL-4331 (#10460) * BAEL-4331 * Add an integration test --- spring-boot-modules/pom.xml | 1 + .../spring-boot-runtime-2/README.md | 6 ++ .../spring-boot-runtime-2/pom.xml | 66 +++++++++++++++++++ .../heap/HeapSizeDemoApplication.java | 12 ++++ .../java/com/baeldung/heap/MemoryStats.java | 31 +++++++++ .../baeldung/heap/MemoryStatusController.java | 20 ++++++ .../resources/heap/spring-boot-runtime-2.conf | 1 + ...MemoryStatusControllerIntegrationTest.java | 32 +++++++++ 8 files changed, 169 insertions(+) create mode 100644 spring-boot-modules/spring-boot-runtime-2/README.md create mode 100644 spring-boot-modules/spring-boot-runtime-2/pom.xml create mode 100644 spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/heap/HeapSizeDemoApplication.java create mode 100644 spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/heap/MemoryStats.java create mode 100644 spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/heap/MemoryStatusController.java create mode 100644 spring-boot-modules/spring-boot-runtime-2/src/main/resources/heap/spring-boot-runtime-2.conf create mode 100644 spring-boot-modules/spring-boot-runtime-2/src/test/java/com/baeldung/heap/MemoryStatusControllerIntegrationTest.java diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index ee088c357a..263d2af089 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -62,6 +62,7 @@ spring-boot-properties-3 spring-boot-property-exp spring-boot-runtime + spring-boot-runtime-2 spring-boot-security spring-boot-springdoc spring-boot-swagger diff --git a/spring-boot-modules/spring-boot-runtime-2/README.md b/spring-boot-modules/spring-boot-runtime-2/README.md new file mode 100644 index 0000000000..f997f2473d --- /dev/null +++ b/spring-boot-modules/spring-boot-runtime-2/README.md @@ -0,0 +1,6 @@ +## Spring Boot Runtime 2 + +This module contains articles about administering a Spring Boot runtime + +### Relevant Articles: + - diff --git a/spring-boot-modules/spring-boot-runtime-2/pom.xml b/spring-boot-modules/spring-boot-runtime-2/pom.xml new file mode 100644 index 0000000000..8f6351165a --- /dev/null +++ b/spring-boot-modules/spring-boot-runtime-2/pom.xml @@ -0,0 +1,66 @@ + + + 4.0.0 + + + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT + ../ + + + spring-boot-runtime-2 + jar + + spring-boot-runtime-2 + Demo project for Spring Boot + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + ${project.artifactId} + + + src/main/resources/heap + ${project.build.directory} + true + + ${project.name}.conf + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + com.baeldung.heap.HeapSizeDemoApplication + + + + + true + + -Xms256m + -Xmx1g + + + + + + diff --git a/spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/heap/HeapSizeDemoApplication.java b/spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/heap/HeapSizeDemoApplication.java new file mode 100644 index 0000000000..60d4bf7bab --- /dev/null +++ b/spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/heap/HeapSizeDemoApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.heap; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class HeapSizeDemoApplication { + + public static void main(String[] args) { + SpringApplication.run(HeapSizeDemoApplication.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/heap/MemoryStats.java b/spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/heap/MemoryStats.java new file mode 100644 index 0000000000..0d2f471a12 --- /dev/null +++ b/spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/heap/MemoryStats.java @@ -0,0 +1,31 @@ +package com.baeldung.heap; + +public class MemoryStats { + private long heapSize; + private long heapMaxSize; + private long heapFreeSize; + + public long getHeapSize() { + return heapSize; + } + + public void setHeapSize(long heapSize) { + this.heapSize = heapSize; + } + + public long getHeapMaxSize() { + return heapMaxSize; + } + + public void setHeapMaxSize(long heapMaxSize) { + this.heapMaxSize = heapMaxSize; + } + + public long getHeapFreeSize() { + return heapFreeSize; + } + + public void setHeapFreeSize(long heapFreeSize) { + this.heapFreeSize = heapFreeSize; + } +} diff --git a/spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/heap/MemoryStatusController.java b/spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/heap/MemoryStatusController.java new file mode 100644 index 0000000000..293747fbd1 --- /dev/null +++ b/spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/heap/MemoryStatusController.java @@ -0,0 +1,20 @@ +package com.baeldung.heap; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class MemoryStatusController { + + @GetMapping("memory-status") + public MemoryStats getMemoryStatistics() { + MemoryStats stats = new MemoryStats(); + stats.setHeapSize(Runtime.getRuntime() + .totalMemory()); + stats.setHeapMaxSize(Runtime.getRuntime() + .maxMemory()); + stats.setHeapFreeSize(Runtime.getRuntime() + .freeMemory()); + return stats; + } +} diff --git a/spring-boot-modules/spring-boot-runtime-2/src/main/resources/heap/spring-boot-runtime-2.conf b/spring-boot-modules/spring-boot-runtime-2/src/main/resources/heap/spring-boot-runtime-2.conf new file mode 100644 index 0000000000..3bfde4e3d9 --- /dev/null +++ b/spring-boot-modules/spring-boot-runtime-2/src/main/resources/heap/spring-boot-runtime-2.conf @@ -0,0 +1 @@ +JAVA_OPTS="-Xms512m -Xmx1024m" \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-runtime-2/src/test/java/com/baeldung/heap/MemoryStatusControllerIntegrationTest.java b/spring-boot-modules/spring-boot-runtime-2/src/test/java/com/baeldung/heap/MemoryStatusControllerIntegrationTest.java new file mode 100644 index 0000000000..2e744285d8 --- /dev/null +++ b/spring-boot-modules/spring-boot-runtime-2/src/test/java/com/baeldung/heap/MemoryStatusControllerIntegrationTest.java @@ -0,0 +1,32 @@ +package com.baeldung.heap; + +import static org.hamcrest.Matchers.notANumber; +import static org.hamcrest.Matchers.not; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +@RunWith(SpringRunner.class) +@WebMvcTest(MemoryStatusController.class) +public class MemoryStatusControllerIntegrationTest { + + @Autowired + private MockMvc mvc; + + @Test + public void whenGetMemoryStatistics_thenReturnJsonArray() throws Exception { + mvc.perform(get("/memory-status").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("heapSize", not(notANumber()))) + .andExpect(jsonPath("heapMaxSize", not(notANumber()))) + .andExpect(jsonPath("heapFreeSize", not(notANumber()))); + } +}