From e9e7aace3164288dfa17113140d69f9bbf974ec0 Mon Sep 17 00:00:00 2001 From: emanueltrandafir1993 Date: Sun, 8 Jan 2023 16:59:46 +0100 Subject: [PATCH 01/34] BAEL-6058: extracting request header --- .../requestheader/BuzzController.java | 21 ++++++ .../requestheader/FooBarController.java | 22 +++++++ .../HeaderInterceptorApplication.java | 15 +++++ .../config/HeaderInterceptorConfig.java | 33 ++++++++++ .../interceptor/OperatorHolder.java | 13 ++++ .../interceptor/OperatorInterceptor.java | 22 +++++++ .../HeaderInterceptorApplicationTest.java | 66 +++++++++++++++++++ 7 files changed, 192 insertions(+) create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/BuzzController.java create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/FooBarController.java create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/HeaderInterceptorApplication.java create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/config/HeaderInterceptorConfig.java create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/interceptor/OperatorHolder.java create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/interceptor/OperatorInterceptor.java create mode 100644 spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/requestheader/HeaderInterceptorApplicationTest.java diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/BuzzController.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/BuzzController.java new file mode 100644 index 0000000000..09bf16f008 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/BuzzController.java @@ -0,0 +1,21 @@ +package com.baeldung.requestheader; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.requestheader.interceptor.OperatorHolder; + +@RestController +public class BuzzController { + private final OperatorHolder operatorHolder; + + public BuzzController(OperatorHolder operatorHolder) { + this.operatorHolder = operatorHolder; + } + + @GetMapping("buzz") + public String buzz() { + return "hello, " + operatorHolder.getOperator(); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/FooBarController.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/FooBarController.java new file mode 100644 index 0000000000..e0fd5f2f64 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/FooBarController.java @@ -0,0 +1,22 @@ +package com.baeldung.requestheader; + +import javax.servlet.http.HttpServletRequest; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class FooBarController { + + @GetMapping("foo") + public String foo(HttpServletRequest request) { + String operator = request.getHeader("operator"); + return "hello, " + operator; + } + + @GetMapping("bar") + public String bar(@RequestHeader("operator") String operator) { + return "hello, " + operator; + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/HeaderInterceptorApplication.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/HeaderInterceptorApplication.java new file mode 100644 index 0000000000..f2e9aaca12 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/HeaderInterceptorApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.requestheader; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +@SpringBootApplication +@EnableWebMvc +public class HeaderInterceptorApplication { + + public static void main(String[] args) { + SpringApplication.run(HeaderInterceptorApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/config/HeaderInterceptorConfig.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/config/HeaderInterceptorConfig.java new file mode 100644 index 0000000000..07fb5b5184 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/config/HeaderInterceptorConfig.java @@ -0,0 +1,33 @@ +package com.baeldung.requestheader.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Scope; +import org.springframework.context.annotation.ScopedProxyMode; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import com.baeldung.requestheader.interceptor.OperatorHolder; +import com.baeldung.requestheader.interceptor.OperatorInterceptor; + +@Configuration +public class HeaderInterceptorConfig implements WebMvcConfigurer { + + @Override + public void addInterceptors(final InterceptorRegistry registry) { + registry.addInterceptor(operatorInterceptor()); + } + + @Bean + public OperatorInterceptor operatorInterceptor() { + return new OperatorInterceptor(operatorHolder()); + } + + @Bean + @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) + public OperatorHolder operatorHolder() { + return new OperatorHolder(); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/interceptor/OperatorHolder.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/interceptor/OperatorHolder.java new file mode 100644 index 0000000000..31d36c0b59 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/interceptor/OperatorHolder.java @@ -0,0 +1,13 @@ +package com.baeldung.requestheader.interceptor; + +public class OperatorHolder { + private String operator; + + public String getOperator() { + return operator; + } + + public void setOperator(String operator) { + this.operator = operator; + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/interceptor/OperatorInterceptor.java b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/interceptor/OperatorInterceptor.java new file mode 100644 index 0000000000..0d0a0c7405 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/main/java/com/baeldung/requestheader/interceptor/OperatorInterceptor.java @@ -0,0 +1,22 @@ +package com.baeldung.requestheader.interceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.servlet.HandlerInterceptor; + +public class OperatorInterceptor implements HandlerInterceptor { + + private final OperatorHolder operatorHolder; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + String operator = request.getHeader("operator"); + operatorHolder.setOperator(operator); + return true; + } + + public OperatorInterceptor(OperatorHolder operatorHolder) { + this.operatorHolder = operatorHolder; + } +} diff --git a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/requestheader/HeaderInterceptorApplicationTest.java b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/requestheader/HeaderInterceptorApplicationTest.java new file mode 100644 index 0000000000..77b48fbe99 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/requestheader/HeaderInterceptorApplicationTest.java @@ -0,0 +1,66 @@ +package com.baeldung.requestheader; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = { HeaderInterceptorApplication.class }) +@WebAppConfiguration +public class HeaderInterceptorApplicationTest { + + @Autowired + private WebApplicationContext webApplicationContext; + + private MockMvc mockMvc; + + @BeforeEach + public void setup() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext) + .build(); + } + + @Test + public void givenARequestWithOperatorHeader_whenWeCallFooEndpoint_thenOperatorIsExtracted() throws Exception { + MockHttpServletResponse response = this.mockMvc.perform(get("/foo").header("operator", "John.Doe")) + .andDo(print()) + .andReturn() + .getResponse(); + + assertThat(response.getContentAsString()).isEqualTo("hello, John.Doe"); + } + + @Test + public void givenARequestWithOperatorHeader_whenWeCallBarEndpoint_thenOperatorIsExtracted() throws Exception { + MockHttpServletResponse response = this.mockMvc.perform(get("/bar").header("operator", "John.Doe")) + .andDo(print()) + .andReturn() + .getResponse(); + + assertThat(response.getContentAsString()).isEqualTo("hello, John.Doe"); + } + + @Test + public void givenARequestWithOperatorHeader_whenWeCallBuzzEndpoint_thenOperatorIsIntercepted() throws Exception { + MockHttpServletResponse response = this.mockMvc.perform(get("/buzz").header("operator", "John.Doe")) + .andDo(print()) + .andReturn() + .getResponse(); + + assertThat(response.getContentAsString()).isEqualTo("hello, John.Doe"); + } + +} \ No newline at end of file From 77d6a987a8684460c91460e4499e6b0e295e09e0 Mon Sep 17 00:00:00 2001 From: emanueltrandafir1993 Date: Tue, 17 Jan 2023 20:47:07 +0100 Subject: [PATCH 02/34] BAEL-6058: renamed test class --- ...licationTest.java => HeaderInterceptorIntegrationTest.java} | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) rename spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/requestheader/{HeaderInterceptorApplicationTest.java => HeaderInterceptorIntegrationTest.java} (96%) diff --git a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/requestheader/HeaderInterceptorApplicationTest.java b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/requestheader/HeaderInterceptorIntegrationTest.java similarity index 96% rename from spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/requestheader/HeaderInterceptorApplicationTest.java rename to spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/requestheader/HeaderInterceptorIntegrationTest.java index 77b48fbe99..9343a608e4 100644 --- a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/requestheader/HeaderInterceptorApplicationTest.java +++ b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/requestheader/HeaderInterceptorIntegrationTest.java @@ -4,7 +4,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -20,7 +19,7 @@ import org.springframework.web.context.WebApplicationContext; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = { HeaderInterceptorApplication.class }) @WebAppConfiguration -public class HeaderInterceptorApplicationTest { +public class HeaderInterceptorIntegrationTest { @Autowired private WebApplicationContext webApplicationContext; From b81ae5b701fcd85c9697da684b0da30e7e008075 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 19 Jan 2023 07:05:30 +0800 Subject: [PATCH 03/34] Update README.md [skip ci] --- persistence-modules/flyway/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/flyway/README.md b/persistence-modules/flyway/README.md index bd5f9bbe03..5fbbc7df9c 100644 --- a/persistence-modules/flyway/README.md +++ b/persistence-modules/flyway/README.md @@ -2,3 +2,4 @@ - [Database Migrations with Flyway](http://www.baeldung.com/database-migrations-with-flyway) - [A Guide to Flyway Callbacks](http://www.baeldung.com/flyway-callbacks) - [Rolling Back Migrations with Flyway](https://www.baeldung.com/flyway-roll-back) +- [Flyway Out of Order Migrations](https://www.baeldung.com/flyway-migrations) From 66441d4f739ad33d40c733d18ba9db0a56873754 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 19 Jan 2023 07:09:56 +0800 Subject: [PATCH 04/34] Create README.md [skip ci] --- logging-modules/tinylog2/README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 logging-modules/tinylog2/README.md diff --git a/logging-modules/tinylog2/README.md b/logging-modules/tinylog2/README.md new file mode 100644 index 0000000000..880ff8e65f --- /dev/null +++ b/logging-modules/tinylog2/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Lightweight Logging With tinylog 2](https://www.baeldung.com/java-logging-tinylog-guide) From 289edb5e48ff97d9884c70b6d42f83309ffda8e9 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 19 Jan 2023 07:16:25 +0800 Subject: [PATCH 05/34] Update README.md [skip ci] --- microservices-modules/rest-express/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/microservices-modules/rest-express/README.md b/microservices-modules/rest-express/README.md index 0fdff99fb7..a3340b238d 100644 --- a/microservices-modules/rest-express/README.md +++ b/microservices-modules/rest-express/README.md @@ -2,4 +2,5 @@ This module contains articles about RestExpress. -### Relevant articles \ No newline at end of file +### Relevant articles +- [RESTful Microservices With RestExpress](https://www.baeldung.com/java-restexpress-guide) From 1af5982423da8321233c5dd8564e0c65f5bde34d Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 19 Jan 2023 07:20:47 +0800 Subject: [PATCH 06/34] Update README.md [skip ci] --- spring-kafka-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-kafka-2/README.md b/spring-kafka-2/README.md index 76c090342d..1f5e015f9e 100644 --- a/spring-kafka-2/README.md +++ b/spring-kafka-2/README.md @@ -4,4 +4,4 @@ This module contains articles about Spring with Kafka ### Relevant articles -- [Implementing Retry In Kafka Consumer] +- [Implementing Retry In Kafka Consumer](https://www.baeldung.com/spring-retry-kafka-consumer) From 063be454404715f7608dc3fd774839d3a383474d Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 19 Jan 2023 07:25:57 +0800 Subject: [PATCH 07/34] Update README.md [skip ci] --- jackson-modules/jackson-annotations/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jackson-modules/jackson-annotations/README.md b/jackson-modules/jackson-annotations/README.md index 3b6cd6f20b..8b405ec778 100644 --- a/jackson-modules/jackson-annotations/README.md +++ b/jackson-modules/jackson-annotations/README.md @@ -8,3 +8,4 @@ This module contains articles about Jackson annotations. - [Jackson – Bidirectional Relationships](https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion) - [Jackson JSON Views](https://www.baeldung.com/jackson-json-view-annotation) - [Deduction-Based Polymorphism in Jackson 2.12](https://www.baeldung.com/jackson-deduction-based-polymorphism) +- [@JsonIgnore vs @Transient](https://www.baeldung.com/java-jsonignore-vs-transient) From f08815a84f13b0ccb21e28e3963bd70e80b4611b Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 19 Jan 2023 07:30:26 +0800 Subject: [PATCH 08/34] Update README.md [skip ci] --- core-java-modules/core-java-collections-array-list/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-collections-array-list/README.md b/core-java-modules/core-java-collections-array-list/README.md index d24f7492bb..094ae33c40 100644 --- a/core-java-modules/core-java-collections-array-list/README.md +++ b/core-java-modules/core-java-collections-array-list/README.md @@ -9,3 +9,4 @@ This module contains articles about the Java ArrayList collection - [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist) - [Removing an Element From an ArrayList](https://www.baeldung.com/java-arraylist-remove-element) - [The Capacity of an ArrayList vs the Size of an Array in Java](https://www.baeldung.com/java-list-capacity-array-size) +- [Case-Insensitive Searching in ArrayList](https://www.baeldung.com/java-arraylist-case-insensitive-search) From 00e455acbb49f034a8a786cf57c63b8da71c3de3 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 19 Jan 2023 07:37:32 +0800 Subject: [PATCH 09/34] Update README.md [skip ci] --- spring-web-modules/spring-web-url/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-web-modules/spring-web-url/README.md b/spring-web-modules/spring-web-url/README.md index 41b479337b..79a89f4386 100644 --- a/spring-web-modules/spring-web-url/README.md +++ b/spring-web-modules/spring-web-url/README.md @@ -6,3 +6,4 @@ This module contains articles about Spring MVC - [Using a Slash Character in Spring URLs](https://www.baeldung.com/spring-slash-character-in-url) - [Excluding URLs for a Filter in a Spring Web Application](https://www.baeldung.com/spring-exclude-filter) - [Handling URL Encoded Form Data in Spring REST](https://www.baeldung.com/spring-url-encoded-form-data) +- [Spring MVC – Mapping the Root URL to a Page](https://www.baeldung.com/spring-mvc-map-root-url) From 0b2b705298afb98c027a7404e3a9fbf2066254a1 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 19 Jan 2023 07:41:04 +0800 Subject: [PATCH 10/34] Update README.md [skip ci] --- jenkins-modules/jenkins-jobs/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jenkins-modules/jenkins-jobs/README.md b/jenkins-modules/jenkins-jobs/README.md index 7b33dc6d99..d29a25244f 100644 --- a/jenkins-modules/jenkins-jobs/README.md +++ b/jenkins-modules/jenkins-jobs/README.md @@ -2,3 +2,4 @@ - [Trigger Another Job from a Jenkins Pipeline](https://www.baeldung.com/ops/jenkins-pipeline-trigger-new-job) - [Fixing the “No Such DSL method” Error in Jenkins Pipeline](https://www.baeldung.com/ops/jenkins-pipeline-no-such-dsl-method-error) - [Jenkins Pipeline – Change to Another Folder](https://www.baeldung.com/ops/jenkins-pipeline-change-to-another-folder) +- [How to Stop a Zombie Job on Jenkins Without Restarting the Server?](https://www.baeldung.com/ops/stop-zombie-job-on-jenkins-without-restarting-the-server) From 00913e061a7c84bf816dc6dcb47538d63dae3170 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 19 Jan 2023 07:44:33 +0800 Subject: [PATCH 11/34] Update README.md [skip ci] --- core-java-modules/core-java-8/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-8/README.md b/core-java-modules/core-java-8/README.md index ff4ceaf6db..6061f3318d 100644 --- a/core-java-modules/core-java-8/README.md +++ b/core-java-modules/core-java-8/README.md @@ -11,4 +11,5 @@ This module contains articles about Java 8 core features - [Finding Min/Max in an Array with Java](https://www.baeldung.com/java-array-min-max) - [Internationalization and Localization in Java 8](https://www.baeldung.com/java-8-localization) - [Generalized Target-Type Inference in Java](https://www.baeldung.com/java-generalized-target-type-inference) +- [Monads in Java](https://www.baeldung.com/java-monads) - [[More -->]](/core-java-modules/core-java-8-2) From a844943283f4998e8b991850406e2329256e356d Mon Sep 17 00:00:00 2001 From: etrandafir93 <75391049+etrandafir93@users.noreply.github.com> Date: Thu, 19 Jan 2023 09:59:49 +0100 Subject: [PATCH 12/34] BAEL-6058: fixed formatting for line continuation --- .../HeaderInterceptorIntegrationTest.java | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/requestheader/HeaderInterceptorIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/requestheader/HeaderInterceptorIntegrationTest.java index 9343a608e4..ee053a4c36 100644 --- a/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/requestheader/HeaderInterceptorIntegrationTest.java +++ b/spring-boot-modules/spring-boot-mvc-5/src/test/java/com/baeldung/requestheader/HeaderInterceptorIntegrationTest.java @@ -29,15 +29,15 @@ public class HeaderInterceptorIntegrationTest { @BeforeEach public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext) - .build(); + .build(); } @Test public void givenARequestWithOperatorHeader_whenWeCallFooEndpoint_thenOperatorIsExtracted() throws Exception { MockHttpServletResponse response = this.mockMvc.perform(get("/foo").header("operator", "John.Doe")) - .andDo(print()) - .andReturn() - .getResponse(); + .andDo(print()) + .andReturn() + .getResponse(); assertThat(response.getContentAsString()).isEqualTo("hello, John.Doe"); } @@ -45,9 +45,9 @@ public class HeaderInterceptorIntegrationTest { @Test public void givenARequestWithOperatorHeader_whenWeCallBarEndpoint_thenOperatorIsExtracted() throws Exception { MockHttpServletResponse response = this.mockMvc.perform(get("/bar").header("operator", "John.Doe")) - .andDo(print()) - .andReturn() - .getResponse(); + .andDo(print()) + .andReturn() + .getResponse(); assertThat(response.getContentAsString()).isEqualTo("hello, John.Doe"); } @@ -55,11 +55,11 @@ public class HeaderInterceptorIntegrationTest { @Test public void givenARequestWithOperatorHeader_whenWeCallBuzzEndpoint_thenOperatorIsIntercepted() throws Exception { MockHttpServletResponse response = this.mockMvc.perform(get("/buzz").header("operator", "John.Doe")) - .andDo(print()) - .andReturn() - .getResponse(); + .andDo(print()) + .andReturn() + .getResponse(); assertThat(response.getContentAsString()).isEqualTo("hello, John.Doe"); } -} \ No newline at end of file +} From 845ed7690e92bc398bcfdacd0a73e1b3c03a2c70 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Thu, 19 Jan 2023 21:30:18 +0530 Subject: [PATCH 13/34] JAVA-16308 Potential issue in Introduction to Spring Data Elasticsearch article (#13286) * JAVA-16308 Potential issue in Introduction to Spring Data Elasticsearch article * JAVA-16308 Update code as per Review Comments --- .../spring/data/es/config/Config.java | 13 ++++------ .../data/es/ElasticSearchManualTest.java | 12 +++++----- .../data/es/ElasticSearchQueryManualTest.java | 24 +++++++++---------- 3 files changed, 22 insertions(+), 27 deletions(-) diff --git a/persistence-modules/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java b/persistence-modules/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java index 51bbe73e9e..7f6653d7a8 100644 --- a/persistence-modules/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java +++ b/persistence-modules/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java @@ -6,17 +6,17 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.elasticsearch.client.ClientConfiguration; import org.springframework.data.elasticsearch.client.RestClients; -import org.springframework.data.elasticsearch.core.ElasticsearchOperations; -import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; +import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration; import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; @Configuration @EnableElasticsearchRepositories(basePackages = "com.baeldung.spring.data.es.repository") @ComponentScan(basePackages = { "com.baeldung.spring.data.es.service" }) -public class Config { +public class Config extends AbstractElasticsearchConfiguration { @Bean - RestHighLevelClient client() { + @Override + public RestHighLevelClient elasticsearchClient() { ClientConfiguration clientConfiguration = ClientConfiguration.builder() .connectedTo("localhost:9200") .build(); @@ -24,9 +24,4 @@ public class Config { return RestClients.create(clientConfiguration) .rest(); } - - @Bean - public ElasticsearchOperations elasticsearchTemplate() { - return new ElasticsearchRestTemplate(client()); - } } diff --git a/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchManualTest.java b/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchManualTest.java index 412cd04e09..cc38acc41c 100644 --- a/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchManualTest.java +++ b/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchManualTest.java @@ -22,7 +22,7 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; -import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; +import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.SearchHits; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; @@ -41,7 +41,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; public class ElasticSearchManualTest { @Autowired - private ElasticsearchRestTemplate elasticsearchTemplate; + private ElasticsearchOperations elasticsearchOperations; @Autowired private ArticleRepository articleRepository; @@ -117,7 +117,7 @@ public class ElasticSearchManualTest { final Query searchQuery = new NativeSearchQueryBuilder().withFilter(regexpQuery("title", ".*data.*")) .build(); - final SearchHits
articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); + final SearchHits
articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog")); assertEquals(1, articles.getTotalHits()); } @@ -126,7 +126,7 @@ public class ElasticSearchManualTest { public void givenSavedDoc_whenTitleUpdated_thenCouldFindByUpdatedTitle() { final Query searchQuery = new NativeSearchQueryBuilder().withQuery(fuzzyQuery("title", "serch")) .build(); - final SearchHits
articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); + final SearchHits
articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog")); assertEquals(1, articles.getTotalHits()); @@ -147,7 +147,7 @@ public class ElasticSearchManualTest { final Query searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", articleTitle).minimumShouldMatch("75%")) .build(); - final SearchHits
articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); + final SearchHits
articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog")); assertEquals(1, articles.getTotalHits()); final long count = articleRepository.count(); @@ -162,7 +162,7 @@ public class ElasticSearchManualTest { public void givenSavedDoc_whenOneTermMatches_thenFindByTitle() { final Query searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Search engines").operator(AND)) .build(); - final SearchHits
articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); + final SearchHits
articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog")); assertEquals(1, articles.getTotalHits()); } } diff --git a/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryManualTest.java b/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryManualTest.java index aaf0c80097..03c8da80c9 100644 --- a/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryManualTest.java +++ b/persistence-modules/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryManualTest.java @@ -39,7 +39,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; +import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.SearchHits; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; @@ -58,7 +58,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; public class ElasticSearchQueryManualTest { @Autowired - private ElasticsearchRestTemplate elasticsearchTemplate; + private ElasticsearchOperations elasticsearchOperations; @Autowired private ArticleRepository articleRepository; @@ -101,7 +101,7 @@ public class ElasticSearchQueryManualTest { public void givenFullTitle_whenRunMatchQuery_thenDocIsFound() { final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Search engines").operator(Operator.AND)) .build(); - final SearchHits
articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); + final SearchHits
articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog")); assertEquals(1, articles.getTotalHits()); } @@ -110,7 +110,7 @@ public class ElasticSearchQueryManualTest { final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Engines Solutions")) .build(); - final SearchHits
articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); + final SearchHits
articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog")); assertEquals(1, articles.getTotalHits()); assertEquals("Search engines", articles.getSearchHit(0) @@ -123,7 +123,7 @@ public class ElasticSearchQueryManualTest { final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "elasticsearch data")) .build(); - final SearchHits
articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); + final SearchHits
articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog")); assertEquals(3, articles.getTotalHits()); } @@ -133,14 +133,14 @@ public class ElasticSearchQueryManualTest { NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title.verbatim", "Second Article About Elasticsearch")) .build(); - SearchHits
articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); + SearchHits
articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog")); assertEquals(1, articles.getTotalHits()); searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title.verbatim", "Second Article About")) .build(); - articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); + articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog")); assertEquals(0, articles.getTotalHits()); } @@ -150,7 +150,7 @@ public class ElasticSearchQueryManualTest { final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder) .build(); - final SearchHits
articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); + final SearchHits
articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog")); assertEquals(2, articles.getTotalHits()); } @@ -205,7 +205,7 @@ public class ElasticSearchQueryManualTest { final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchPhraseQuery("title", "spring elasticsearch").slop(1)) .build(); - final SearchHits
articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); + final SearchHits
articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog")); assertEquals(1, articles.getTotalHits()); } @@ -217,7 +217,7 @@ public class ElasticSearchQueryManualTest { .prefixLength(3)) .build(); - final SearchHits
articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); + final SearchHits
articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog")); assertEquals(1, articles.getTotalHits()); } @@ -229,7 +229,7 @@ public class ElasticSearchQueryManualTest { .type(MultiMatchQueryBuilder.Type.BEST_FIELDS)) .build(); - final SearchHits
articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); + final SearchHits
articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog")); assertEquals(2, articles.getTotalHits()); } @@ -241,7 +241,7 @@ public class ElasticSearchQueryManualTest { final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder) .build(); - final SearchHits
articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); + final SearchHits
articles = elasticsearchOperations.search(searchQuery, Article.class, IndexCoordinates.of("blog")); assertEquals(2, articles.getTotalHits()); } From aa53dde12729407d9999dc42610d9969a73d1125 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Thu, 19 Jan 2023 21:36:54 +0530 Subject: [PATCH 14/34] JAVA-14179 Potential issue in Keycloak Integration - OAuth article (#13305) --- .../src/main/resources/application.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/resources/application.yml b/spring-boot-modules/spring-boot-swagger-keycloak/src/main/resources/application.yml index e4bcdb5888..5d3c8b3af5 100644 --- a/spring-boot-modules/spring-boot-swagger-keycloak/src/main/resources/application.yml +++ b/spring-boot-modules/spring-boot-swagger-keycloak/src/main/resources/application.yml @@ -2,7 +2,6 @@ keycloak: auth-server-url: https://api.example.com/auth # Keycloak server url realm: todos-service-realm # Keycloak Realm resource: todos-service-clients # Keycloak Client - public-client: true principal-attribute: preferred_username ssl-required: external credentials: From edd27fda3ba06dcb11e9e55bb9ec92eb59302056 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Thu, 19 Jan 2023 16:21:21 +0000 Subject: [PATCH 15/34] [JAVA-15021] Upgraded to apache httpclient 5.2 (#13309) Co-authored-by: panagiotiskakos --- httpclient-simple/pom.xml | 13 ++ .../httpclient/HttpClientPostingLiveTest.java | 183 +++++++++++------- .../httpclient/ProgressEntityWrapper.java | 4 +- 3 files changed, 125 insertions(+), 75 deletions(-) diff --git a/httpclient-simple/pom.xml b/httpclient-simple/pom.xml index 45da1e7a39..c39983564f 100644 --- a/httpclient-simple/pom.xml +++ b/httpclient-simple/pom.xml @@ -112,6 +112,18 @@ + + + org.apache.httpcomponents.client5 + httpclient5-fluent + ${httpclient5-fluent.version} + + + commons-logging + commons-logging + + + org.apache.commons @@ -308,6 +320,7 @@ 5.2 5.2 + 5.2 1.6.1 diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientPostingLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientPostingLiveTest.java index f5dff8d757..b30921c990 100644 --- a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientPostingLiveTest.java +++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientPostingLiveTest.java @@ -1,74 +1,88 @@ package com.baeldung.httpclient; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.auth.AuthenticationException; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.fluent.Form; -import org.apache.http.client.fluent.Request; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.impl.auth.BasicScheme; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.message.BasicNameValuePair; -import org.junit.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.junit.jupiter.api.Test; + +import org.apache.hc.client5.http.auth.AuthScope; +import org.apache.hc.client5.http.auth.UsernamePasswordCredentials; +import org.apache.hc.client5.http.classic.methods.HttpPost; +import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; +import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; +import org.apache.hc.client5.http.fluent.Form; +import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.NameValuePair; +import org.apache.hc.client5.http.fluent.Request; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.http.message.BasicNameValuePair; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; +import com.baeldung.handler.CustomHttpClientResponseHandler; /* * NOTE : Need module spring-rest to be running */ -public class HttpClientPostingLiveTest { +class HttpClientPostingLiveTest { private static final String SAMPLE_URL = "http://www.example.com"; private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; private static final String DEFAULT_USER = "test"; private static final String DEFAULT_PASS = "test"; @Test - public void whenSendPostRequestUsingHttpClient_thenCorrect() throws IOException { - final CloseableHttpClient client = HttpClients.createDefault(); + void whenSendPostRequestUsingHttpClient_thenCorrect() throws IOException { final HttpPost httpPost = new HttpPost(SAMPLE_URL); - final List params = new ArrayList(); params.add(new BasicNameValuePair("username", DEFAULT_USER)); params.add(new BasicNameValuePair("password", DEFAULT_PASS)); httpPost.setEntity(new UrlEncodedFormEntity(params)); - final CloseableHttpResponse response = client.execute(httpPost); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); - client.close(); + try (CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(httpPost, new CustomHttpClientResponseHandler())) { + + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } } @Test - public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException, AuthenticationException { - final CloseableHttpClient client = HttpClients.createDefault(); + void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException { final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION); - httpPost.setEntity(new StringEntity("test post")); - final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS); - httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null)); - final CloseableHttpResponse response = client.execute(httpPost); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); - client.close(); + final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); + final UsernamePasswordCredentials credentials = + new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS.toCharArray()); + + credsProvider.setCredentials(new AuthScope(URL_SECURED_BY_BASIC_AUTHENTICATION, 80) ,credentials); + + try (CloseableHttpClient client = HttpClients.custom() + .setDefaultCredentialsProvider(credsProvider) + .build(); + + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(httpPost, new CustomHttpClientResponseHandler())) { + + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } } @Test - public void whenPostJsonUsingHttpClient_thenCorrect() throws IOException { - final CloseableHttpClient client = HttpClients.createDefault(); + void whenPostJsonUsingHttpClient_thenCorrect() throws IOException { final HttpPost httpPost = new HttpPost(SAMPLE_URL); final String json = "{\"id\":1,\"name\":\"John\"}"; @@ -77,68 +91,91 @@ public class HttpClientPostingLiveTest { httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); - final CloseableHttpResponse response = client.execute(httpPost); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); - client.close(); + try (CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(httpPost, new CustomHttpClientResponseHandler())) { + + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } } @Test - public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws IOException { - final HttpResponse response = Request.Post(SAMPLE_URL).bodyForm(Form.form().add("username", DEFAULT_USER).add("password", DEFAULT_PASS).build()).execute().returnResponse(); + void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws IOException { + Request request = Request.post(SAMPLE_URL) + .bodyForm(Form.form() + .add("username", DEFAULT_USER) + .add("password", DEFAULT_PASS) + .build()); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + HttpResponse response = request.execute() + .returnResponse(); + assertThat(response.getCode(), equalTo(HttpStatus.SC_OK)); } @Test - public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws IOException { - final CloseableHttpClient client = HttpClients.createDefault(); + void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws IOException { final HttpPost httpPost = new HttpPost(SAMPLE_URL); final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("username", DEFAULT_USER); builder.addTextBody("password", DEFAULT_PASS); - builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext"); + builder.addBinaryBody( + "file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext"); + + final HttpEntity multipart = builder.build(); + httpPost.setEntity(multipart); + + try (CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(httpPost, new CustomHttpClientResponseHandler())) { + + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } + } + + @Test + void whenUploadFileUsingHttpClient_thenCorrect() throws IOException { + final HttpPost httpPost = new HttpPost(SAMPLE_URL); + + final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + builder.addBinaryBody( + "file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext"); final HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); - final CloseableHttpResponse response = client.execute(httpPost); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); - client.close(); + try (CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(httpPost, new CustomHttpClientResponseHandler())) { + + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } } @Test - public void whenUploadFileUsingHttpClient_thenCorrect() throws IOException { - final CloseableHttpClient client = HttpClients.createDefault(); + void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws IOException { final HttpPost httpPost = new HttpPost(SAMPLE_URL); final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext"); + builder.addBinaryBody( + "file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext"); final HttpEntity multipart = builder.build(); - httpPost.setEntity(multipart); - - final CloseableHttpResponse response = client.execute(httpPost); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); - client.close(); - } - - @Test - public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws IOException { - final CloseableHttpClient client = HttpClients.createDefault(); - final HttpPost httpPost = new HttpPost(SAMPLE_URL); - - final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext"); - final HttpEntity multipart = builder.build(); - - final ProgressEntityWrapper.ProgressListener pListener = percentage -> assertFalse(Float.compare(percentage, 100) > 0); + final ProgressEntityWrapper.ProgressListener pListener = + percentage -> assertFalse(Float.compare(percentage, 100) > 0); httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener)); - final CloseableHttpResponse response = client.execute(httpPost); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); - client.close(); + try (CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(httpPost, new CustomHttpClientResponseHandler())) { + + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } } } \ No newline at end of file diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/ProgressEntityWrapper.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/ProgressEntityWrapper.java index c7adf51b3e..0fbc6e5dcd 100644 --- a/httpclient-simple/src/test/java/com/baeldung/httpclient/ProgressEntityWrapper.java +++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/ProgressEntityWrapper.java @@ -4,8 +4,8 @@ import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; -import org.apache.http.HttpEntity; -import org.apache.http.entity.HttpEntityWrapper; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.io.entity.HttpEntityWrapper; public class ProgressEntityWrapper extends HttpEntityWrapper { private final ProgressListener listener; From 947f992d84457c19029378ef3c1594f2ac7dcb02 Mon Sep 17 00:00:00 2001 From: Anastasios Ioannidis <121166333+anastasiosioannidis@users.noreply.github.com> Date: Thu, 19 Jan 2023 19:58:20 +0200 Subject: [PATCH 16/34] JAVA-15609 Fixed failing tests (#13304) --- ....java => ApiControllerDocTesterUnitTest.java} | 6 +++--- ...nTest.java => ApiControllerMockUnitTest.java} | 16 ++++++++-------- 2 files changed, 11 insertions(+), 11 deletions(-) rename web-modules/ninja/src/test/java/controllers/{ApiControllerDocTesterIntegrationTest.java => ApiControllerDocTesterUnitTest.java} (90%) rename web-modules/ninja/src/test/java/controllers/{ApiControllerMockIntegrationTest.java => ApiControllerMockUnitTest.java} (68%) diff --git a/web-modules/ninja/src/test/java/controllers/ApiControllerDocTesterIntegrationTest.java b/web-modules/ninja/src/test/java/controllers/ApiControllerDocTesterUnitTest.java similarity index 90% rename from web-modules/ninja/src/test/java/controllers/ApiControllerDocTesterIntegrationTest.java rename to web-modules/ninja/src/test/java/controllers/ApiControllerDocTesterUnitTest.java index a075497dc8..64812f6935 100644 --- a/web-modules/ninja/src/test/java/controllers/ApiControllerDocTesterIntegrationTest.java +++ b/web-modules/ninja/src/test/java/controllers/ApiControllerDocTesterUnitTest.java @@ -7,11 +7,11 @@ import org.doctester.testbrowser.Response; import org.junit.Test; import ninja.NinjaDocTester; -public class ApiControllerDocTesterIntegrationTest extends NinjaDocTester { +public class ApiControllerDocTesterUnitTest extends NinjaDocTester { String URL_INDEX = "/"; String URL_HELLO = "/hello"; - + @Test public void testGetIndex() { Response response = makeRequest(Request.GET().url(testServerUrl().path(URL_INDEX))); @@ -23,5 +23,5 @@ public class ApiControllerDocTesterIntegrationTest extends NinjaDocTester { Response response = makeRequest(Request.GET().url(testServerUrl().path(URL_HELLO))); assertThat(response.payload, containsString("Bonjour, bienvenue dans Ninja Framework!")); } - + } diff --git a/web-modules/ninja/src/test/java/controllers/ApiControllerMockIntegrationTest.java b/web-modules/ninja/src/test/java/controllers/ApiControllerMockUnitTest.java similarity index 68% rename from web-modules/ninja/src/test/java/controllers/ApiControllerMockIntegrationTest.java rename to web-modules/ninja/src/test/java/controllers/ApiControllerMockUnitTest.java index 53a760aadc..8534fa0b0f 100644 --- a/web-modules/ninja/src/test/java/controllers/ApiControllerMockIntegrationTest.java +++ b/web-modules/ninja/src/test/java/controllers/ApiControllerMockUnitTest.java @@ -1,23 +1,23 @@ package controllers; import static org.junit.Assert.assertEquals; -import javax.inject.Inject; + import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import ninja.NinjaRunner; + +import ninja.NinjaTest; import ninja.Result; import services.UserService; -@RunWith(NinjaRunner.class) -public class ApiControllerMockIntegrationTest { +public class ApiControllerMockUnitTest extends NinjaTest { - @Inject private UserService userService; + private UserService userService; - ApplicationController applicationController; + private ApplicationController applicationController; @Before public void setupTest() { + userService = this.ninjaTestServer.getInjector().getInstance(UserService.class); applicationController = new ApplicationController(); applicationController.userService = userService; } @@ -28,5 +28,5 @@ public class ApiControllerMockIntegrationTest { System.out.println(result.getRenderable()); assertEquals(userService.getUserMap().toString(), result.getRenderable().toString()); } - + } From 58069ea225fe025432c4da0443570c66fbb5505a Mon Sep 17 00:00:00 2001 From: Anastasios Ioannidis <121166333+anastasiosioannidis@users.noreply.github.com> Date: Thu, 19 Jan 2023 20:07:14 +0200 Subject: [PATCH 17/34] JAVA-12390 Enabled CORS (#13208) --- .../basicauth/config/BasicAuthConfiguration.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/spring-security-modules/spring-security-web-angular/spring-security-web-angular-server/src/main/java/com/baeldung/springbootsecurityrest/basicauth/config/BasicAuthConfiguration.java b/spring-security-modules/spring-security-web-angular/spring-security-web-angular-server/src/main/java/com/baeldung/springbootsecurityrest/basicauth/config/BasicAuthConfiguration.java index 504dbf63e3..5f4b82a191 100644 --- a/spring-security-modules/spring-security-web-angular/spring-security-web-angular-server/src/main/java/com/baeldung/springbootsecurityrest/basicauth/config/BasicAuthConfiguration.java +++ b/spring-security-modules/spring-security-web-angular/spring-security-web-angular-server/src/main/java/com/baeldung/springbootsecurityrest/basicauth/config/BasicAuthConfiguration.java @@ -1,5 +1,7 @@ package com.baeldung.springbootsecurityrest.basicauth.config; +import static org.springframework.security.config.Customizer.withDefaults; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; @@ -27,6 +29,7 @@ public class BasicAuthConfiguration { public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf() .disable() + .cors(withDefaults()) .authorizeRequests() .antMatchers(HttpMethod.OPTIONS, "/**") .permitAll() From 1b25127d899fb85b25a3f8b8eb03b110261284eb Mon Sep 17 00:00:00 2001 From: Kapil Khandelwal Date: Fri, 20 Jan 2023 00:24:58 +0530 Subject: [PATCH 18/34] LNX-453:- Prevent Jenkins build from failing when execute shell step fails (#13300) --- .../pipeline-prevent-build-failure-job | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 jenkins-modules/jenkins-jobs/prevent-build-failure-job/pipeline-prevent-build-failure-job diff --git a/jenkins-modules/jenkins-jobs/prevent-build-failure-job/pipeline-prevent-build-failure-job b/jenkins-modules/jenkins-jobs/prevent-build-failure-job/pipeline-prevent-build-failure-job new file mode 100644 index 0000000000..b143f31dc7 --- /dev/null +++ b/jenkins-modules/jenkins-jobs/prevent-build-failure-job/pipeline-prevent-build-failure-job @@ -0,0 +1,16 @@ +pipeline { + agent any + stages { + stage('tryCatch') { + steps { + script { + try { + sh 'test_script.sh' + } catch (e) { + echo "An error occurred: ${e}" + } + } + } + } + } +} From 305b369f5d1fd62c5b9cd5ee651ff9e60f1c9327 Mon Sep 17 00:00:00 2001 From: Iniubong LA Date: Thu, 19 Jan 2023 19:03:51 +0000 Subject: [PATCH 19/34] arthurshur@gmail.com (#13275) * Creating a deep vs shallow copy of an object in Java * Creating a deep vs shallow copy of an object in Java * Baeldung article converting number bases * Baeldung article converting number bases * edits made to Converting a Number from One Base to Another in Java * added braces to oneliners * added precondition to check input --- .../ConvertNumberBases.java | 52 +++++++++++-------- .../ConvertNumberBasesUnitTest.java | 12 +++++ 2 files changed, 42 insertions(+), 22 deletions(-) diff --git a/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/convertnumberbases/ConvertNumberBases.java b/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/convertnumberbases/ConvertNumberBases.java index 405504a965..09b880cd19 100644 --- a/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/convertnumberbases/ConvertNumberBases.java +++ b/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/convertnumberbases/ConvertNumberBases.java @@ -2,68 +2,76 @@ package com.baeldung.convertnumberbases; public class ConvertNumberBases { - public static String convertNumberToNewBase(String number, int base, int newBase){ + public static String convertNumberToNewBase(String number, int base, int newBase) { return Integer.toString(Integer.parseInt(number, base), newBase); } + public static String convertNumberToNewBaseCustom(String num, int base, int newBase) { int decimalNumber = convertFromAnyBaseToDecimal(num, base); - return convertFromDecimalToBaseX(decimalNumber, newBase); + String targetBase = ""; + try { + targetBase = convertFromDecimalToBaseX(decimalNumber, newBase); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } + return targetBase; } - public static String convertFromDecimalToBaseX(int num, int newBase) { + public static String convertFromDecimalToBaseX(int num, int newBase) throws IllegalArgumentException { + if ((newBase < 2 || newBase > 10) && newBase != 16) { + throw new IllegalArgumentException("New base must be from 2 - 10 or 16"); + } String result = ""; int remainder; while (num > 0) { remainder = num % newBase; if (newBase == 16) { - if (remainder == 10) + if (remainder == 10) { result += 'A'; - else if (remainder == 11) + } else if (remainder == 11) { result += 'B'; - else if (remainder == 12) + } else if (remainder == 12) { result += 'C'; - else if (remainder == 13) + } else if (remainder == 13) { result += 'D'; - else if (remainder == 14) + } else if (remainder == 14) { result += 'E'; - else if (remainder == 15) + } else if (remainder == 15) { result += 'F'; - else + } else { result += remainder; - } else + } + } else { result += remainder; - + } num /= newBase; } return new StringBuffer(result).reverse().toString(); } public static int convertFromAnyBaseToDecimal(String num, int base) { - - if (base < 2 || (base > 10 && base != 16)) + if (base < 2 || (base > 10 && base != 16)) { return -1; - + } int val = 0; int power = 1; - for (int i = num.length() - 1; i >= 0; i--) { int digit = charToDecimal(num.charAt(i)); - - if (digit < 0 || digit >= base) + if (digit < 0 || digit >= base) { return -1; - + } val += digit * power; power = power * base; } - return val; } public static int charToDecimal(char c) { - if (c >= '0' && c <= '9') + if (c >= '0' && c <= '9') { return (int) c - '0'; - else + } else { return (int) c - 'A' + 10; + } } } diff --git a/core-java-modules/core-java-lang-5/src/test/java/com/baeldung/convertnumberbases/ConvertNumberBasesUnitTest.java b/core-java-modules/core-java-lang-5/src/test/java/com/baeldung/convertnumberbases/ConvertNumberBasesUnitTest.java index 109e1da1b2..a666346b1a 100644 --- a/core-java-modules/core-java-lang-5/src/test/java/com/baeldung/convertnumberbases/ConvertNumberBasesUnitTest.java +++ b/core-java-modules/core-java-lang-5/src/test/java/com/baeldung/convertnumberbases/ConvertNumberBasesUnitTest.java @@ -1,5 +1,6 @@ package com.baeldung.convertnumberbases; +import static com.baeldung.convertnumberbases.ConvertNumberBases.convertFromDecimalToBaseX; import static com.baeldung.convertnumberbases.ConvertNumberBases.convertNumberToNewBase; import static com.baeldung.convertnumberbases.ConvertNumberBases.convertNumberToNewBaseCustom; import static org.junit.jupiter.api.Assertions.*; @@ -17,4 +18,15 @@ class ConvertNumberBasesUnitTest { assertEquals(convertNumberToNewBaseCustom("11001000", 2, 8), "310"); } + @Test + void whenInputIsOutOfRange_thenIllegalArgumentExceptionIsThrown() { + Exception exception = assertThrows(IllegalArgumentException.class, ()-> { + convertFromDecimalToBaseX(100, 12); + }); + String expectedMessage = "New base must be from 2 - 10 or 16"; + String actualMessage = exception.getMessage(); + + assertTrue(actualMessage.contains(expectedMessage)); + } + } \ No newline at end of file From cf5eeaa1765bf4b22f1593d7ba0d6b78360ac4ba Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Fri, 20 Jan 2023 07:39:27 +0530 Subject: [PATCH 20/34] Updated Readme to include info on building modules from the root (#13312) --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 1ae225b1f3..aecd561645 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,13 @@ Building a single module To build a specific module, run the command: `mvn clean install` in the module directory. +Building modules from the root of the repository +==================== +To build specific modules from the root of the repository, run the command: `mvn clean install --pl asm,atomikos -Pdefault-first` in the root directory. + +Here `asm` and `atomikos` are the modules that we want to build and `default-first` is the maven profile in which these modules are present. + + Running a Spring Boot module ==================== To run a Spring Boot module, run the command: `mvn spring-boot:run` in the module directory. From 0c3db032b8d9238dd8cb16dbf920b38ef6897e71 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 20 Jan 2023 16:11:34 +0800 Subject: [PATCH 21/34] Update README.md [skip ci] --- core-java-modules/core-java-collections-array-list/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-collections-array-list/README.md b/core-java-modules/core-java-collections-array-list/README.md index 094ae33c40..0bc090d635 100644 --- a/core-java-modules/core-java-collections-array-list/README.md +++ b/core-java-modules/core-java-collections-array-list/README.md @@ -10,3 +10,4 @@ This module contains articles about the Java ArrayList collection - [Removing an Element From an ArrayList](https://www.baeldung.com/java-arraylist-remove-element) - [The Capacity of an ArrayList vs the Size of an Array in Java](https://www.baeldung.com/java-list-capacity-array-size) - [Case-Insensitive Searching in ArrayList](https://www.baeldung.com/java-arraylist-case-insensitive-search) +- [Storing Data Triple in a List in Java](https://www.baeldung.com/java-list-storing-triple) From a8b953195db115646fbd0e6b74fd24994824bb9b Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 20 Jan 2023 16:17:17 +0800 Subject: [PATCH 22/34] Update README.md [skip ci] --- core-java-modules/core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java/README.md b/core-java-modules/core-java/README.md index 087c5d356e..0000962164 100644 --- a/core-java-modules/core-java/README.md +++ b/core-java-modules/core-java/README.md @@ -9,3 +9,4 @@ - [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle) - [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties) - [Illegal Character Compilation Error](https://www.baeldung.com/java-illegal-character-error) +- [Lambda Expression vs. Anonymous Inner Class](https://www.baeldung.com/java-lambdas-vs-anonymous-class) From a028f31823cebcef7826c14d55dca4418221cb8a Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 20 Jan 2023 16:21:36 +0800 Subject: [PATCH 23/34] Update README.md [skip ci] --- core-java-modules/core-java-streams-4/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-streams-4/README.md b/core-java-modules/core-java-streams-4/README.md index 187117d5d3..b210c2775a 100644 --- a/core-java-modules/core-java-streams-4/README.md +++ b/core-java-modules/core-java-streams-4/README.md @@ -5,3 +5,4 @@ - [Filter Java Stream to 1 and Only 1 Element](https://www.baeldung.com/java-filter-stream-unique-element) - [Java 8 Streams: Multiple Filters vs. Complex Condition](https://www.baeldung.com/java-streams-multiple-filters-vs-condition) - [Finding Max Date in List Using Streams](https://www.baeldung.com/java-max-date-list-streams) +- [Batch Processing of Stream Data in Java](https://www.baeldung.com/java-stream-batch-processing) From 9b0daac6406573b15d5a749f29745b63619a0bc4 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 20 Jan 2023 16:24:48 +0800 Subject: [PATCH 24/34] Update README.md [skip ci] --- core-java-modules/core-java-jvm-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-jvm-3/README.md b/core-java-modules/core-java-jvm-3/README.md index 5c694edaa0..0c8a325cf2 100644 --- a/core-java-modules/core-java-jvm-3/README.md +++ b/core-java-modules/core-java-jvm-3/README.md @@ -5,4 +5,5 @@ This module contains articles about working with the Java Virtual Machine (JVM). ### Relevant Articles: - [Difference Between Class.getResource() and ClassLoader.getResource()](https://www.baeldung.com/java-class-vs-classloader-getresource) +- [Compiling and Executing Code From a String in Java](https://www.baeldung.com/java-string-compile-execute-code) - More articles: [[<-- prev]](/core-java-modules/core-java-jvm-2) From 5e420e34e1be7b4086569f6fc966922f629a707c Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 20 Jan 2023 16:27:49 +0800 Subject: [PATCH 25/34] Update README.md [skip ci] --- core-java-modules/core-java-lang-oop-others/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-lang-oop-others/README.md b/core-java-modules/core-java-lang-oop-others/README.md index d3909c0014..b482669508 100644 --- a/core-java-modules/core-java-lang-oop-others/README.md +++ b/core-java-modules/core-java-lang-oop-others/README.md @@ -6,3 +6,4 @@ This module contains articles about Object Oriented Programming (OOP) in Java - [Object-Oriented-Programming Concepts in Java](https://www.baeldung.com/java-oop) - [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding) - [Pass-By-Value as a Parameter Passing Mechanism in Java](https://www.baeldung.com/java-pass-by-value-or-pass-by-reference) +- [Check If All the Variables of an Object Are Null](https://www.baeldung.com/java-check-all-variables-object-null) From b2731db3ef48af77243fcd97c4f01f0d3390e07c Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 20 Jan 2023 16:31:09 +0800 Subject: [PATCH 26/34] Update README.md [skip ci] --- core-java-modules/core-java-collections-array-list/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-collections-array-list/README.md b/core-java-modules/core-java-collections-array-list/README.md index 0bc090d635..53568ca98a 100644 --- a/core-java-modules/core-java-collections-array-list/README.md +++ b/core-java-modules/core-java-collections-array-list/README.md @@ -11,3 +11,4 @@ This module contains articles about the Java ArrayList collection - [The Capacity of an ArrayList vs the Size of an Array in Java](https://www.baeldung.com/java-list-capacity-array-size) - [Case-Insensitive Searching in ArrayList](https://www.baeldung.com/java-arraylist-case-insensitive-search) - [Storing Data Triple in a List in Java](https://www.baeldung.com/java-list-storing-triple) +- [Convert an ArrayList of Object to an ArrayList of String Elements](https://www.baeldung.com/java-object-list-to-strings) From 05601ae0febcf4249c61f17bf1a06d1cd45d3d67 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 20 Jan 2023 16:34:39 +0800 Subject: [PATCH 27/34] Update README.md [skip ci] --- persistence-modules/spring-data-jpa-repo-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-data-jpa-repo-2/README.md b/persistence-modules/spring-data-jpa-repo-2/README.md index f51e7135ae..6f19577606 100644 --- a/persistence-modules/spring-data-jpa-repo-2/README.md +++ b/persistence-modules/spring-data-jpa-repo-2/README.md @@ -7,4 +7,5 @@ - [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries) - [How to Access EntityManager with Spring Data](https://www.baeldung.com/spring-data-entitymanager) - [Difference Between JPA and Spring Data JPA](https://www.baeldung.com/spring-data-jpa-vs-jpa) +- [Differences Between Spring Data JPA findFirst() and findTop()](https://www.baeldung.com/spring-data-jpa-findfirst-vs-findtop) - More articles: [[<-- prev]](../spring-data-jpa-repo) From 63b714f00fcadc827f42d961da0bfa948466c274 Mon Sep 17 00:00:00 2001 From: Kumar Prabhash Anand Date: Fri, 20 Jan 2023 19:14:23 +0100 Subject: [PATCH 28/34] BAEL-6073 added scylladb code (#13307) * BAEL-6073 added scylladb code * BAEL-6073 renamed test class name --- persistence-modules/scylladb/pom.xml | 85 ++++++++++++++++++ .../scylladb/ScylladbApplication.java | 89 +++++++++++++++++++ .../com/baeldung/scylladb/model/User.java | 17 ++++ .../src/main/resources/application.yml | 3 + .../scylladb/ScyllaDBApplicationLiveTest.java | 68 ++++++++++++++ .../src/test/resources/application.yml | 3 + 6 files changed, 265 insertions(+) create mode 100644 persistence-modules/scylladb/pom.xml create mode 100644 persistence-modules/scylladb/src/main/java/com/baeldung/scylladb/ScylladbApplication.java create mode 100644 persistence-modules/scylladb/src/main/java/com/baeldung/scylladb/model/User.java create mode 100644 persistence-modules/scylladb/src/main/resources/application.yml create mode 100644 persistence-modules/scylladb/src/test/java/com/baeldung/scylladb/ScyllaDBApplicationLiveTest.java create mode 100644 persistence-modules/scylladb/src/test/resources/application.yml diff --git a/persistence-modules/scylladb/pom.xml b/persistence-modules/scylladb/pom.xml new file mode 100644 index 0000000000..e457c75d91 --- /dev/null +++ b/persistence-modules/scylladb/pom.xml @@ -0,0 +1,85 @@ + + + 4.0.0 + com.baeldung.examples.scylladb + scylladb + 0.0.1-SNAPSHOT + scylladb + Sample ScyllaDB Project + + 1.17.6 + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + org.springframework.boot + spring-boot-starter + + + com.scylladb + java-driver-core + 4.14.1.0 + + + com.scylladb + java-driver-query-builder + 4.14.1.0 + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.testcontainers + testcontainers + test + + + org.testcontainers + junit-jupiter + test + + + + + + org.testcontainers + testcontainers-bom + ${testcontainers.version} + pom + import + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/persistence-modules/scylladb/src/main/java/com/baeldung/scylladb/ScylladbApplication.java b/persistence-modules/scylladb/src/main/java/com/baeldung/scylladb/ScylladbApplication.java new file mode 100644 index 0000000000..3e6cea7ed2 --- /dev/null +++ b/persistence-modules/scylladb/src/main/java/com/baeldung/scylladb/ScylladbApplication.java @@ -0,0 +1,89 @@ +package com.baeldung.scylladb; + +import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.insertInto; +import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.literal; +import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.selectFrom; +import static com.datastax.oss.driver.api.querybuilder.SchemaBuilder.createKeyspace; +import static com.datastax.oss.driver.api.querybuilder.SchemaBuilder.createTable; + +import java.util.ArrayList; +import java.util.List; + +import com.baeldung.scylladb.model.User; +import com.datastax.oss.driver.api.core.CqlSession; +import com.datastax.oss.driver.api.core.cql.ResultSet; +import com.datastax.oss.driver.api.core.cql.Row; +import com.datastax.oss.driver.api.core.cql.SimpleStatement; +import com.datastax.oss.driver.api.core.type.DataTypes; +import com.datastax.oss.driver.api.querybuilder.insert.InsertInto; +import com.datastax.oss.driver.api.querybuilder.schema.CreateKeyspaceStart; +import com.datastax.oss.driver.api.querybuilder.schema.CreateTableStart; +import com.datastax.oss.driver.api.querybuilder.select.Select; + +public class ScylladbApplication { + + private String keySpaceName; + private String tableName; + + public ScylladbApplication(String keySpaceName, String tableName) { + this.keySpaceName = keySpaceName; + this.tableName = tableName; + CreateKeyspaceStart createKeyspace = createKeyspace(keySpaceName); + SimpleStatement keypaceStatement = createKeyspace.ifNotExists() + .withSimpleStrategy(3) + .build(); + + CreateTableStart createTable = createTable(keySpaceName, tableName); + SimpleStatement tableStatement = createTable.ifNotExists() + .withPartitionKey("id", DataTypes.BIGINT) + .withColumn("name", DataTypes.TEXT) + .build(); + + try (CqlSession session = CqlSession.builder().build()) { + ResultSet rs = session.execute(keypaceStatement); + if (null == rs.getExecutionInfo().getErrors() || rs.getExecutionInfo().getErrors().isEmpty()) { + rs = session.execute(tableStatement); + } + } + } + + public List getAllUserNames() { + List userNames = new ArrayList<>(); + try (CqlSession session = CqlSession.builder().build()) { + String query = String.format("select * from %s.%s",keySpaceName,tableName); + ResultSet rs = session.execute(query); + for (Row r : rs.all()) + userNames.add(r.getString("name")); + } + return userNames; + } + + public List getUsersByUserName(String userName) { + List userList = new ArrayList<>(); + try (CqlSession session = CqlSession.builder().build()) { + Select query = selectFrom(keySpaceName, tableName).all() + .whereColumn("name") + .isEqualTo(literal(userName)) + .allowFiltering(); + SimpleStatement statement = query.build(); + ResultSet rs = session.execute(statement); + for (Row r : rs) + userList.add(new User(r.getLong("id"), r.getString("name"))); + } + return userList; + } + + public boolean addNewUser(User user) { + boolean response = false; + try (CqlSession session = CqlSession.builder().build()) { + InsertInto insert = insertInto(keySpaceName, tableName); + SimpleStatement statement = insert.value("id", literal(user.getId())) + .value("name", literal(user.getName())) + .build(); + ResultSet rs = session.execute(statement); + response = null == rs.getExecutionInfo().getErrors() || rs.getExecutionInfo().getErrors().isEmpty(); + } + return response; + } + +} diff --git a/persistence-modules/scylladb/src/main/java/com/baeldung/scylladb/model/User.java b/persistence-modules/scylladb/src/main/java/com/baeldung/scylladb/model/User.java new file mode 100644 index 0000000000..28d60112b9 --- /dev/null +++ b/persistence-modules/scylladb/src/main/java/com/baeldung/scylladb/model/User.java @@ -0,0 +1,17 @@ +package com.baeldung.scylladb.model; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class User { + + private long id; + + private String name; +} diff --git a/persistence-modules/scylladb/src/main/resources/application.yml b/persistence-modules/scylladb/src/main/resources/application.yml new file mode 100644 index 0000000000..3a4abad3dd --- /dev/null +++ b/persistence-modules/scylladb/src/main/resources/application.yml @@ -0,0 +1,3 @@ +datastax-java-driver: + basic: + contact-points: 127.0.0.1:9042 \ No newline at end of file diff --git a/persistence-modules/scylladb/src/test/java/com/baeldung/scylladb/ScyllaDBApplicationLiveTest.java b/persistence-modules/scylladb/src/test/java/com/baeldung/scylladb/ScyllaDBApplicationLiveTest.java new file mode 100644 index 0000000000..4e3cb00a41 --- /dev/null +++ b/persistence-modules/scylladb/src/test/java/com/baeldung/scylladb/ScyllaDBApplicationLiveTest.java @@ -0,0 +1,68 @@ +package com.baeldung.scylladb; + +import static org.junit.Assert.assertEquals; + +import java.util.List; +import java.util.function.Consumer; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; + +import com.baeldung.scylladb.model.User; +import com.github.dockerjava.api.command.CreateContainerCmd; +import com.github.dockerjava.api.model.ExposedPort; +import com.github.dockerjava.api.model.PortBinding; +import com.github.dockerjava.api.model.Ports; + +@Testcontainers +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class ScyllaDBApplicationLiveTest { + + private static final String IMAGE_NAME = "scylladb/scylla"; + private static final int hostPort = 9042; + private static final int containerExposedPort = 9042; + private static Consumer cmd = e -> e.withPortBindings(new PortBinding(Ports.Binding.bindPort(hostPort), + new ExposedPort(containerExposedPort))); + + @Container + private static final GenericContainer scyllaDbContainer = new GenericContainer(DockerImageName.parse(IMAGE_NAME)) + .withExposedPorts(containerExposedPort) + .withCreateContainerCmdModifier(cmd); + + private ScylladbApplication scylladbApplication; + + @BeforeAll + void setUp() { + scylladbApplication = new ScylladbApplication("baeldung", "User"); + } + + @Test + public void givenKeySpaceAndTable_whenInsertData_thenShouldBeAbleToFindData() { + User user = new User(10, "John"); + scylladbApplication.addNewUser(user); + + List userList = scylladbApplication.getUsersByUserName("John"); + assertEquals(1, userList.size()); + assertEquals("John", userList.get(0).getName()); + assertEquals(10, userList.get(0).getId()); + + } + + @Test + public void givenKeySpaceAndTable_whenInsertData_thenRowCountIncreases() { + int initialCount = scylladbApplication.getAllUserNames().size(); + User user = new User(11, "Doe"); + scylladbApplication.addNewUser(user); + + int expectedCount = initialCount+1; + int updatedCount = scylladbApplication.getAllUserNames().size(); + assertEquals(expectedCount, updatedCount); + + } + +} diff --git a/persistence-modules/scylladb/src/test/resources/application.yml b/persistence-modules/scylladb/src/test/resources/application.yml new file mode 100644 index 0000000000..3a4abad3dd --- /dev/null +++ b/persistence-modules/scylladb/src/test/resources/application.yml @@ -0,0 +1,3 @@ +datastax-java-driver: + basic: + contact-points: 127.0.0.1:9042 \ No newline at end of file From 54a6c6c61d18a8f2cdc8b3cb6c0faf0346c3eb05 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 21 Jan 2023 15:50:19 +0530 Subject: [PATCH 29/34] fixed backlink --- axon/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/axon/README.md b/axon/README.md index 5db38a7c94..2dad554110 100644 --- a/axon/README.md +++ b/axon/README.md @@ -20,4 +20,4 @@ Two scripts are included to easily start middleware using Docker matching the pr - [Multi-Entity Aggregates in Axon](https://www.baeldung.com/java-axon-multi-entity-aggregates) - [Snapshotting Aggregates in Axon](https://www.baeldung.com/axon-snapshotting-aggregates) - [Dispatching Queries in Axon Framework](https://www.baeldung.com/axon-query-dispatching) -- [Persisting the Query Model](https://www.baeldung.com/persisting-the-query-model) +- [Persisting the Query Model](https://www.baeldung.com/axon-persisting-query-model) From 5835814337c37dca43df1da1c50a615486e45b15 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 21 Jan 2023 15:52:19 +0530 Subject: [PATCH 30/34] backlink fixed --- jmeter/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jmeter/README.md b/jmeter/README.md index e53f411cdb..76d329342d 100644 --- a/jmeter/README.md +++ b/jmeter/README.md @@ -54,4 +54,4 @@ Enjoy it :) - [Configure Jenkins to Run and Show JMeter Tests](https://www.baeldung.com/ops/jenkins-and-jmeter) - [Write Extracted Data to a File Using JMeter](https://www.baeldung.com/jmeter-write-to-file) - [Basic Authentication in JMeter](https://www.baeldung.com/jmeter-basic-auth) -- [JMeter: Latency vs. Load Time](https://www.baeldung.com/java-jmeter-latency-vs-load-time/) +- [JMeter: Latency vs. Load Time](https://www.baeldung.com/java-jmeter-latency-vs-load-time) From 3b770c4deeeffbd8dbd2a00338c6086f4c3e2fc2 Mon Sep 17 00:00:00 2001 From: Azhwani <13301425+azhwani@users.noreply.github.com> Date: Sat, 21 Jan 2023 16:16:18 +0100 Subject: [PATCH 31/34] BAEL-6044: Fix the IllegalArgumentException: No enum const class (#13171) --- .../exception/noenumconst/Priority.java | 13 +++++++ .../exception/noenumconst/PriorityUtils.java | 21 +++++++++++ .../noenumconst/PriorityUtilsUnitTest.java | 36 +++++++++++++++++++ 3 files changed, 70 insertions(+) create mode 100644 core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/noenumconst/Priority.java create mode 100644 core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/noenumconst/PriorityUtils.java create mode 100644 core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/noenumconst/PriorityUtilsUnitTest.java diff --git a/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/noenumconst/Priority.java b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/noenumconst/Priority.java new file mode 100644 index 0000000000..ff9591b1e0 --- /dev/null +++ b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/noenumconst/Priority.java @@ -0,0 +1,13 @@ +package com.baeldung.exception.noenumconst; + +public enum Priority { + + HIGH("High"), MEDIUM("Medium"), LOW("Low"); + + private String name; + + Priority(String name) { + this.name = name; + } + +} diff --git a/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/noenumconst/PriorityUtils.java b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/noenumconst/PriorityUtils.java new file mode 100644 index 0000000000..8d7004bf39 --- /dev/null +++ b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/noenumconst/PriorityUtils.java @@ -0,0 +1,21 @@ +package com.baeldung.exception.noenumconst; + +public class PriorityUtils { + + public static Priority getByName(String name) { + return Priority.valueOf(name); + } + + public static Priority getByUpperCaseName(String name) { + if (name == null || name.isEmpty()) { + return null; + } + + return Priority.valueOf(name.toUpperCase()); + } + + public static void main(String[] args) { + System.out.println(getByName("Low")); + } + +} diff --git a/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/noenumconst/PriorityUtilsUnitTest.java b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/noenumconst/PriorityUtilsUnitTest.java new file mode 100644 index 0000000000..1ff9c49015 --- /dev/null +++ b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/noenumconst/PriorityUtilsUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.exception.noenumconst; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class PriorityUtilsUnitTest { + + @Test + void givenCustomName_whenUsingGetByName_thenThrowIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> PriorityUtils.getByName("Low")); + } + + @Test + void givenCustomName_whenUsingGetByUpperCaseName_thenReturnEnumConstant() { + assertEquals(Priority.HIGH, PriorityUtils.getByUpperCaseName("High")); + } + + @Test + void givenInvalidCustomName_whenUsingGetByUpperCaseName_thenThrowIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> PriorityUtils.getByUpperCaseName("invalid")); + } + + @Test + void givenEmptyName_whenUsingGetByUpperCaseName_thenReturnNull() { + assertNull(PriorityUtils.getByUpperCaseName("")); + } + + @Test + void givenNull_whenUsingGetByUpperCaseName_thenReturnNull() { + assertNull(PriorityUtils.getByUpperCaseName(null)); + } + +} From fa6b78233c56d6f6f1d1d33024f5bf0ed1cea958 Mon Sep 17 00:00:00 2001 From: Vali Tuguran Date: Sun, 22 Jan 2023 05:39:34 +0100 Subject: [PATCH 32/34] BAEL-6040 Add Java List tests. (#13255) * BAEL-6040 Add list interface example. * BAEL-6040 Updated list iterator. * BAEL-6040 Removed logger import. * BAEL-6040 Added List interface tests. * BAEL-6040 Update tests success names. * BAEL-6040 Small names refactoring. * BAEL-6040 Add new core-java-collections-5 module. * BAEL-6040 Create module core-java-collections-list-5. * BAEL-6040 Create module core-java-collections-list-5. --- .../core-java-collections-list-5/README.md | 5 + .../core-java-collections-list-5/pom.xml | 35 +++++ .../com/baeldung/java/list/ListUnitTest.java | 126 ++++++++++++++++++ 3 files changed, 166 insertions(+) create mode 100644 core-java-modules/core-java-collections-list-5/README.md create mode 100644 core-java-modules/core-java-collections-list-5/pom.xml create mode 100644 core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/list/ListUnitTest.java diff --git a/core-java-modules/core-java-collections-list-5/README.md b/core-java-modules/core-java-collections-list-5/README.md new file mode 100644 index 0000000000..4b7fbf8669 --- /dev/null +++ b/core-java-modules/core-java-collections-list-5/README.md @@ -0,0 +1,5 @@ +## Core Java Collections List (Part 5) + +This module contains articles about the Java List collection + +### Relevant Articles: \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-5/pom.xml b/core-java-modules/core-java-collections-list-5/pom.xml new file mode 100644 index 0000000000..0807f7612c --- /dev/null +++ b/core-java-modules/core-java-collections-list-5/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + core-java-collections-list-5 + 0.1.0-SNAPSHOT + core-java-collections-list-5 + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + + + commons-lang + commons-lang + ${commons-lang.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + + 2.2 + 3.12.0 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/list/ListUnitTest.java b/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/list/ListUnitTest.java new file mode 100644 index 0000000000..2222bc5a6f --- /dev/null +++ b/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/list/ListUnitTest.java @@ -0,0 +1,126 @@ +package com.baeldung.java.list; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; + +import org.junit.Test; + +public class ListUnitTest { + + @Test + public void givenAFruitList_whenAddNewFruit_thenFruitIsAdded(){ + List fruits = new ArrayList<>(); + assertEquals("Unexpected number of fruits in the list, should have been 0", 0, fruits.size()); + + fruits.add("Apple"); + assertEquals("Unexpected number of fruits in the list, should have been 1", 1, fruits.size()); + } + + @Test + public void givenAFruitList_whenContainsFruit_thenFruitIsInTheList(){ + List fruits = new ArrayList<>(); + + fruits.add("Apple"); + assertTrue("Apple should be in the fruit list", fruits.contains("Apple")); + assertFalse("Banana should not be in the fruit list", fruits.contains("Banana")); + } + + @Test + public void givenAnEmptyFruitList_whenEmptyCheck_thenListIsEmpty(){ + List fruits = new ArrayList<>(); + assertTrue("Fruit list should be empty", fruits.isEmpty()); + + fruits.add("Apple"); + assertFalse("Fruit list should not be empty", fruits.isEmpty()); + } + + @Test + public void givenAFruitList_whenIterateOverIt_thenFruitsAreInOrder(){ + List fruits = new ArrayList<>(); + + fruits.add("Apple"); // fruit at index 0 + fruits.add("Orange");// fruit at index 1 + fruits.add("Banana");// fruit at index 2 + int index = 0; + for (Iterator it = fruits.listIterator(); it.hasNext(); ) { + String fruit = it.next(); + assertEquals("Fruits should be in order", fruits.get(index++), fruit); + } + } + + @Test + public void givenAFruitList_whenRemoveFruit_thenFruitIsRemoved(){ + List fruits = new ArrayList<>(); + + fruits.add("Apple"); + fruits.add("Orange"); + assertEquals("Unexpected number of fruits in the list, should have been 2", 2, fruits.size()); + + fruits.remove("Apple"); + assertEquals("Unexpected number of fruits in the list, should have been 1", 1, fruits.size()); + } + + @Test + public void givenAFruitList_whenSetFruit_thenFruitIsUpdated(){ + List fruits = new ArrayList<>(); + + fruits.add("Apple"); + fruits.add("Orange"); + + fruits.set(0, "Banana"); + assertEquals("Fruit at index 0 should be Banana", "Banana", fruits.get(0)); + } + + @Test + public void givenAFruitList_whenSort_thenFruitsAreSorted(){ + List fruits = new ArrayList<>(); + + fruits.add("Apple"); + fruits.add("Orange"); + fruits.add("Banana"); + + fruits.sort(Comparator.naturalOrder()); + + assertEquals("Fruit at index 0 should be Apple", "Apple", fruits.get(0)); + assertEquals("Fruit at index 1 should be Banana", "Banana", fruits.get(1)); + assertEquals("Fruit at index 2 should be Orange", "Orange", fruits.get(2)); + } + + @Test + public void givenAFruitList_whenSublist_thenWeGetASublist(){ + List fruits = new ArrayList<>(); + + fruits.add("Apple"); + fruits.add("Orange"); + fruits.add("Banana"); + + List fruitsSublist = fruits.subList(0, 2); + assertEquals("Unexpected number of fruits in the sublist, should have been 2", 2, fruitsSublist.size()); + + assertEquals("Fruit at index 0 should be Apple", "Apple", fruitsSublist.get(0)); + assertEquals("Fruit at index 1 should be Orange", "Orange", fruitsSublist.get(1)); + } + + @Test + public void givenAFruitList_whenToArray_thenWeGetAnArray(){ + List fruits = new ArrayList<>(); + + fruits.add("Apple"); + fruits.add("Orange"); + fruits.add("Banana"); + + String[] fruitsArray = fruits.toArray(new String[0]); + assertEquals("Unexpected number of fruits in the array, should have been 3", 3, fruitsArray.length); + + assertEquals("Fruit at index 0 should be Apple", "Apple", fruitsArray[0]); + assertEquals("Fruit at index 1 should be Orange", "Orange", fruitsArray[1]); + assertEquals("Fruit at index 2 should be Banana", "Banana", fruitsArray[2]); + } + +} From b958c3fdcb28c5ff2a75d1e15740a7f7cdcfafb0 Mon Sep 17 00:00:00 2001 From: brokenhardisk Date: Sun, 22 Jan 2023 12:48:56 +0100 Subject: [PATCH 33/34] BAEL-5942 Code changes (#13147) * BAEL-5942 Code changes * BAEL-5942 Code changes * BAEL-5942 Code updates from Review * BAEL-5942 Code updates from Review * BAEL-5942 Code updates from Review * BAEL-5942 Code updates from Review * BAEL-5942 Code updates from Review * BAEL-5942 Code updates from Review * BAEL-5942 Test updates from Review * BAEL-5942 Test updates from Review * BAEL-5942 Test updates from Review --- spring-web-modules/pom.xml | 1 + spring-web-modules/spring-mvc-file/.gitignore | 9 +++ spring-web-modules/spring-mvc-file/README.md | 9 +++ spring-web-modules/spring-mvc-file/pom.xml | 50 ++++++++++++++++ .../main/java/com/baeldung/Application.java | 11 ++++ .../baeldung/file/CustomMultipartFile.java | 60 +++++++++++++++++++ .../file/CustomMultipartFileUnitTest.java | 49 +++++++++++++++ 7 files changed, 189 insertions(+) create mode 100644 spring-web-modules/spring-mvc-file/.gitignore create mode 100644 spring-web-modules/spring-mvc-file/README.md create mode 100644 spring-web-modules/spring-mvc-file/pom.xml create mode 100644 spring-web-modules/spring-mvc-file/src/main/java/com/baeldung/Application.java create mode 100644 spring-web-modules/spring-mvc-file/src/main/java/com/baeldung/file/CustomMultipartFile.java create mode 100644 spring-web-modules/spring-mvc-file/src/test/java/com/baeldung/file/CustomMultipartFileUnitTest.java diff --git a/spring-web-modules/pom.xml b/spring-web-modules/pom.xml index 047dbaaad0..a9970e85c0 100644 --- a/spring-web-modules/pom.xml +++ b/spring-web-modules/pom.xml @@ -23,6 +23,7 @@ spring-mvc-basics-4 spring-mvc-basics-5 spring-mvc-crash + spring-mvc-file spring-mvc-forms-jsp spring-mvc-forms-thymeleaf spring-mvc-java diff --git a/spring-web-modules/spring-mvc-file/.gitignore b/spring-web-modules/spring-mvc-file/.gitignore new file mode 100644 index 0000000000..da9ec604ff --- /dev/null +++ b/spring-web-modules/spring-mvc-file/.gitignore @@ -0,0 +1,9 @@ +*.class + +#folders# +/target + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-file/README.md b/spring-web-modules/spring-mvc-file/README.md new file mode 100644 index 0000000000..c1622f80c2 --- /dev/null +++ b/spring-web-modules/spring-mvc-file/README.md @@ -0,0 +1,9 @@ +## Spring MVC File + + + +### The Course + + +### Relevant Articles: + diff --git a/spring-web-modules/spring-mvc-file/pom.xml b/spring-web-modules/spring-mvc-file/pom.xml new file mode 100644 index 0000000000..c6b063c785 --- /dev/null +++ b/spring-web-modules/spring-mvc-file/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + spring-mvc-file + 0.1-SNAPSHOT + spring-mvc-file + jar + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + commons-io + commons-io + ${commons-io.version} + + + + + + spring-mvc-file + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.Application + JAR + + + + + + \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-file/src/main/java/com/baeldung/Application.java b/spring-web-modules/spring-mvc-file/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..d58049fb35 --- /dev/null +++ b/spring-web-modules/spring-mvc-file/src/main/java/com/baeldung/Application.java @@ -0,0 +1,11 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-web-modules/spring-mvc-file/src/main/java/com/baeldung/file/CustomMultipartFile.java b/spring-web-modules/spring-mvc-file/src/main/java/com/baeldung/file/CustomMultipartFile.java new file mode 100644 index 0000000000..c68729588f --- /dev/null +++ b/spring-web-modules/spring-mvc-file/src/main/java/com/baeldung/file/CustomMultipartFile.java @@ -0,0 +1,60 @@ +package com.baeldung.file; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.springframework.web.multipart.MultipartFile; + +public class CustomMultipartFile implements MultipartFile { + private byte[] input; + + public CustomMultipartFile(byte[] input) { + this.input = input; + } + + @Override + public String getName() { + return null; + } + + @Override + public String getOriginalFilename() { + return null; + } + + @Override + public String getContentType() { + return null; + } + + @Override + public boolean isEmpty() { + return input == null || input.length == 0; + } + + @Override + public long getSize() { + return input.length; + } + + @Override + public byte[] getBytes() throws IOException { + return input; + } + + @Override + public InputStream getInputStream() throws IOException { + return new ByteArrayInputStream(input); + } + + @Override + public void transferTo(File destination) throws IOException, IllegalStateException { + try(FileOutputStream fos = new FileOutputStream(destination)) { + fos.write(input); + } + } + +} diff --git a/spring-web-modules/spring-mvc-file/src/test/java/com/baeldung/file/CustomMultipartFileUnitTest.java b/spring-web-modules/spring-mvc-file/src/test/java/com/baeldung/file/CustomMultipartFileUnitTest.java new file mode 100644 index 0000000000..1aa07766ca --- /dev/null +++ b/spring-web-modules/spring-mvc-file/src/test/java/com/baeldung/file/CustomMultipartFileUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.file; + +import java.io.IOException; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockMultipartFile; + +class CustomMultipartFileUnitTest { + + @Test + void whenProvidingByteArray_thenMultipartFileCreated() throws IOException { + byte[] inputArray = "Test String".getBytes(); + CustomMultipartFile customMultipartFile = new CustomMultipartFile(inputArray); + Assertions.assertFalse(customMultipartFile.isEmpty()); + Assertions.assertArrayEquals(inputArray, customMultipartFile.getBytes()); + Assertions.assertEquals(inputArray.length, customMultipartFile.getSize()); + } + + @Test + void whenProvidingEmptyByteArray_thenMockMultipartFileIsEmpty() throws IOException { + byte[] inputArray = "".getBytes(); + MockMultipartFile mockMultipartFile = new MockMultipartFile("tempFileName", inputArray); + Assertions.assertTrue(mockMultipartFile.isEmpty()); + } + + @Test + void whenProvidingNullByteArray_thenMockMultipartFileIsEmpty() throws IOException { + byte[] inputArray = null; + MockMultipartFile mockMultipartFile = new MockMultipartFile("tempFileName", inputArray); + Assertions.assertTrue(mockMultipartFile.isEmpty()); + } + + @Test + void whenProvidingByteArray_thenMultipartFileInputSizeMatches() throws IOException { + byte[] inputArray = "Testing String".getBytes(); + CustomMultipartFile customMultipartFile = new CustomMultipartFile(inputArray); + Assertions.assertEquals(inputArray.length, customMultipartFile.getSize()); + } + + @Test + void whenProvidingByteArray_thenMockMultipartFileCreated() throws IOException { + byte[] inputArray = "Test String".getBytes(); + MockMultipartFile mockMultipartFile = new MockMultipartFile("tempFileName", inputArray); + Assertions.assertFalse(mockMultipartFile.isEmpty()); + Assertions.assertArrayEquals(inputArray, mockMultipartFile.getBytes()); + Assertions.assertEquals(inputArray.length, mockMultipartFile.getSize()); + } +} From e6685e5dac69dbd136554835caaa78d67ae590ff Mon Sep 17 00:00:00 2001 From: jsgrah-spring Date: Mon, 23 Jan 2023 09:22:37 +0100 Subject: [PATCH 34/34] Fix The PR that is merged here is causing some other integration tests to fail in the same module (#13331) * JAVA-14459, GitHub Issue: Reactive WebSocket App example no longer works. * JAVA-14459, Move spring5 reactive webflux filters to its own module. Co-authored-by: jogra --- spring-reactive-modules/pom.xml | 1 + .../spring-5-reactive-filters/.gitignore | 12 ++++ .../spring-5-reactive-filters/README.md | 15 ++++ .../spring-5-reactive-filters/pom.xml | 68 +++++++++++++++++++ .../Spring5ReactiveFiltersApplication.java | 13 ++++ .../filters/ExampleHandlerFilterFunction.java | 0 .../reactive/filters/ExampleWebFilter.java | 0 .../reactive/filters/PlayerHandler.java | 0 .../reactive/filters/PlayerRouter.java | 0 .../reactive/filters/UserController.java | 0 .../src/main/resources/application.properties | 1 + .../src/main/resources/logback.xml | 13 ++++ .../java/com/baeldung/SpringContextTest.java | 17 +++++ .../filters/PlayerHandlerIntegrationTest.java | 0 .../UserControllerIntegrationTest.java | 0 15 files changed, 140 insertions(+) create mode 100644 spring-reactive-modules/spring-5-reactive-filters/.gitignore create mode 100644 spring-reactive-modules/spring-5-reactive-filters/README.md create mode 100644 spring-reactive-modules/spring-5-reactive-filters/pom.xml create mode 100644 spring-reactive-modules/spring-5-reactive-filters/src/main/java/com/baeldung/reactive/Spring5ReactiveFiltersApplication.java rename spring-reactive-modules/{spring-5-reactive => spring-5-reactive-filters}/src/main/java/com/baeldung/reactive/filters/ExampleHandlerFilterFunction.java (100%) rename spring-reactive-modules/{spring-5-reactive => spring-5-reactive-filters}/src/main/java/com/baeldung/reactive/filters/ExampleWebFilter.java (100%) rename spring-reactive-modules/{spring-5-reactive => spring-5-reactive-filters}/src/main/java/com/baeldung/reactive/filters/PlayerHandler.java (100%) rename spring-reactive-modules/{spring-5-reactive => spring-5-reactive-filters}/src/main/java/com/baeldung/reactive/filters/PlayerRouter.java (100%) rename spring-reactive-modules/{spring-5-reactive => spring-5-reactive-filters}/src/main/java/com/baeldung/reactive/filters/UserController.java (100%) create mode 100644 spring-reactive-modules/spring-5-reactive-filters/src/main/resources/application.properties create mode 100644 spring-reactive-modules/spring-5-reactive-filters/src/main/resources/logback.xml create mode 100644 spring-reactive-modules/spring-5-reactive-filters/src/test/java/com/baeldung/SpringContextTest.java rename spring-reactive-modules/{spring-5-reactive => spring-5-reactive-filters}/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java (100%) rename spring-reactive-modules/{spring-5-reactive => spring-5-reactive-filters}/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java (100%) diff --git a/spring-reactive-modules/pom.xml b/spring-reactive-modules/pom.xml index 0d9ea6bf5d..c8c9c84394 100644 --- a/spring-reactive-modules/pom.xml +++ b/spring-reactive-modules/pom.xml @@ -23,6 +23,7 @@ spring-5-reactive-3 spring-5-reactive-client spring-5-reactive-client-2 + spring-5-reactive-filters spring-5-reactive-oauth spring-5-reactive-security spring-reactive diff --git a/spring-reactive-modules/spring-5-reactive-filters/.gitignore b/spring-reactive-modules/spring-5-reactive-filters/.gitignore new file mode 100644 index 0000000000..dec013dfa4 --- /dev/null +++ b/spring-reactive-modules/spring-5-reactive-filters/.gitignore @@ -0,0 +1,12 @@ +#folders# +.idea +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/spring-reactive-modules/spring-5-reactive-filters/README.md b/spring-reactive-modules/spring-5-reactive-filters/README.md new file mode 100644 index 0000000000..aa8d2800e2 --- /dev/null +++ b/spring-reactive-modules/spring-5-reactive-filters/README.md @@ -0,0 +1,15 @@ +## Spring 5 Reactive Project + +This module contains articles about reactive Spring 5 + +### The Course +The "REST With Spring" Classes: https://bit.ly/restwithspring + +### Relevant Articles + +- [Exploring the Spring 5 WebFlux URL Matching](https://www.baeldung.com/spring-5-mvc-url-matching) +- [Reactive WebSockets with Spring 5](https://www.baeldung.com/spring-5-reactive-websockets) +- [Spring WebFlux Filters](https://www.baeldung.com/spring-webflux-filters) +- [How to Set a Header on a Response with Spring 5](https://www.baeldung.com/spring-response-header) +- [A Guide to Spring Session Reactive Support: WebSession](https://www.baeldung.com/spring-session-reactive) +- More articles: [[next -->]](../spring-5-reactive-2) diff --git a/spring-reactive-modules/spring-5-reactive-filters/pom.xml b/spring-reactive-modules/spring-5-reactive-filters/pom.xml new file mode 100644 index 0000000000..c9503d631a --- /dev/null +++ b/spring-reactive-modules/spring-5-reactive-filters/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + spring-5-reactive-filters + 0.0.1-SNAPSHOT + spring-5-reactive-filters + jar + spring 5 sample project about new features + + + com.baeldung.spring.reactive + spring-reactive-modules + 1.0.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter-webflux + + + + + org.springframework.boot + spring-boot-devtools + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + io.projectreactor + reactor-test + test + + + + + io.netty + netty-all + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.reactive.Spring5ReactiveFiltersApplication + JAR + + + + + + \ No newline at end of file diff --git a/spring-reactive-modules/spring-5-reactive-filters/src/main/java/com/baeldung/reactive/Spring5ReactiveFiltersApplication.java b/spring-reactive-modules/spring-5-reactive-filters/src/main/java/com/baeldung/reactive/Spring5ReactiveFiltersApplication.java new file mode 100644 index 0000000000..41f95a274c --- /dev/null +++ b/spring-reactive-modules/spring-5-reactive-filters/src/main/java/com/baeldung/reactive/Spring5ReactiveFiltersApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.reactive; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Spring5ReactiveFiltersApplication{ + + public static void main(String[] args) { + SpringApplication.run(Spring5ReactiveFiltersApplication.class, args); + } + +} diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/ExampleHandlerFilterFunction.java b/spring-reactive-modules/spring-5-reactive-filters/src/main/java/com/baeldung/reactive/filters/ExampleHandlerFilterFunction.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/ExampleHandlerFilterFunction.java rename to spring-reactive-modules/spring-5-reactive-filters/src/main/java/com/baeldung/reactive/filters/ExampleHandlerFilterFunction.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/ExampleWebFilter.java b/spring-reactive-modules/spring-5-reactive-filters/src/main/java/com/baeldung/reactive/filters/ExampleWebFilter.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/ExampleWebFilter.java rename to spring-reactive-modules/spring-5-reactive-filters/src/main/java/com/baeldung/reactive/filters/ExampleWebFilter.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/PlayerHandler.java b/spring-reactive-modules/spring-5-reactive-filters/src/main/java/com/baeldung/reactive/filters/PlayerHandler.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/PlayerHandler.java rename to spring-reactive-modules/spring-5-reactive-filters/src/main/java/com/baeldung/reactive/filters/PlayerHandler.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/PlayerRouter.java b/spring-reactive-modules/spring-5-reactive-filters/src/main/java/com/baeldung/reactive/filters/PlayerRouter.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/PlayerRouter.java rename to spring-reactive-modules/spring-5-reactive-filters/src/main/java/com/baeldung/reactive/filters/PlayerRouter.java diff --git a/spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/UserController.java b/spring-reactive-modules/spring-5-reactive-filters/src/main/java/com/baeldung/reactive/filters/UserController.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/main/java/com/baeldung/reactive/filters/UserController.java rename to spring-reactive-modules/spring-5-reactive-filters/src/main/java/com/baeldung/reactive/filters/UserController.java diff --git a/spring-reactive-modules/spring-5-reactive-filters/src/main/resources/application.properties b/spring-reactive-modules/spring-5-reactive-filters/src/main/resources/application.properties new file mode 100644 index 0000000000..4b49e8e8a2 --- /dev/null +++ b/spring-reactive-modules/spring-5-reactive-filters/src/main/resources/application.properties @@ -0,0 +1 @@ +logging.level.root=INFO \ No newline at end of file diff --git a/spring-reactive-modules/spring-5-reactive-filters/src/main/resources/logback.xml b/spring-reactive-modules/spring-5-reactive-filters/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-reactive-modules/spring-5-reactive-filters/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-reactive-modules/spring-5-reactive-filters/src/test/java/com/baeldung/SpringContextTest.java b/spring-reactive-modules/spring-5-reactive-filters/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..3e026ef45f --- /dev/null +++ b/spring-reactive-modules/spring-5-reactive-filters/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.reactive.Spring5ReactiveFiltersApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Spring5ReactiveFiltersApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-reactive-modules/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java b/spring-reactive-modules/spring-5-reactive-filters/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java rename to spring-reactive-modules/spring-5-reactive-filters/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java diff --git a/spring-reactive-modules/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java b/spring-reactive-modules/spring-5-reactive-filters/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java similarity index 100% rename from spring-reactive-modules/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java rename to spring-reactive-modules/spring-5-reactive-filters/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java