From 2f5696c8632803976bddb417ceb87e5152074598 Mon Sep 17 00:00:00 2001 From: PJ Fanning Date: Thu, 22 Dec 2022 23:13:57 +0100 Subject: [PATCH 01/43] need to handle trailing tokens see https://github.com/FasterXML/jackson/discussions/143#discussioncomment-4479800 --- .../java/com/baeldung/jsonvalidation/JacksonValidator.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/json-modules/json-2/src/main/java/com/baeldung/jsonvalidation/JacksonValidator.java b/json-modules/json-2/src/main/java/com/baeldung/jsonvalidation/JacksonValidator.java index 8c339f46c8..4385b39bb3 100644 --- a/json-modules/json-2/src/main/java/com/baeldung/jsonvalidation/JacksonValidator.java +++ b/json-modules/json-2/src/main/java/com/baeldung/jsonvalidation/JacksonValidator.java @@ -1,11 +1,15 @@ package com.baeldung.jsonvalidation; import com.fasterxml.jackson.core.JacksonException; +import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; public class JacksonValidator { - final ObjectMapper mapper = new ObjectMapper(); + final ObjectMapper mapper = JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); public boolean isValid(String json) { try { From e9e7aace3164288dfa17113140d69f9bbf974ec0 Mon Sep 17 00:00:00 2001 From: emanueltrandafir1993 Date: Sun, 8 Jan 2023 16:59:46 +0100 Subject: [PATCH 02/43] 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 c0157effb048677bc0ab4782c988a01f822c179a Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Sat, 14 Jan 2023 03:34:54 +0100 Subject: [PATCH 03/43] [List-CaseInsenContains] Case-Insensitive Searching in ArrayList (#13280) --- .../list/ignorecase/IgnoreCaseSearchUtil.java | 14 ++++++ .../list/ignorecase/IgnoreCaseStringList.java | 29 ++++++++++++ .../IgnoreCaseContainsUnitTest.java | 45 +++++++++++++++++++ 3 files changed, 88 insertions(+) create mode 100644 core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/list/ignorecase/IgnoreCaseSearchUtil.java create mode 100644 core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/list/ignorecase/IgnoreCaseStringList.java create mode 100644 core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/list/ignorecase/IgnoreCaseContainsUnitTest.java diff --git a/core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/list/ignorecase/IgnoreCaseSearchUtil.java b/core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/list/ignorecase/IgnoreCaseSearchUtil.java new file mode 100644 index 0000000000..38532ef031 --- /dev/null +++ b/core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/list/ignorecase/IgnoreCaseSearchUtil.java @@ -0,0 +1,14 @@ +package com.baeldung.list.ignorecase; + +import java.util.List; + +public class IgnoreCaseSearchUtil { + public static boolean ignoreCaseContains(List theList, String searchStr) { + for (String s : theList) { + if (searchStr.equalsIgnoreCase(s)) { + return true; + } + } + return false; + } +} diff --git a/core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/list/ignorecase/IgnoreCaseStringList.java b/core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/list/ignorecase/IgnoreCaseStringList.java new file mode 100644 index 0000000000..a27c2650ed --- /dev/null +++ b/core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/list/ignorecase/IgnoreCaseStringList.java @@ -0,0 +1,29 @@ +package com.baeldung.list.ignorecase; + +import java.util.ArrayList; +import java.util.Collection; + +public class IgnoreCaseStringList extends ArrayList { + + public IgnoreCaseStringList() { + + } + + public IgnoreCaseStringList(Collection c) { + super(c); + } + + @Override + public boolean contains(Object o) { + String searchStr = (String) o; + // Using Stream API: + // return this.stream().anyMatch(searchStr::equalsIgnoreCase); + for (String s : this) { + if (searchStr.equalsIgnoreCase(s)) { + return true; + } + } + return false; + } + +} diff --git a/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/list/ignorecase/IgnoreCaseContainsUnitTest.java b/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/list/ignorecase/IgnoreCaseContainsUnitTest.java new file mode 100644 index 0000000000..5ca9bb1028 --- /dev/null +++ b/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/list/ignorecase/IgnoreCaseContainsUnitTest.java @@ -0,0 +1,45 @@ +package com.baeldung.list.ignorecase; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class IgnoreCaseContainsUnitTest { + private static final List LANGUAGES = Arrays.asList("Java", "Python", "Kotlin", "Ruby", "Javascript", "Go"); + + @Test + void givenStringList_whenCallTheStandardContains_shouldReturnFalse() { + String searchStr = "jAvA"; + boolean result = LANGUAGES.contains(searchStr); + assertFalse(result); + } + + @Test + void givenStringList_whenSearchIgnoreCaseUsingStreamAPI_shouldReturnTrue() { + String searchStr = "koTliN"; + boolean result = LANGUAGES.stream().anyMatch(searchStr::equalsIgnoreCase); + assertTrue(result); + } + + @Test + void givenStringList_whenUsingUtilClass_shouldReturnTrue() { + String searchStr = "ruBY"; + boolean result = IgnoreCaseSearchUtil.ignoreCaseContains(LANGUAGES, searchStr); + assertTrue(result); + } + + @Test + void givenStringList_whenUsingIgnoreCaseStringList_shouldReturnTrue() { + String searchStr = "pYtHoN"; + List ignoreCaseList = new IgnoreCaseStringList(LANGUAGES); + boolean result = ignoreCaseList.contains(searchStr); + assertTrue(result); + + boolean resultContainAll = ignoreCaseList.containsAll(Arrays.asList("pYtHon", "jAvA", "koTliN", "ruBY")); + assertTrue(resultContainAll); + } +} From e80b67b507bb55e88cf91384f14b51cec02eaaf7 Mon Sep 17 00:00:00 2001 From: Abhinav Pandey Date: Sat, 14 Jan 2023 11:37:48 +0530 Subject: [PATCH 04/43] Bael 5436 new (#13283) * BAEL-5777 - Mocking a singleton with Mockito * BAEL-5436 - Root mapping * Revert "BAEL-5777 - Mocking a singleton with Mockito" This reverts commit 358a061997a4b853e3215dea0217a070f0e391e4. * BAEL-5436 - Uncommenting controller --- .../rootmapping/RootMappingApplication.java | 14 ++++++++++++++ .../com/baeldung/rootmapping/config/WebConfig.java | 13 +++++++++++++ .../rootmapping/controller/RootController.java | 12 ++++++++++++ .../src/main/resources/templates/index.html | 10 ++++++++++ 4 files changed, 49 insertions(+) create mode 100644 spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/RootMappingApplication.java create mode 100644 spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/config/WebConfig.java create mode 100644 spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/controller/RootController.java create mode 100644 spring-web-modules/spring-web-url/src/main/resources/templates/index.html diff --git a/spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/RootMappingApplication.java b/spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/RootMappingApplication.java new file mode 100644 index 0000000000..f64753fa36 --- /dev/null +++ b/spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/RootMappingApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.rootmapping; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +@SpringBootApplication +@EnableWebMvc +public class RootMappingApplication { + + public static void main(String[] args) { + SpringApplication.run(RootMappingApplication.class, args); + } +} \ No newline at end of file diff --git a/spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/config/WebConfig.java b/spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/config/WebConfig.java new file mode 100644 index 0000000000..ba15bc992c --- /dev/null +++ b/spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/config/WebConfig.java @@ -0,0 +1,13 @@ +package com.baeldung.rootmapping.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebConfig implements WebMvcConfigurer { + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("index"); + } +} diff --git a/spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/controller/RootController.java b/spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/controller/RootController.java new file mode 100644 index 0000000000..7724e43e71 --- /dev/null +++ b/spring-web-modules/spring-web-url/src/main/java/com/baeldung/rootmapping/controller/RootController.java @@ -0,0 +1,12 @@ +package com.baeldung.rootmapping.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class RootController { + @GetMapping("/") + public String index() { + return "index"; + } +} \ No newline at end of file diff --git a/spring-web-modules/spring-web-url/src/main/resources/templates/index.html b/spring-web-modules/spring-web-url/src/main/resources/templates/index.html new file mode 100644 index 0000000000..acfb847868 --- /dev/null +++ b/spring-web-modules/spring-web-url/src/main/resources/templates/index.html @@ -0,0 +1,10 @@ + + + + + Index Page + + +

Hello World!

+ + \ No newline at end of file From a53ee3f0cbeee2b23007c66cb7755b0e092182ec Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sun, 15 Jan 2023 14:21:58 +0530 Subject: [PATCH 05/43] JAVA-14471 Update Keycloak articles - deprecated client adapters --- .../spring-boot-keycloak-adapters/README.md | 7 ++ .../spring-boot-keycloak-adapters/pom.xml | 91 +++++++++++++++++++ .../keycloak/CustomUserAttrController.java | 0 .../java/com/baeldung/keycloak/Customer.java | 49 ++++++++++ .../com/baeldung/keycloak/CustomerDAO.java | 7 ++ .../com/baeldung/keycloak/KeycloakConfig.java | 0 .../keycloak/KeycloakLogoutHandler.java | 45 +++++++++ .../com/baeldung/keycloak/SecurityConfig.java | 41 +++++++++ .../com/baeldung/keycloak/SpringBoot.java | 20 ++++ .../com/baeldung/keycloak/WebController.java | 60 ++++++++++++ .../resources/application-embedded.properties | 0 .../src/main/resources/application.properties | 15 +++ .../src/main/resources/logback.xml | 13 +++ .../main/resources/templates/customers.html | 34 +++++++ .../main/resources/templates/external.html | 31 +++++++ .../src/main/resources/templates/layout.html | 18 ++++ .../main/resources/templates/userInfo.html | 0 .../KeycloakConfigurationLiveTest.java | 0 .../spring-boot-keycloak/README.md | 3 +- .../spring-boot-keycloak/pom.xml | 20 +--- .../com/baeldung/keycloak/SecurityConfig.java | 10 ++ .../keycloaksoap/KeycloakSecurityConfig.java | 55 +++-------- .../resources/application-keycloak.properties | 8 +- .../src/main/resources/application.properties | 13 +-- .../KeycloakContextIntegrationTest.java | 18 ++++ .../keycloaksoap/KeycloakSoapLiveTest.java | 2 +- .../resources/application-test.properties | 5 +- 27 files changed, 486 insertions(+), 79 deletions(-) create mode 100644 spring-boot-modules/spring-boot-keycloak-adapters/README.md create mode 100644 spring-boot-modules/spring-boot-keycloak-adapters/pom.xml rename spring-boot-modules/{spring-boot-keycloak => spring-boot-keycloak-adapters}/src/main/java/com/baeldung/keycloak/CustomUserAttrController.java (100%) create mode 100644 spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/Customer.java create mode 100644 spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/CustomerDAO.java rename spring-boot-modules/{spring-boot-keycloak => spring-boot-keycloak-adapters}/src/main/java/com/baeldung/keycloak/KeycloakConfig.java (100%) create mode 100644 spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/KeycloakLogoutHandler.java create mode 100644 spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/SecurityConfig.java create mode 100644 spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/SpringBoot.java create mode 100644 spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/WebController.java rename spring-boot-modules/{spring-boot-keycloak => spring-boot-keycloak-adapters}/src/main/resources/application-embedded.properties (100%) create mode 100644 spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/application.properties create mode 100644 spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/logback.xml create mode 100644 spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/templates/customers.html create mode 100644 spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/templates/external.html create mode 100644 spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/templates/layout.html rename spring-boot-modules/{spring-boot-keycloak => spring-boot-keycloak-adapters}/src/main/resources/templates/userInfo.html (100%) rename spring-boot-modules/{spring-boot-keycloak => spring-boot-keycloak-adapters}/src/test/java/com/baeldung/keycloak/KeycloakConfigurationLiveTest.java (100%) create mode 100644 spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakContextIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-keycloak-adapters/README.md b/spring-boot-modules/spring-boot-keycloak-adapters/README.md new file mode 100644 index 0000000000..d24d315f50 --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak-adapters/README.md @@ -0,0 +1,7 @@ +## Spring Boot Keycloak + +This module contains articles about Keycloak in Spring Boot projects. + +## Relevant articles: +- [Custom User Attributes with Keycloak](https://www.baeldung.com/keycloak-custom-user-attributes) +- [Get Keycloak User ID in Spring](https://www.baeldung.com/spring-keycloak-get-user-id) diff --git a/spring-boot-modules/spring-boot-keycloak-adapters/pom.xml b/spring-boot-modules/spring-boot-keycloak-adapters/pom.xml new file mode 100644 index 0000000000..0da8d920d1 --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak-adapters/pom.xml @@ -0,0 +1,91 @@ + + + 4.0.0 + com.baeldung.keycloak + spring-boot-keycloak-adapters + 0.0.1 + spring-boot-keycloak-adapters + jar + This is a simple application demonstrating integration between Keycloak and Spring Boot. + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + + org.keycloak.bom + keycloak-adapter-bom + ${keycloak-adapter-bom.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter + + + org.keycloak + keycloak-spring-boot-starter + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-oauth2-client + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + org.hsqldb + hsqldb + runtime + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.security + spring-security-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + 15.0.2 + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/CustomUserAttrController.java b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/CustomUserAttrController.java similarity index 100% rename from spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/CustomUserAttrController.java rename to spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/CustomUserAttrController.java diff --git a/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/Customer.java b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/Customer.java new file mode 100644 index 0000000000..3293446b1d --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/Customer.java @@ -0,0 +1,49 @@ +package com.baeldung.keycloak; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Customer { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + private String name; + private String serviceRendered; + private String address; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getServiceRendered() { + return serviceRendered; + } + + public void setServiceRendered(String serviceRendered) { + this.serviceRendered = serviceRendered; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + +} diff --git a/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/CustomerDAO.java b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/CustomerDAO.java new file mode 100644 index 0000000000..20d992d335 --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/CustomerDAO.java @@ -0,0 +1,7 @@ +package com.baeldung.keycloak; + +import org.springframework.data.repository.CrudRepository; + +public interface CustomerDAO extends CrudRepository { + +} diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/KeycloakConfig.java b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/KeycloakConfig.java similarity index 100% rename from spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/KeycloakConfig.java rename to spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/KeycloakConfig.java diff --git a/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/KeycloakLogoutHandler.java b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/KeycloakLogoutHandler.java new file mode 100644 index 0000000000..06c41e9b1d --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/KeycloakLogoutHandler.java @@ -0,0 +1,45 @@ +package com.baeldung.keycloak; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.core.oidc.user.OidcUser; +import org.springframework.security.web.authentication.logout.LogoutHandler; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@Component +public class KeycloakLogoutHandler implements LogoutHandler { + + private static final Logger logger = LoggerFactory.getLogger(KeycloakLogoutHandler.class); + private final RestTemplate restTemplate; + + public KeycloakLogoutHandler(RestTemplate restTemplate) { + this.restTemplate = restTemplate; + } + + @Override + public void logout(HttpServletRequest request, HttpServletResponse response, Authentication auth) { + logoutFromKeycloak((OidcUser) auth.getPrincipal()); + } + + private void logoutFromKeycloak(OidcUser user) { + String endSessionEndpoint = user.getIssuer() + "/protocol/openid-connect/logout"; + UriComponentsBuilder builder = UriComponentsBuilder + .fromUriString(endSessionEndpoint) + .queryParam("id_token_hint", user.getIdToken().getTokenValue()); + + ResponseEntity logoutResponse = restTemplate.getForEntity(builder.toUriString(), String.class); + if (logoutResponse.getStatusCode().is2xxSuccessful()) { + logger.info("Successfulley logged out from Keycloak"); + } else { + logger.error("Could not propagate logout to Keycloak"); + } + } + +} diff --git a/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/SecurityConfig.java b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/SecurityConfig.java new file mode 100644 index 0000000000..c39e37cfaa --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/SecurityConfig.java @@ -0,0 +1,41 @@ +package com.baeldung.keycloak; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.core.session.SessionRegistryImpl; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy; +import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; + +@Configuration +@EnableWebSecurity +class SecurityConfig { + + private final KeycloakLogoutHandler keycloakLogoutHandler; + + SecurityConfig(KeycloakLogoutHandler keycloakLogoutHandler) { + this.keycloakLogoutHandler = keycloakLogoutHandler; + } + + @Bean + protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { + return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl()); + } + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/customers*", "/users*") + .hasRole("USER") + .anyRequest() + .permitAll(); + http.oauth2Login() + .and() + .logout() + .addLogoutHandler(keycloakLogoutHandler) + .logoutSuccessUrl("/"); + return http.build(); + } +} diff --git a/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/SpringBoot.java b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/SpringBoot.java new file mode 100644 index 0000000000..90d7e774a4 --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/SpringBoot.java @@ -0,0 +1,20 @@ +package com.baeldung.keycloak; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.web.client.RestTemplate; + +@SpringBootApplication + +public class SpringBoot { + + public static void main(String[] args) { + SpringApplication.run(SpringBoot.class, args); + } + + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(); + } +} diff --git a/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/WebController.java b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/WebController.java new file mode 100644 index 0000000000..bbd96c8135 --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/java/com/baeldung/keycloak/WebController.java @@ -0,0 +1,60 @@ +package com.baeldung.keycloak; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +import java.security.Principal; + +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.http.HttpServletRequest; + +@Controller +public class WebController { + + @Autowired + private CustomerDAO customerDAO; + + @GetMapping(path = "/") + public String index() { + return "external"; + } + + @GetMapping("/logout") + public String logout(HttpServletRequest request) throws Exception { + request.logout(); + return "redirect:/"; + } + + @GetMapping(path = "/customers") + public String customers(Principal principal, Model model) { + addCustomers(); + Iterable customers = customerDAO.findAll(); + model.addAttribute("customers", customers); + model.addAttribute("username", principal.getName()); + return "customers"; + } + + // add customers for demonstration + public void addCustomers() { + + Customer customer1 = new Customer(); + customer1.setAddress("1111 foo blvd"); + customer1.setName("Foo Industries"); + customer1.setServiceRendered("Important services"); + customerDAO.save(customer1); + + Customer customer2 = new Customer(); + customer2.setAddress("2222 bar street"); + customer2.setName("Bar LLP"); + customer2.setServiceRendered("Important services"); + customerDAO.save(customer2); + + Customer customer3 = new Customer(); + customer3.setAddress("33 main street"); + customer3.setName("Big LLC"); + customer3.setServiceRendered("Important services"); + customerDAO.save(customer3); + } +} diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/resources/application-embedded.properties b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/application-embedded.properties similarity index 100% rename from spring-boot-modules/spring-boot-keycloak/src/main/resources/application-embedded.properties rename to spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/application-embedded.properties diff --git a/spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/application.properties b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/application.properties new file mode 100644 index 0000000000..323617e2ef --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/application.properties @@ -0,0 +1,15 @@ +### server port +server.port=8081 + +#Keycloak Configuration +keycloak.auth-server-url=http://localhost:8180/auth +keycloak.realm=SpringBootKeycloak +keycloak.resource=login-app +keycloak.public-client=true +keycloak.principal-attribute=preferred_username + +spring.security.oauth2.client.registration.keycloak.client-id=login-app +spring.security.oauth2.client.registration.keycloak.authorization-grant-type=authorization_code +spring.security.oauth2.client.registration.keycloak.scope=openid +spring.security.oauth2.client.provider.keycloak.issuer-uri=http://localhost:8180/auth/realms/SpringBootKeycloak +spring.security.oauth2.client.provider.keycloak.user-name-attribute=preferred_username \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak-adapters/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-boot-modules/spring-boot-keycloak-adapters/src/main/resources/templates/customers.html b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/templates/customers.html new file mode 100644 index 0000000000..de2df93ef1 --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/templates/customers.html @@ -0,0 +1,34 @@ + + + + + +
+

+ Hello, --name--. +

+ + + + + + + + + + + + + + + + + +
IDNameAddressService Rendered
Text ...Text ...Text ...Text...
+ + Logout +
+ + + diff --git a/spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/templates/external.html b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/templates/external.html new file mode 100644 index 0000000000..2f9cc76961 --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/templates/external.html @@ -0,0 +1,31 @@ + + + + + +
+
+

Customer Portal

+
+
+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam + erat lectus, vehicula feugiat ultricies at, tempus sed ante. Cras + arcu erat, lobortis vitae quam et, mollis pharetra odio. Nullam sit + amet congue ipsum. Nunc dapibus odio ut ligula venenatis porta non + id dui. Duis nec tempor tellus. Suspendisse id blandit ligula, sit + amet varius mauris. Nulla eu eros pharetra, tristique dui quis, + vehicula libero. Aenean a neque sit amet tellus porttitor rutrum nec + at leo.

+ +

Existing Customers

+
+ Enter the intranet: customers +
+
+ +
+ + + + diff --git a/spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/templates/layout.html b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/templates/layout.html new file mode 100644 index 0000000000..bab0c2982b --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/templates/layout.html @@ -0,0 +1,18 @@ + + + +Customer Portal + + + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/resources/templates/userInfo.html b/spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/templates/userInfo.html similarity index 100% rename from spring-boot-modules/spring-boot-keycloak/src/main/resources/templates/userInfo.html rename to spring-boot-modules/spring-boot-keycloak-adapters/src/main/resources/templates/userInfo.html diff --git a/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationLiveTest.java b/spring-boot-modules/spring-boot-keycloak-adapters/src/test/java/com/baeldung/keycloak/KeycloakConfigurationLiveTest.java similarity index 100% rename from spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakConfigurationLiveTest.java rename to spring-boot-modules/spring-boot-keycloak-adapters/src/test/java/com/baeldung/keycloak/KeycloakConfigurationLiveTest.java diff --git a/spring-boot-modules/spring-boot-keycloak/README.md b/spring-boot-modules/spring-boot-keycloak/README.md index e95ada0e05..b4545e121c 100644 --- a/spring-boot-modules/spring-boot-keycloak/README.md +++ b/spring-boot-modules/spring-boot-keycloak/README.md @@ -4,9 +4,8 @@ This module contains articles about Keycloak in Spring Boot projects. ## Relevant articles: - [A Quick Guide to Using Keycloak With Spring Boot](https://www.baeldung.com/spring-boot-keycloak) -- [Custom User Attributes with Keycloak](https://www.baeldung.com/keycloak-custom-user-attributes) - [Customizing the Login Page for Keycloak](https://www.baeldung.com/keycloak-custom-login-page) - [Keycloak User Self-Registration](https://www.baeldung.com/keycloak-user-registration) - [Customizing Themes for Keycloak](https://www.baeldung.com/spring-keycloak-custom-themes) - [Securing SOAP Web Services With Keycloak](https://www.baeldung.com/soap-keycloak) -- [Get Keycloak User ID in Spring](https://www.baeldung.com/spring-keycloak-get-user-id) + diff --git a/spring-boot-modules/spring-boot-keycloak/pom.xml b/spring-boot-modules/spring-boot-keycloak/pom.xml index 4f30d32bec..d13ef22345 100644 --- a/spring-boot-modules/spring-boot-keycloak/pom.xml +++ b/spring-boot-modules/spring-boot-keycloak/pom.xml @@ -17,26 +17,14 @@ ../../parent-boot-2 - - - - org.keycloak.bom - keycloak-adapter-bom - ${keycloak-adapter-bom.version} - pom - import - - - - org.springframework.boot spring-boot-starter - org.keycloak - keycloak-spring-boot-starter + org.springframework.boot + spring-boot-starter-oauth2-resource-server org.springframework.boot @@ -113,8 +101,4 @@ - - 15.0.2 - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java index c39e37cfaa..c85438952a 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java @@ -2,8 +2,11 @@ package com.baeldung.keycloak; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer; import org.springframework.security.core.session.SessionRegistryImpl; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy; @@ -36,6 +39,13 @@ class SecurityConfig { .logout() .addLogoutHandler(keycloakLogoutHandler) .logoutSuccessUrl("/"); + http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); return http.build(); } + + @Bean + public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception { + return http.getSharedObject(AuthenticationManagerBuilder.class) + .build(); + } } diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/KeycloakSecurityConfig.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/KeycloakSecurityConfig.java index 66a17f4967..e55d307e33 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/KeycloakSecurityConfig.java +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloaksoap/KeycloakSecurityConfig.java @@ -1,54 +1,27 @@ package com.baeldung.keycloaksoap; -import org.keycloak.adapters.KeycloakConfigResolver; -import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver; -import org.keycloak.adapters.springsecurity.KeycloakConfiguration; -import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider; -import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper; -import org.springframework.security.core.session.SessionRegistryImpl; -import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy; -import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer; +import org.springframework.security.web.SecurityFilterChain; -@KeycloakConfiguration +@Configuration +@EnableWebSecurity @ConditionalOnProperty(name = "keycloak.enabled", havingValue = "true") @EnableGlobalMethodSecurity(jsr250Enabled = true) -public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter { - @Override - protected void configure(HttpSecurity http) throws Exception { - super.configure(http); - //@formatter:off - http - .csrf() - .disable() - .authorizeRequests() - .anyRequest() - .permitAll(); - //@formatter:on - } - - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) { - KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider(); - keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper()); - auth.authenticationProvider(keycloakAuthenticationProvider); - } +public class KeycloakSecurityConfig { @Bean - @Override - protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { - return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl()); + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http.csrf() + .disable() + .authorizeHttpRequests(auth -> auth.anyRequest() + .authenticated()) + .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); + return http.build(); } - - @Bean - public KeycloakConfigResolver keycloakSpringBootConfigResolver() { - return new KeycloakSpringBootConfigResolver(); - } - } diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/resources/application-keycloak.properties b/spring-boot-modules/spring-boot-keycloak/src/main/resources/application-keycloak.properties index 0a28b7ac48..474e671ce3 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/resources/application-keycloak.properties +++ b/spring-boot-modules/spring-boot-keycloak/src/main/resources/application-keycloak.properties @@ -1,14 +1,8 @@ server.port=18080 keycloak.enabled=true -keycloak.realm=baeldung-soap-services -keycloak.auth-server-url=http://localhost:8080/auth -keycloak.bearer-only=true -keycloak.credentials.secret=14da6f9e-261f-489a-9bf0-1441e4a9ddc4 -keycloak.ssl-required=external -keycloak.resource=baeldung-soap-services -keycloak.use-resource-role-mappings=true +spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/realms/baeldung-soap-services # Custom properties begin here ws.api.path=/ws/api/v1/* diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/resources/application.properties b/spring-boot-modules/spring-boot-keycloak/src/main/resources/application.properties index 323617e2ef..df2fadabae 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-keycloak/src/main/resources/application.properties @@ -1,15 +1,10 @@ ### server port server.port=8081 -#Keycloak Configuration -keycloak.auth-server-url=http://localhost:8180/auth -keycloak.realm=SpringBootKeycloak -keycloak.resource=login-app -keycloak.public-client=true -keycloak.principal-attribute=preferred_username - spring.security.oauth2.client.registration.keycloak.client-id=login-app spring.security.oauth2.client.registration.keycloak.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.keycloak.scope=openid -spring.security.oauth2.client.provider.keycloak.issuer-uri=http://localhost:8180/auth/realms/SpringBootKeycloak -spring.security.oauth2.client.provider.keycloak.user-name-attribute=preferred_username \ No newline at end of file +spring.security.oauth2.client.provider.keycloak.issuer-uri=http://localhost:8080/realms/SpringBootKeycloak +spring.security.oauth2.client.provider.keycloak.user-name-attribute=preferred_username + +spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/realms/SpringBootKeycloak \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakContextIntegrationTest.java b/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakContextIntegrationTest.java new file mode 100644 index 0000000000..336c8364aa --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloak/KeycloakContextIntegrationTest.java @@ -0,0 +1,18 @@ +package com.baeldung.keycloak; + +import org.junit.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import com.baeldung.keycloak.SpringBoot; + +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = { SpringBoot.class }) +public class KeycloakContextIntegrationTest { + + @Test + public void whenLoadApplication_thenSuccess() { + + } + +} diff --git a/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloaksoap/KeycloakSoapLiveTest.java b/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloaksoap/KeycloakSoapLiveTest.java index 0327915399..171c7bf330 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloaksoap/KeycloakSoapLiveTest.java +++ b/spring-boot-modules/spring-boot-keycloak/src/test/java/com/baeldung/keycloaksoap/KeycloakSoapLiveTest.java @@ -105,7 +105,7 @@ class KeycloakSoapLiveTest { void givenAccessToken_whenDeleteProduct_thenReturnSuccess() { HttpHeaders headers = new HttpHeaders(); headers.set("content-type", "text/xml"); - headers.set("Authorization", "Bearer " + generateToken("jhondoe", "password")); + headers.set("Authorization", "Bearer " + generateToken("johndoe", "password")); HttpEntity request = new HttpEntity<>(Utility.getDeleteProductsRequest(), headers); ResponseEntity responseEntity = restTemplate.postForEntity("http://localhost:" + port + "/ws/api/v1/", request, String.class); diff --git a/spring-boot-modules/spring-boot-keycloak/src/test/resources/application-test.properties b/spring-boot-modules/spring-boot-keycloak/src/test/resources/application-test.properties index a818b5be7a..609d59b4bf 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/test/resources/application-test.properties +++ b/spring-boot-modules/spring-boot-keycloak/src/test/resources/application-test.properties @@ -1,4 +1,7 @@ grant.type=password client.id=baeldung-soap-services client.secret=d2ba7af8-f7d2-4c97-b4a5-3c88b59920ae -url=http://localhost:8080/auth/realms/baeldung-soap-services/protocol/openid-connect/token +url=http://localhost:8080/realms/baeldung-soap-services/protocol/openid-connect/token + +keycloak.enabled=true +spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/realms/baeldung-soap-services From c16ec71a13693f799fb1a868b610e7e60cddaaa3 Mon Sep 17 00:00:00 2001 From: Anastasios Ioannidis Date: Mon, 16 Jan 2023 10:26:20 +0200 Subject: [PATCH 06/43] JAVA-15609 Changed to IntegrationTest to reproduce issue on Jenkins --- ...nualTest.java => ApiControllerDocTesterIntegrationTest.java} | 2 +- ...ockManualTest.java => ApiControllerMockIntegrationTest.java} | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename web-modules/ninja/src/test/java/controllers/{ApiControllerDocTesterManualTest.java => ApiControllerDocTesterIntegrationTest.java} (91%) rename web-modules/ninja/src/test/java/controllers/{ApiControllerMockManualTest.java => ApiControllerMockIntegrationTest.java} (94%) diff --git a/web-modules/ninja/src/test/java/controllers/ApiControllerDocTesterManualTest.java b/web-modules/ninja/src/test/java/controllers/ApiControllerDocTesterIntegrationTest.java similarity index 91% rename from web-modules/ninja/src/test/java/controllers/ApiControllerDocTesterManualTest.java rename to web-modules/ninja/src/test/java/controllers/ApiControllerDocTesterIntegrationTest.java index b77901c8e2..a075497dc8 100644 --- a/web-modules/ninja/src/test/java/controllers/ApiControllerDocTesterManualTest.java +++ b/web-modules/ninja/src/test/java/controllers/ApiControllerDocTesterIntegrationTest.java @@ -7,7 +7,7 @@ import org.doctester.testbrowser.Response; import org.junit.Test; import ninja.NinjaDocTester; -public class ApiControllerDocTesterManualTest extends NinjaDocTester { +public class ApiControllerDocTesterIntegrationTest extends NinjaDocTester { String URL_INDEX = "/"; String URL_HELLO = "/hello"; diff --git a/web-modules/ninja/src/test/java/controllers/ApiControllerMockManualTest.java b/web-modules/ninja/src/test/java/controllers/ApiControllerMockIntegrationTest.java similarity index 94% rename from web-modules/ninja/src/test/java/controllers/ApiControllerMockManualTest.java rename to web-modules/ninja/src/test/java/controllers/ApiControllerMockIntegrationTest.java index 2fa76bca4e..53a760aadc 100644 --- a/web-modules/ninja/src/test/java/controllers/ApiControllerMockManualTest.java +++ b/web-modules/ninja/src/test/java/controllers/ApiControllerMockIntegrationTest.java @@ -10,7 +10,7 @@ import ninja.Result; import services.UserService; @RunWith(NinjaRunner.class) -public class ApiControllerMockManualTest { +public class ApiControllerMockIntegrationTest { @Inject private UserService userService; From 227fa031429cb967d4009bac64ae2eba04336461 Mon Sep 17 00:00:00 2001 From: Thiago dos Santos Hora Date: Mon, 16 Jan 2023 17:30:08 +0100 Subject: [PATCH 07/43] BAEL-5959: Adjust code style (#13299) * BAEL-5959: Monad in Java * Fix test name * Fix code style --- .../java/com/baeldung/monad/MonadSamples.java | 39 ++----------------- 1 file changed, 4 insertions(+), 35 deletions(-) diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/monad/MonadSamples.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/monad/MonadSamples.java index 3ccbac2a3c..87b7fe697e 100644 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/monad/MonadSamples.java +++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/monad/MonadSamples.java @@ -28,30 +28,16 @@ class MonadSample1 extends MonadBaseExample { public double apply(double n) { return subtract1(add3(divideBy2(multiplyBy2(multiplyBy2(2))))); } - - public static void main(String[] args) { - final MonadSample1 test = new MonadSample1(); - System.out.println(test.apply(2)); - //6.0 - } - } class MonadSample2 extends MonadBaseExample { public double apply(double n) { - final double n1 = multiplyBy2(n); - final double n2 = multiplyBy2(n1); - final double n3 = divideBy2(n2); - final double n4 = add3(n3); + double n1 = multiplyBy2(n); + double n2 = multiplyBy2(n1); + double n3 = divideBy2(n2); + double n4 = add3(n3); return subtract1(n4); } - - public static void main(String[] args) { - final MonadSample2 test = new MonadSample2(); - System.out.println(test.apply(2)); - //6.0 - } - } class MonadSample3 extends MonadBaseExample { @@ -66,11 +52,6 @@ class MonadSample3 extends MonadBaseExample { .get(); } - public static void main(String[] args) { - final MonadSample3 test = new MonadSample3(); - System.out.println(test.apply(2)); - //6.0 - } } class MonadSample4 extends MonadBaseExample { @@ -90,13 +71,6 @@ class MonadSample3 extends MonadBaseExample { return leftSide.equals(rightSide); } - public static void main(String[] args) { - final MonadSample4 test = new MonadSample4(); - - System.out.println(test.leftIdentity()); //true - System.out.println(test.rightIdentity()); //true - System.out.println(test.associativity()); //true - } } class MonadSample5 extends MonadBaseExample { @@ -104,10 +78,5 @@ class MonadSample5 extends MonadBaseExample { Function> mapping = value -> Optional.of(value == null ? -1 : value + 1); return Optional.ofNullable((Integer) null).flatMap(mapping).equals(mapping.apply(null)); } - - public static void main(String[] args) { - final MonadSample5 test = new MonadSample5(); - System.out.println(test.fail()); - } } From 18787b33c5884555a69c2a75b3794ee0218d8c7a Mon Sep 17 00:00:00 2001 From: jsgrah-spring Date: Mon, 16 Jan 2023 18:31:13 +0100 Subject: [PATCH 08/43] JAVA-16085, Potential issue in "A Guide to SAML with Spring Security" article (#13279) * JAVA-16085, Potential issue in "A Guide to SAML with Spring Security" article. * JAVA-16085, Cleanup unnecessary resources samlKeystore.jks and library maven-war-plugin. Co-authored-by: jogra --- .../src/main/resources/application.properties | 8 ++++---- .../src/main/resources/saml/saml-keystore.jks | Bin 0 -> 2784 bytes .../src/main/resources/saml/samlKeystore.jks | Bin 2244 -> 0 bytes 3 files changed, 4 insertions(+), 4 deletions(-) create mode 100644 spring-security-modules/spring-security-saml/src/main/resources/saml/saml-keystore.jks delete mode 100644 spring-security-modules/spring-security-saml/src/main/resources/saml/samlKeystore.jks diff --git a/spring-security-modules/spring-security-saml/src/main/resources/application.properties b/spring-security-modules/spring-security-saml/src/main/resources/application.properties index fd7798dda9..332278225c 100644 --- a/spring-security-modules/spring-security-saml/src/main/resources/application.properties +++ b/spring-security-modules/spring-security-saml/src/main/resources/application.properties @@ -1,9 +1,9 @@ -saml.keystore.location=classpath:/saml/saml-keystore +saml.keystore.location=classpath:/saml/saml-keystore.jks # Password for Java keystore and item therein -saml.keystore.password= -saml.keystore.alias= +saml.keystore.password=baeldungsamlokta +saml.keystore.alias=baeldungspringsaml # SAML Entity ID extracted from top of SAML metadata file -saml.idp= +saml.idp=http://www.okta.com/exk26fxqrz8LLk9dV4x7 saml.sp=http://localhost:8080/saml/metadata spring.main.allow-circular-references=true \ No newline at end of file diff --git a/spring-security-modules/spring-security-saml/src/main/resources/saml/saml-keystore.jks b/spring-security-modules/spring-security-saml/src/main/resources/saml/saml-keystore.jks new file mode 100644 index 0000000000000000000000000000000000000000..535c6111809dbf409b56ee85a6a7d0fb680fa703 GIT binary patch literal 2784 zcma);X*kr67RP7Cm|>z+qiki%PJUx-W6i!!Nen}_ge0=2MYCB(wj#2ngh95ZWXpt# z;adJ#vWr65qOpty$?ZP(KK-Bj>fRUUIp=)N`JR{G=KvJM1O&_lP!Mr2Ud1@exF7sr zI5?kzh=fuQVZZTJfWpoEuMu}0l)_#88$bIU<*_LkFb)8us=!ANl**U^rr&gV7jf9>_o^2>}Q zRz6JVB%8xY;OKTlCNSH(OiY~tP+Juw8_y!9Jo}o_QrS(ds=uUCUrmlh4B|O;cv1Mu z(9`oWRhrv}=38j2#r?HxG#6_mUHhEw%Jj2t`wQqYK+|wF)n8G zJu+1NvOFyf$tlWsGr2s>(!dr()^&H;dl$O|C8Rq7H2$Sv8F}#nk&d;TA3Oih8dh%E zQEiK@Xfi?%0+4Xe6_RW-mX5Z6CE@j{=p^1S6yltaOAHwcGR zWE*H!JSsE+nuQ#1qrM+D3@C2O^gBy0knE}FcTMfMSC6;3UO~2X12zNtaq;dGtkgV7 z$s1wh1IKbR3#kk+@oPi2#0qLgni8BRRDOur10`c_L^g7jTwI(WlZiTm1TG_sg9-(K zPEd>0{+}1x9*~GJUkYspcEJpDqYJ)c_BETu(lO(Dg6MRcm3u-k*prGr#Eed*9h+cs zUmI#O22Fj`J{_j;WYq^9^sDXX2i6jVKmo#M0@_x$$QBTVU!d<4Sd_~5|7$sw73YV==#7}EF29FZ?XZ){6&yL{FjU_uOs;yC(<+T1l zUCN!%2ob>Gcyu4=Qre(t>%(}x%r6_U{?GaDeHFo09rb1L~e&#-m`&23Fp`7FFAUXR+M}n(zqUOk0Y9q(hkJ^jv z_wf8=FJwbEfFU71F9^ zQ)Y5nWmFuRt0r~pBJo|py}F=7xssIH?Y6;LU171yr8&=+?Mv#D7DlPamGdDx$)hj3 z^fH~c7Qd`zoFpK#&*^ms22)=hH+RK)7jk@G})$B|mgsZdV8& zqOW4^^~RNodx`jBjm9<=(?DYPc~ersK1i39q#g&m+A^KNy(sxSkruNHQbVcMi6~}- zw8iE1ZXT2~fc|5byhxPn@e`m6ATN*)=nCi}C;}7&@&ko|fo1ynu_=2Y z!lsXBz?V8r#EN>kik(eQc_tQqGxzmac9gr38y?K)#^SOa$k^OBV_{Og)ZU-B#hk*r zeL+oF`_|pnBkF5Mz9A!s9sPT*Dsi8HNYRV>#U9E$_vLcWX%5WMFwB9UR#NUR!}+#$ zG~XQddijKXXDM3+vVCNDMAfQ$^c_O*x=`okAXo&}!?W$>$(VT-wteQBcr@%+c=>nC zSz?+O8pgA{vmYKozy0!wgydT})gKA4t4sU)x=Q)h`sdQ?YrUf)ZP~7?hzX$)uYm7_ z)+EkTbk0ZBM(<}VQt?)!>IVT_hzt0`(7GL$CHxMK^VZaQ-$oyj_vdwd*Cb(Cc+y-+ zf#^9ovy)}XNtAhUiANW%7bA-;-uJ8z%agdQb%gA^6$e+e#;fD^mGRW(hmk5+m+1>1 zX}cT^QSQ5=N9}6J-gDui*HExS$vow>QhvRt%gcjtnropcUTxzio=d~qGx<7HL3SKZ{{(Db^evxY+4R{mVV7&}?L4 z$2P>>f++!qzsZRim8HpNw$g#-tF}E6-yfTtRQz;w*iNA7eyp_RfKhGF6k{r1=Fa() z`T4~i0BrM&bjnHgFDVr@BAUkO?!#4DC(rqB?Te)d*!)RNH~Z4Lc{K z?#HVp>N^2=+O?DiQx(TDZPUuVnc~C8yiPRy5~1c#WCbmoG{bJE*lV|X2QN+75US;m zn{~Oc-qQs-z8N+aMdf7quG}3t71`g#hujKBGqsQHm+A(d`o1=K_Po@`8p*^;aRS~& z&f#te$LLh$P~-0^sU)iuB_ZS&@1##jJ$Rvy!yTPM7P2yXe(Kx!{ z5FfhQj2gE6VnJO!crOt1{a4Tp?dczm^TCBlHS#+(T1swQDt)Fo>xS~gK7GQbsr3_` z%GcKZ(>qr1$+X#31tdth6YPl?H&&AC@;lPBFyz#Ss+%7_q{U#L_Fcy%}YX zt-lvwQ+B}`cN8OYL4u$YpX;f5S6`TwTk}ja)S>LwcDXg$(lU@BIXv(xO3>UH42wzf z*4iZS`dIJ!)&0^`yR+Y#lYt=GCQHAxKxTUR7C9i$FX*CLGNUQ)A@l~DV6HEBZAcAJoc2kKC_BV{Zlskcg3R|eNYan|h(3^9iyeDr-M77FTLwMafbO}w0O z<;1S>`#hJj^jS-*01nUgX^7gkjW6EgLr^=W#YeS+T2sUP3}68i!2jp#gMhg~P>Edy zN2hg-F46dA2@zv^aj*@DcOf-bmz1whzsSgFOM)UH!=GOmoIW_^ux`q2CD-wScDUUB HUzYSwll%Zc literal 0 HcmV?d00001 diff --git a/spring-security-modules/spring-security-saml/src/main/resources/saml/samlKeystore.jks b/spring-security-modules/spring-security-saml/src/main/resources/saml/samlKeystore.jks deleted file mode 100644 index 7f3a5850d9c79eb1bbe47eae6c1ae21e2e2d3529..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2244 zcmchYdpHw{AI5hxx7mmk#d0lkX>Jjnxg>YmBA1cNrdSwCY+Vo=#b}8fmk<`RP%dXg z2uF#qLLy@2QmJfmY0}T{Jip(0&hzyD`Q!cL{rvTP-sgSZ@8;s>A^-pYZ3+07#3DkY z1J4GAhi!qgG_&?506+wQPK0cr;ZO-}C=dcffnz2L)YR3+PuxCxl~nO-JFFkrMX{EEBwc(iN9$0L2Z2jc29s*-Zk9reBt% zKil-vtg$owD=&YZqP2n?NVfJ2)rnW9N*!$nwl1jk4H#)+Pm{KFposK|@tK zl#y!WV^eWaC9QY!B5Gv2WEsyJQ3M4nO|p&JOF{(8U|>Y z2b4TdF=A);s7ky!+FI5%vpz}}=YPoL<-R)@{qjL|xz_A#@qXxKA~nE66Xp?f`nqSr zYZB_cj_0^PfdF;CJQrUu8hXXw8eI1NK0|jGL%mk&6~u6JVy_Z@bHVKdPaC=ODegSs zp`!Ai+doG1ZHJ0g!BuWL2Eu|@3lC3WL*Yu(Cpq}cM~QQ^T8(}I_sp5m#kMEy&Bxo- zmzS+8K!!t^@r~FTR75O443Wh|(rpe6WhQ6ybBsLFT;=h0j}6Q)>ez1liputV%kz)m z?ap%{Hh3C$`l@B`wqd>_?J`q%Kiy+o9`Kg#!K}LNS8SS+q#RSXqJkstsu(YdO)d0u zX=!6zYP9ZFHjU}eALbb>46AZ$9Ikrv%cuqDIG=WFzJDvML}U);v*36gfh|X*MV{Z_=jk~(*B}0efq7y7RPI11xH5Cl9!8eeg~B}QnK9Kv9RDK&76(h zRH+I5drgkgT6J_*kZ}O}wWwWr0r3rEP`S~`J&r9T4oV7OPtJ?JqY5NF*EmMJ2+3pJ zc*vlSPy+Vwl?K`LR!ZtM&6x&I20^{%RaAvYYH(L(nI@@|9vp63tU5@F7-R*ksKZUvk z_p+_csB$6r9{ncaoMz z+Qvi#yOy=z${@xYP{Z0!8Phu);DCN}Ck2FUFxCE82-xTV1<5j-g8p|CT$h^G}8Kr}K-bAZMI%B(JOfJW0oKo}EoW!2I z+8LauH)1B25Vb7hqmmyk?|?{fqS{$Fr?IC>UmX7KrW|zJq{0w%`T82~&*5lEhr9b4 zU{kAhRqxTIU(8n3&`e=}}=3v#j9UOv|JG_7brnbnn++zYf? zkgN&7Tm8hX1FfCXk69?ukR^rwB5m856W=gZ>D{28+6rfG|Fw)FUV6spg8%^d0y+^K zi%taj7lT1S5C|f5vG){O3M!6DwohJ_0s#@S0#*MR$JVa^Cjt>$ zPXs6dN(2G{bw5w)@>3Zhq1^HsvBFcDvXV;&EfrpRY%<@OMCEm^DZl~BS-j7d=)0Wz zCvtGZ=2=G!=EWH{pj;h0@xU=)H)>$B>*p7ik&|>$cgVnt%^Lf&F^BHaBLn&*eM>4n zdaUr4%SX$NbzHWaSWrlx+c-fLf_QDn3x}Dc<)JXLjOudz#ZhyHhAaI0<2ZWc?%X>A zOt8p}C37jCR{O)3x}<%t>KqJ{16VyvPz0H$`jho6^eGLTl*vFcSYNFNdZE2w*XPQV z8xPMldTg6LL$Af+5{?+}nRj7x{vf^?h~3v$;x}ZLq<%xF{S0S8m}7m}@Dnh__9fF4 zdKHAnL0}*NSgL|XqLsE9q6CM?L*)FHz~b6JqId(^bykuG@$Mg#TPOY*;#Q}&LIeWL zN79`m?x*G^yXsxaatG2OC|Nwn)!FP_r^~scA#Q@)EY^-sX=ZuH>{wGl)~2H&T8iH+FOxDXFm;e ztji3w^d6CXNmLWl80Ww>(gE`sDWgeV)582XPH-Uk4ed!4P8^ZFObH9eyjdnB$vKq} zkbAvgrwZ=R_}N6TLaUIBgzLI6`6OPl>NzzPjO-QJ_Luyn2wFf7vN+?F4V6HcOzT+x T_;Wn+`Mka2bNFxOdj|dk==RY4 From c217f7e95c90b8d78631c8fce1c036b41ee9b5d9 Mon Sep 17 00:00:00 2001 From: jsgrah-spring Date: Mon, 16 Jan 2023 18:37:14 +0100 Subject: [PATCH 09/43] JAVA-15621, Potential issue in "Guide to UUID in Java" article. (#13271) * JAVA-15621, Potential issue in "Guide to UUID in Java" article. * JAVA-15621, Keep the raw strings in the article to make it easy for users to understand. * JAVA-15621, Keep the raw strings in the article to make it easy for users to understand. Co-authored-by: jogra --- .../main/java/com/baeldung/uuid/UUIDGenerator.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDGenerator.java b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDGenerator.java index 2170a72644..68ff9ce1d4 100644 --- a/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDGenerator.java +++ b/core-java-modules/core-java-uuid/src/main/java/com/baeldung/uuid/UUIDGenerator.java @@ -27,17 +27,17 @@ public final class UUIDGenerator { private static long get64LeastSignificantBitsForVersion1() { final long random63BitLong = new Random().nextLong() & 0x3FFFFFFFFFFFFFFFL; - final long variant3BitFlag = 0x8000000000000000L; - return random63BitLong + variant3BitFlag; + long variant3BitFlag = 0x8000000000000000L; + return random63BitLong | variant3BitFlag; } private static long get64MostSignificantBitsForVersion1() { - final long timeForUuidIn100Nanos = System.currentTimeMillis(); - final long time_low = (timeForUuidIn100Nanos & 0x0000_0000_FFFF_FFFFL) << 32; - final long time_mid = ((timeForUuidIn100Nanos >> 32) & 0xFFFF) << 16; + final long currentTimeMillis = System.currentTimeMillis(); + final long time_low = (currentTimeMillis & 0x0000_0000_FFFF_FFFFL) << 32; + final long time_mid = ((currentTimeMillis >> 32) & 0xFFFF) << 16; final long version = 1 << 12; - final long time_hi = ((timeForUuidIn100Nanos >> 48) & 0x0FFF); - return time_low + time_mid + version + time_hi; + final long time_high = ((currentTimeMillis >> 48) & 0x0FFF); + return time_low | time_mid | version | time_high; } /** From b90386e8d4d74fd499cd10ed621e5f33f8871374 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Mon, 16 Jan 2023 17:48:20 +0000 Subject: [PATCH 10/43] [JAVA-17295] Create and initialize ThreadPoolTaskExecutor (#13249) Co-authored-by: panagiotiskakos --- .../java/com/baeldung/async/config/SpringAsyncConfig.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/spring-scheduling/src/main/java/com/baeldung/async/config/SpringAsyncConfig.java b/spring-scheduling/src/main/java/com/baeldung/async/config/SpringAsyncConfig.java index 56fa643017..872f59ebb6 100644 --- a/spring-scheduling/src/main/java/com/baeldung/async/config/SpringAsyncConfig.java +++ b/spring-scheduling/src/main/java/com/baeldung/async/config/SpringAsyncConfig.java @@ -24,7 +24,9 @@ public class SpringAsyncConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { - return new SimpleAsyncTaskExecutor(); + ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); + threadPoolTaskExecutor.initialize(); + return threadPoolTaskExecutor; } @Override From dcc35801e77167f8add6d0dfc0ed29f315a4f43b Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Tue, 17 Jan 2023 03:40:44 +0000 Subject: [PATCH 11/43] [JAVA-15025] Upgraded to apache http 5 (#13296) * [JAVA-15025] Upgraded to apache http 5 * [JAVA-15025] Clean up Co-authored-by: panagiotiskakos --- .../sec/HttpClientAuthLiveTest.java | 139 +++++++++--------- 1 file changed, 70 insertions(+), 69 deletions(-) diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/sec/HttpClientAuthLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/sec/HttpClientAuthLiveTest.java index 0f7018a9ac..35af84679b 100644 --- a/httpclient-simple/src/test/java/com/baeldung/httpclient/sec/HttpClientAuthLiveTest.java +++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/sec/HttpClientAuthLiveTest.java @@ -1,118 +1,119 @@ package com.baeldung.httpclient.sec; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + import org.apache.commons.codec.binary.Base64; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpHost; -import org.apache.http.HttpStatus; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.AuthCache; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.impl.auth.BasicScheme; -import org.apache.http.impl.client.BasicAuthCache; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.protocol.HttpContext; -import com.baeldung.httpclient.ResponseUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; + +import com.baeldung.handler.CustomHttpClientResponseHandler; + +import org.apache.hc.client5.http.auth.AuthScope; +import org.apache.hc.client5.http.auth.AuthCache; +import org.apache.hc.client5.http.auth.CredentialsProvider; +import org.apache.hc.client5.http.auth.UsernamePasswordCredentials; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.impl.auth.BasicAuthCache; +import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider; +import org.apache.hc.client5.http.impl.auth.BasicScheme; +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.HttpClientBuilder; +import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.HttpHost; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.protocol.HttpContext; + +import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.charset.StandardCharsets; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; - /* * NOTE : Need module httpclient-simple to be running */ - -public class HttpClientAuthLiveTest { +class HttpClientAuthLiveTest { private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://localhost:8082/httpclient-simple/api/foos/1"; private static final String DEFAULT_USER = "user1"; private static final String DEFAULT_PASS = "user1Pass"; - - private CloseableHttpClient client; - - private CloseableHttpResponse response; - - @Before - public final void before() { - client = HttpClientBuilder.create().build(); - } - - @After - public final void after() throws IllegalStateException, IOException { - ResponseUtil.closeResponse(response); - } - - // tests + private final char[] DEFAULT_PASS_ARRAY = DEFAULT_PASS.toCharArray() ; @Test - public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException { - client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider()).build(); + final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException { + final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); + try (CloseableHttpClient client = HttpClientBuilder.create() + .setDefaultCredentialsProvider(provider()) + .build(); - response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION)); - - final int statusCode = response.getStatusLine().getStatusCode(); - assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(request, new CustomHttpClientResponseHandler())) { + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } } @Test - public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException { - client = HttpClientBuilder.create().build(); - response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context()); + final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException { + final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); + try (CloseableHttpClient client = HttpClientBuilder.create() + .build(); - final int statusCode = response.getStatusLine().getStatusCode(); - assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(request, context(), new CustomHttpClientResponseHandler())) { + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(200)); + } } @Test - public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws IOException { - client = HttpClientBuilder.create().build(); - + final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws IOException { final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); request.setHeader(HttpHeaders.AUTHORIZATION, authorizationHeader(DEFAULT_USER, DEFAULT_PASS)); - response = client.execute(request); + try (CloseableHttpClient client = HttpClientBuilder.create() + .build(); - final int statusCode = response.getStatusLine().getStatusCode(); - assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(request, context(), new CustomHttpClientResponseHandler())) { + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } } @Test - public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws IOException { + final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws IOException { final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION); final String auth = DEFAULT_USER + ":" + DEFAULT_PASS; final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1)); final String authHeader = "Basic " + new String(encodedAuth); request.setHeader(HttpHeaders.AUTHORIZATION, authHeader); - client = HttpClientBuilder.create().build(); - response = client.execute(request); + try (CloseableHttpClient client = HttpClientBuilder.create() + .build(); - final int statusCode = response.getStatusLine().getStatusCode(); - assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(request, new CustomHttpClientResponseHandler())) { + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } } // UTILS private CredentialsProvider provider() { - final CredentialsProvider provider = new BasicCredentialsProvider(); - final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS); - provider.setCredentials(AuthScope.ANY, credentials); + final HttpHost targetHost = new HttpHost("http", "localhost", 8082); + final BasicCredentialsProvider provider = new BasicCredentialsProvider(); + AuthScope authScope = new AuthScope(targetHost); + provider.setCredentials(authScope, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS_ARRAY)); return provider; } private HttpContext context() { - final HttpHost targetHost = new HttpHost("localhost", 8082, "http"); - final CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS)); + final HttpHost targetHost = new HttpHost("http", "localhost", 8082); + final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); + AuthScope authScope = new AuthScope(targetHost); + credsProvider.setCredentials(authScope, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS_ARRAY)); // Create AuthCache instance final AuthCache authCache = new BasicAuthCache(); From 0a76db37d657fee22224cc4178aa5aa4ba74d67c Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Tue, 17 Jan 2023 05:39:28 +0000 Subject: [PATCH 12/43] [JAVA-15016] Upgraded to apache http client 5.2 (#13269) * [JAVA-15016] Upgraded to apache http client 5.2 * [JAVA-15016] Clean up * [JAVA-15016] Junit 5 clean up Co-authored-by: panagiotiskakos --- .../HttpClientGettingCookieValueUnitTest.java | 58 ++++++++++--------- 1 file changed, 31 insertions(+), 27 deletions(-) diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/cookies/HttpClientGettingCookieValueUnitTest.java b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/cookies/HttpClientGettingCookieValueUnitTest.java index 404acb3098..265fa39816 100644 --- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/cookies/HttpClientGettingCookieValueUnitTest.java +++ b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/cookies/HttpClientGettingCookieValueUnitTest.java @@ -1,46 +1,50 @@ package com.baeldung.httpclient.cookies; -import org.apache.http.client.CookieStore; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.Cookie; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.cookie.BasicClientCookie; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.cookie.BasicCookieStore; +import org.apache.hc.client5.http.cookie.Cookie; +import org.apache.hc.client5.http.cookie.CookieStore; + +import org.apache.hc.client5.http.impl.classic.BasicHttpClientResponseHandler; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; + +import org.apache.hc.client5.http.impl.cookie.BasicClientCookie; +import org.apache.hc.client5.http.protocol.HttpClientContext; + import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; -import static org.junit.Assert.assertEquals; - - -public class HttpClientGettingCookieValueUnitTest { +class HttpClientGettingCookieValueUnitTest { private static Logger log = LoggerFactory.getLogger(HttpClientGettingCookieValueUnitTest.class); private static final String SAMPLE_URL = "http://www.baeldung.com/"; @Test - public final void whenSettingCustomCookieOnTheRequest_thenGettingTheSameCookieFromTheResponse() throws IOException { + void whenSettingCustomCookieOnTheRequest_thenGettingTheSameCookieFromTheResponse() throws IOException { + HttpClientContext context = HttpClientContext.create(); context.setAttribute(HttpClientContext.COOKIE_STORE, createCustomCookieStore()); - try (CloseableHttpClient httpClient = HttpClients.createDefault()) { - try (CloseableHttpResponse response = httpClient.execute(new HttpGet(SAMPLE_URL), context)) { - CookieStore cookieStore = context.getCookieStore(); - Cookie customCookie = cookieStore.getCookies() - .stream() - .peek(cookie -> log.info("cookie name:{}", cookie.getName())) - .filter(cookie -> "custom_cookie".equals(cookie.getName())) - .findFirst() - .orElseThrow(IllegalStateException::new); + final HttpGet request = new HttpGet(SAMPLE_URL); - assertEquals("test_value", customCookie.getValue()); - } + try (CloseableHttpClient client = HttpClientBuilder.create() + .build()) { + client.execute(request, context, new BasicHttpClientResponseHandler()); + CookieStore cookieStore = context.getCookieStore(); + Cookie customCookie = cookieStore.getCookies() + .stream() + .peek(cookie -> log.info("cookie name:{}", cookie.getName())) + .filter(cookie -> "custom_cookie".equals(cookie.getName())) + .findFirst() + .orElseThrow(IllegalStateException::new); + + assertEquals("test_value", customCookie.getValue()); } } @@ -48,7 +52,7 @@ public class HttpClientGettingCookieValueUnitTest { BasicCookieStore cookieStore = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("custom_cookie", "test_value"); cookie.setDomain("baeldung.com"); - cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true"); + cookie.setAttribute("domain", "true"); cookie.setPath("/"); cookieStore.addCookie(cookie); return cookieStore; From 77d6a987a8684460c91460e4499e6b0e295e09e0 Mon Sep 17 00:00:00 2001 From: emanueltrandafir1993 Date: Tue, 17 Jan 2023 20:47:07 +0100 Subject: [PATCH 13/43] 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 a4f6d89cc7789bc2d0ef9fb8c9ff60f9ab55286f Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Wed, 18 Jan 2023 00:15:26 +0100 Subject: [PATCH 14/43] [store-triple-in-list] Storing Data Triple in a List in Java (#13295) * [store-triple-in-list] Storing Data Triple in a List in Java * [store-triple-in-list] method name "give..."->"given..." --- .../main/java/com/baeldung/triple/Triple.java | 26 +++++ .../baeldung/triple/TripleInListUnitTest.java | 105 ++++++++++++++++++ 2 files changed, 131 insertions(+) create mode 100644 core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/triple/Triple.java create mode 100644 core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/triple/TripleInListUnitTest.java diff --git a/core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/triple/Triple.java b/core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/triple/Triple.java new file mode 100644 index 0000000000..b19266ad21 --- /dev/null +++ b/core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/triple/Triple.java @@ -0,0 +1,26 @@ +package com.baeldung.triple; + +public class Triple { + + private final L left; + private final M middle; + private final R right; + + public Triple(L left, M middle, R right) { + this.left = left; + this.middle = middle; + this.right = right; + } + + public L getLeft() { + return left; + } + + public M getMiddle() { + return middle; + } + + public R getRight() { + return right; + } +} diff --git a/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/triple/TripleInListUnitTest.java b/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/triple/TripleInListUnitTest.java new file mode 100644 index 0000000000..2196ae687f --- /dev/null +++ b/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/triple/TripleInListUnitTest.java @@ -0,0 +1,105 @@ +package com.baeldung.triple; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import org.junit.jupiter.api.Test; + +public class TripleInListUnitTest { + + enum OP { + PLUS("+"), MINUS("-"), MULTIPLY("x"); + final String opSign; + + OP(String x) { + this.opSign = x; + } + } + + private String createQuestion(Long num1, OP operator, Long num2) { + long result; + switch (operator) { + case PLUS: + result = num1 + num2; + break; + case MINUS: + result = num1 - num2; + break; + case MULTIPLY: + result = num1 * num2; + break; + default: + throw new IllegalArgumentException("Unknown operator"); + } + return String.format("%d %s %d = ? ( answer: %d )", num1, operator.opSign, num2, result); + } + + private static final List EXPECTED_QUESTIONS = Arrays.asList( + "100 - 42 = ? ( answer: 58 )", + "100 + 42 = ? ( answer: 142 )", + "100 x 42 = ? ( answer: 4200 )"); + + @Test + void givenTripleValues_whenStoreAsList_thenTypeIsNotSafe() { + + List myTriple1 = new ArrayList(3); + myTriple1.add(100L); + myTriple1.add(OP.MINUS); + myTriple1.add(42L); + + List myTriple2 = new ArrayList(3); + myTriple2.add(100L); + myTriple2.add(OP.PLUS); + myTriple2.add(42L); + + List myTriple3 = new ArrayList(3); + myTriple3.add(100L); + myTriple3.add(OP.MULTIPLY); + myTriple3.add(42L); + + List listOfTriples = new ArrayList<>(Arrays.asList(myTriple1, myTriple2, myTriple3)); + + List oopsTriple = new ArrayList(3); + oopsTriple.add("Oops"); + oopsTriple.add(911L); + oopsTriple.add("The type is wrong"); + + listOfTriples.add(oopsTriple); + assertEquals(4, listOfTriples.size()); + + List questions = listOfTriples.stream() + .filter( + triple -> triple.size() == 3 + && triple.get(0) instanceof Long + && triple.get(1) instanceof OP + && triple.get(2) instanceof Long + ).map(triple -> { + Long left = (Long) triple.get(0); + OP op = (OP) triple.get(1); + Long right = (Long) triple.get(2); + return createQuestion(left, op, right); + }).collect(Collectors.toList()); + + assertEquals(EXPECTED_QUESTIONS, questions); + } + + @Test + void givenTripleValues_whenUsingTheTripleClass_thenTypeIsSafeAndNeat() { + Triple triple1 = new Triple<>(100L, OP.MINUS, 42L); + Triple triple2 = new Triple<>(100L, OP.PLUS, 42L); + Triple triple3 = new Triple<>(100L, OP.MULTIPLY, 42L); + Triple tripleOops = new Triple<>("Oops", 911L, "The type is wrong"); + + List> listOfTriples = new ArrayList<>(Arrays.asList(triple1, triple2, triple3)); + // listOfTriples.add(tripleOops); // Compiler error: "java: incompatible types ... " + + List questions = listOfTriples.stream() + .map(triple -> createQuestion(triple.getLeft(), triple.getMiddle(), triple.getRight())) + .collect(Collectors.toList()); + + assertEquals(EXPECTED_QUESTIONS, questions); + } +} From de6d2bc25cabd418b944cf7498d8dcffe796253b Mon Sep 17 00:00:00 2001 From: alemoles Date: Wed, 18 Jan 2023 09:48:57 -0300 Subject: [PATCH 15/43] BAEL-5924 Java 8 Stream with Batch Processing Support (#13203) --- core-java-modules/core-java-streams-4/pom.xml | 36 +++++ .../processing/CustomBatchIterator.java | 47 ++++++ .../processing/StreamProcessingUnitTest.java | 141 ++++++++++++++++++ .../StreamProcessingWithVavrUnitTest.java | 30 ++++ 4 files changed, 254 insertions(+) create mode 100644 core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/processing/CustomBatchIterator.java create mode 100644 core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/processing/StreamProcessingUnitTest.java create mode 100644 core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/processing/vavr/StreamProcessingWithVavrUnitTest.java diff --git a/core-java-modules/core-java-streams-4/pom.xml b/core-java-modules/core-java-streams-4/pom.xml index ed4603796d..46c0f3f7e1 100644 --- a/core-java-modules/core-java-streams-4/pom.xml +++ b/core-java-modules/core-java-streams-4/pom.xml @@ -59,6 +59,36 @@ 3.12.0 test + + io.reactivex.rxjava3 + rxjava + ${rx.java3.version} + + + io.vavr + vavr + ${io.varv.version} + + + io.projectreactor + reactor-core + ${io.reactor3.version} + + + org.apache.commons + commons-collections4 + ${apache.commons.collection4.version} + + + com.google.guava + guava + ${google.guava.version} + + + com.oath.cyclops + cyclops + ${cyclops.version} + @@ -90,6 +120,12 @@ 12 1.2.5 2.2.2 + 3.1.5 + 1.0.0-alpha-4 + 3.5.1 + 4.4 + 31.1-jre + 10.4.1 \ No newline at end of file diff --git a/core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/processing/CustomBatchIterator.java b/core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/processing/CustomBatchIterator.java new file mode 100644 index 0000000000..b5407b7283 --- /dev/null +++ b/core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/processing/CustomBatchIterator.java @@ -0,0 +1,47 @@ +package com.baeldung.streams.processing; + +import static java.util.Spliterator.ORDERED; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Spliterators; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + +public class CustomBatchIterator implements Iterator> { + private final int batchSize; + private List currentBatch; + private final Iterator iterator; + + public CustomBatchIterator(Iterator sourceIterator, int batchSize) { + this.batchSize = batchSize; + this.iterator = sourceIterator; + } + + @Override + public List next() { + return currentBatch; + } + + @Override + public boolean hasNext() { + prepareNextBatch(); + return currentBatch != null && !currentBatch.isEmpty(); + } + + public static Stream> batchStreamOf(Stream stream, int batchSize) { + return stream(new CustomBatchIterator<>(stream.iterator(), batchSize)); + } + + private static Stream stream(Iterator iterator) { + return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, ORDERED), false); + } + + private void prepareNextBatch() { + currentBatch = new ArrayList<>(batchSize); + while (iterator.hasNext() && currentBatch.size() < batchSize) { + currentBatch.add(iterator.next()); + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/processing/StreamProcessingUnitTest.java b/core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/processing/StreamProcessingUnitTest.java new file mode 100644 index 0000000000..f8f88387d5 --- /dev/null +++ b/core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/processing/StreamProcessingUnitTest.java @@ -0,0 +1,141 @@ +package com.baeldung.streams.processing; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import org.apache.commons.collections4.ListUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.google.common.collect.Iterators; + +import cyclops.data.LazySeq; +import cyclops.reactive.ReactiveSeq; +import io.reactivex.rxjava3.core.Observable; +import reactor.core.publisher.Flux; + +public class StreamProcessingUnitTest { + public final int BATCH_SIZE = 10; + + private final List firstBatch = List.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + private final List secondBatch = List.of(10, 11, 12, 13, 14, 15, 16, 17, 18, 19); + private final List thirdBatch = List.of(20, 21, 22, 23, 24, 25, 26, 27, 28, 29); + private final List fourthBatch = List.of(30, 31, 32, 33); + + public Stream data; + + @BeforeEach + public void setUp() { + data = IntStream.range(0, 34) + .boxed(); + } + + @Test + public void givenAStreamOfData_whenIsProcessingInBatchUsingSpliterator_thenFourBatchesAreObtained() { + Collection> result = new ArrayList<>(); + CustomBatchIterator.batchStreamOf(data, BATCH_SIZE) + .forEach(result::add); + assertTrue(result.contains(firstBatch)); + assertTrue(result.contains(secondBatch)); + assertTrue(result.contains(thirdBatch)); + assertTrue(result.contains(fourthBatch)); + } + + @Test + public void givenAStreamOfData_whenIsProcessingInBatchUsingCollectionAPI_thenFourBatchesAreObtained() { + Collection> result = data.collect(Collectors.groupingBy(it -> it / BATCH_SIZE)) + .values(); + assertTrue(result.contains(firstBatch)); + assertTrue(result.contains(secondBatch)); + assertTrue(result.contains(thirdBatch)); + assertTrue(result.contains(fourthBatch)); + } + + @Test + public void givenAStreamOfData_whenIsProcessingInBatchParallelUsingCollectionAPI_thenFourBatchesAreObtained() { + Collection> result = data.parallel() + .collect(Collectors.groupingBy(it -> it / BATCH_SIZE)) + .values(); + assertTrue(result.contains(firstBatch)); + assertTrue(result.contains(secondBatch)); + assertTrue(result.contains(thirdBatch)); + assertTrue(result.contains(fourthBatch)); + } + + @Test + public void givenAStreamOfData_whenIsProcessingInBatchUsingRxJavaV3_thenFourBatchesAreObtained() { + // RxJava v3 + Collection> result = new ArrayList<>(); + Observable.fromStream(data) + .buffer(BATCH_SIZE) + .subscribe(result::add); + assertTrue(result.contains(firstBatch)); + assertTrue(result.contains(secondBatch)); + assertTrue(result.contains(thirdBatch)); + assertTrue(result.contains(fourthBatch)); + } + + @Test + public void givenAStreamOfData_whenIsProcessingInBatchUsingReactor_thenFourBatchesAreObtained() { + Collection> result = new ArrayList<>(); + Flux.fromStream(data) + .buffer(BATCH_SIZE) + .subscribe(result::add); + assertTrue(result.contains(firstBatch)); + assertTrue(result.contains(secondBatch)); + assertTrue(result.contains(thirdBatch)); + assertTrue(result.contains(fourthBatch)); + } + + @Test + public void givenAStreamOfData_whenIsProcessingInBatchUsingApacheCommon_thenFourBatchesAreObtained() { + Collection> result = new ArrayList<>(ListUtils.partition(data.collect(Collectors.toList()), BATCH_SIZE)); + assertTrue(result.contains(firstBatch)); + assertTrue(result.contains(secondBatch)); + assertTrue(result.contains(thirdBatch)); + assertTrue(result.contains(fourthBatch)); + } + + @Test + public void givenAStreamOfData_whenIsProcessingInBatchUsingGuava_thenFourBatchesAreObtained() { + Collection> result = new ArrayList<>(); + Iterators.partition(data.iterator(), BATCH_SIZE) + .forEachRemaining(result::add); + assertTrue(result.contains(firstBatch)); + assertTrue(result.contains(secondBatch)); + assertTrue(result.contains(thirdBatch)); + assertTrue(result.contains(fourthBatch)); + } + + @Test + public void givenAStreamOfData_whenIsProcessingInBatchUsingCyclops_thenFourBatchesAreObtained() { + Collection> result = new ArrayList<>(); + ReactiveSeq.fromStream(data) + .grouped(BATCH_SIZE) + .toList() + .forEach(value -> result.add(value.collect(Collectors.toList()))); + assertTrue(result.contains(firstBatch)); + assertTrue(result.contains(secondBatch)); + assertTrue(result.contains(thirdBatch)); + assertTrue(result.contains(fourthBatch)); + } + + @Test + public void givenAStreamOfData_whenIsProcessingInBatchUsingCyclopsLazy_thenFourBatchesAreObtained() { + Collection> result = new ArrayList<>(); + LazySeq.fromStream(data) + .grouped(BATCH_SIZE) + .toList() + .forEach(value -> result.add(value.collect(Collectors.toList()))); + assertTrue(result.contains(firstBatch)); + assertTrue(result.contains(secondBatch)); + assertTrue(result.contains(thirdBatch)); + assertTrue(result.contains(fourthBatch)); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/processing/vavr/StreamProcessingWithVavrUnitTest.java b/core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/processing/vavr/StreamProcessingWithVavrUnitTest.java new file mode 100644 index 0000000000..859b059889 --- /dev/null +++ b/core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/processing/vavr/StreamProcessingWithVavrUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.streams.processing.vavr; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +import com.baeldung.streams.processing.StreamProcessingUnitTest; + +import io.vavr.collection.List; +import io.vavr.collection.Stream; + +public class StreamProcessingWithVavrUnitTest extends StreamProcessingUnitTest { + + private final List firstBatch = List.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + private final List secondBatch = List.of(10, 11, 12, 13, 14, 15, 16, 17, 18, 19); + private final List thirdBatch = List.of(20, 21, 22, 23, 24, 25, 26, 27, 28, 29); + private final List fourthBatch = List.of(30, 31, 32, 33); + + @Test + public void givenAStreamOfData_whenIsProcessingInBatchUsingVavr_thenFourBatchesAreObtained() { + List> result = Stream.ofAll(data) + .toList() + .grouped(BATCH_SIZE) + .toList(); + assertTrue(result.contains(firstBatch)); + assertTrue(result.contains(secondBatch)); + assertTrue(result.contains(thirdBatch)); + assertTrue(result.contains(fourthBatch)); + } +} From eef1e050177ef079c7630ac4bd9eb709dbe90726 Mon Sep 17 00:00:00 2001 From: IfThen2 <57305322+IfThen2@users.noreply.github.com> Date: Wed, 18 Jan 2023 05:54:00 -0700 Subject: [PATCH 16/43] code for BAEL-5999 Converting String Object to Java Compilable Code (#13179) * code for BAEL-5999 Converting String Object to Java Compilable Code * move code from core-java-jvm-2 to core-java-jvm-3 fix unit test name fix core-java-jvm-3 test directory structure disable non-working unit tests from core-java-jvm-3 --- .../inmemorycompilation/InMemoryClass.java | 6 ++ .../InMemoryClassLoader.java | 30 ++++++++++ .../InMemoryFileManager.java | 52 +++++++++++++++++ .../inmemorycompilation/JavaClassAsBytes.java | 27 +++++++++ .../JavaSourceFromString.java | 26 +++++++++ .../InMemoryCompilationUnitTest.java | 57 +++++++++++++++++++ .../resource/ClassGetResourceUnitTest.java | 2 + .../ClassLoaderGetResourceUnitTest.java | 2 + 8 files changed, 202 insertions(+) create mode 100644 core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/InMemoryClass.java create mode 100644 core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/InMemoryClassLoader.java create mode 100644 core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/InMemoryFileManager.java create mode 100644 core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/JavaClassAsBytes.java create mode 100644 core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/JavaSourceFromString.java create mode 100644 core-java-modules/core-java-jvm-3/src/test/java/com/baeldung/inmemorycompilation/InMemoryCompilationUnitTest.java rename core-java-modules/core-java-jvm-3/{ => src}/test/java/com/baeldung/resource/ClassGetResourceUnitTest.java (93%) rename core-java-modules/core-java-jvm-3/{ => src}/test/java/com/baeldung/resource/ClassLoaderGetResourceUnitTest.java (93%) diff --git a/core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/InMemoryClass.java b/core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/InMemoryClass.java new file mode 100644 index 0000000000..c61f28bb79 --- /dev/null +++ b/core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/InMemoryClass.java @@ -0,0 +1,6 @@ +package com.baeldung.inmemorycompilation; + +public interface InMemoryClass { + + void runCode(); +} diff --git a/core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/InMemoryClassLoader.java b/core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/InMemoryClassLoader.java new file mode 100644 index 0000000000..b4951e9d91 --- /dev/null +++ b/core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/InMemoryClassLoader.java @@ -0,0 +1,30 @@ +package com.baeldung.inmemorycompilation; + +import static java.util.Objects.requireNonNull; + +import java.util.Map; + +public class InMemoryClassLoader extends ClassLoader { + + private final InMemoryFileManager manager; + + public InMemoryClassLoader(ClassLoader parent, InMemoryFileManager manager) { + super(parent); + this.manager = requireNonNull(manager, "manager must not be null"); + } + + @Override + protected Class findClass(String name) throws ClassNotFoundException { + + Map compiledClasses = manager + .getBytesMap(); + + if (compiledClasses.containsKey(name)) { + byte[] bytes = compiledClasses.get(name) + .getBytes(); + return defineClass(name, bytes, 0, bytes.length); + } else { + throw new ClassNotFoundException(); + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/InMemoryFileManager.java b/core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/InMemoryFileManager.java new file mode 100644 index 0000000000..34ad78856a --- /dev/null +++ b/core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/InMemoryFileManager.java @@ -0,0 +1,52 @@ +package com.baeldung.inmemorycompilation; + +import java.util.Hashtable; +import java.util.Map; +import javax.tools.FileObject; +import javax.tools.ForwardingJavaFileManager; +import javax.tools.JavaFileManager; +import javax.tools.JavaFileObject; +import javax.tools.JavaFileObject.Kind; +import javax.tools.StandardJavaFileManager; + +public class InMemoryFileManager extends ForwardingJavaFileManager { + + private final Map compiledClasses; + private final ClassLoader loader; + + public InMemoryFileManager(StandardJavaFileManager standardManager) { + super(standardManager); + this.compiledClasses = new Hashtable<>(); + this.loader = new InMemoryClassLoader(this.getClass() + .getClassLoader(), + this + ); + } + + /** + * Used to get the class loader for our compiled class. It creates an anonymous class extending + * the SecureClassLoader which uses the byte code created by the compiler and stored in the + * JavaClassObject, and returns the Class for it + * + * @param location where to place or search for file objects. + */ + @Override + public ClassLoader getClassLoader(Location location) { + return loader; + } + + @Override + public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, + FileObject sibling) { + + JavaClassAsBytes classAsBytes = new JavaClassAsBytes( + className, kind); + compiledClasses.put(className, classAsBytes); + + return classAsBytes; + } + + public Map getBytesMap() { + return compiledClasses; + } +} diff --git a/core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/JavaClassAsBytes.java b/core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/JavaClassAsBytes.java new file mode 100644 index 0000000000..b7af9a76ba --- /dev/null +++ b/core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/JavaClassAsBytes.java @@ -0,0 +1,27 @@ +package com.baeldung.inmemorycompilation; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.net.URI; +import javax.tools.SimpleJavaFileObject; + +/** + * Represents a Java class file (compiled byte-code) + */ +public class JavaClassAsBytes extends SimpleJavaFileObject { + + protected final ByteArrayOutputStream bos = new ByteArrayOutputStream(); + + public JavaClassAsBytes(String name, Kind kind) { + super(URI.create("string:///" + name.replace('.', '/') + kind.extension), kind); + } + + public byte[] getBytes() { + return bos.toByteArray(); + } + + @Override + public OutputStream openOutputStream() { + return bos; + } +} diff --git a/core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/JavaSourceFromString.java b/core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/JavaSourceFromString.java new file mode 100644 index 0000000000..eaa6c21b54 --- /dev/null +++ b/core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/inmemorycompilation/JavaSourceFromString.java @@ -0,0 +1,26 @@ +package com.baeldung.inmemorycompilation; + +import static java.util.Objects.requireNonNull; + +import java.net.URI; +import javax.tools.SimpleJavaFileObject; + +/** + * Represents a Java source code file + */ +public class JavaSourceFromString extends SimpleJavaFileObject { + + private final String sourceCode; + + public JavaSourceFromString(String name, String sourceCode) { + super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension), + Kind.SOURCE + ); + this.sourceCode = requireNonNull(sourceCode, "sourceCode must not be null"); + } + + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors) { + return sourceCode; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-jvm-3/src/test/java/com/baeldung/inmemorycompilation/InMemoryCompilationUnitTest.java b/core-java-modules/core-java-jvm-3/src/test/java/com/baeldung/inmemorycompilation/InMemoryCompilationUnitTest.java new file mode 100644 index 0000000000..410bdca866 --- /dev/null +++ b/core-java-modules/core-java-jvm-3/src/test/java/com/baeldung/inmemorycompilation/InMemoryCompilationUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.inmemorycompilation; + +import java.util.Collections; +import java.util.List; + +import javax.tools.DiagnosticCollector; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.ToolProvider; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class InMemoryCompilationUnitTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(InMemoryCompilationUnitTest.class); + + final static String QUALIFIED_CLASS_NAME = "com.baeldung.inmemorycompilation.TestClass"; + + final static String SOURCE_CODE = + "package com.baeldung.inmemorycompilation;\n" + + "public class TestClass implements InMemoryClass {\n" + + "@Override\n" + + " public void runCode() {\n" + + " System.out.println(\"code is running...\");\n" + + " }\n" + + "}\n"; + + @Test + public void whenStringIsCompiled_ThenCodeShouldExecute() throws ClassNotFoundException, InstantiationException, IllegalAccessException { + + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + InMemoryFileManager manager = new InMemoryFileManager(compiler.getStandardFileManager(null, null, null)); + + List sourceFiles = Collections.singletonList(new JavaSourceFromString(QUALIFIED_CLASS_NAME, SOURCE_CODE)); + + JavaCompiler.CompilationTask task = compiler.getTask(null, manager, diagnostics, null, null, sourceFiles); + + boolean result = task.call(); + + if (result) { + diagnostics.getDiagnostics() + .forEach(d -> LOGGER.error(String.valueOf(d))); + } else { + ClassLoader classLoader = manager.getClassLoader(null); + Class clazz = classLoader.loadClass(QUALIFIED_CLASS_NAME); + InMemoryClass instanceOfClass = (InMemoryClass) clazz.newInstance(); + + Assertions.assertInstanceOf(InMemoryClass.class, instanceOfClass); + + instanceOfClass.runCode(); + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-jvm-3/test/java/com/baeldung/resource/ClassGetResourceUnitTest.java b/core-java-modules/core-java-jvm-3/src/test/java/com/baeldung/resource/ClassGetResourceUnitTest.java similarity index 93% rename from core-java-modules/core-java-jvm-3/test/java/com/baeldung/resource/ClassGetResourceUnitTest.java rename to core-java-modules/core-java-jvm-3/src/test/java/com/baeldung/resource/ClassGetResourceUnitTest.java index fb0c88f4bb..2fe512384a 100644 --- a/core-java-modules/core-java-jvm-3/test/java/com/baeldung/resource/ClassGetResourceUnitTest.java +++ b/core-java-modules/core-java-jvm-3/src/test/java/com/baeldung/resource/ClassGetResourceUnitTest.java @@ -1,10 +1,12 @@ package com.baeldung.resource; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.net.URL; +@Disabled class ClassGetResourceUnitTest { @Test diff --git a/core-java-modules/core-java-jvm-3/test/java/com/baeldung/resource/ClassLoaderGetResourceUnitTest.java b/core-java-modules/core-java-jvm-3/src/test/java/com/baeldung/resource/ClassLoaderGetResourceUnitTest.java similarity index 93% rename from core-java-modules/core-java-jvm-3/test/java/com/baeldung/resource/ClassLoaderGetResourceUnitTest.java rename to core-java-modules/core-java-jvm-3/src/test/java/com/baeldung/resource/ClassLoaderGetResourceUnitTest.java index 54025c5404..d2d0600165 100644 --- a/core-java-modules/core-java-jvm-3/test/java/com/baeldung/resource/ClassLoaderGetResourceUnitTest.java +++ b/core-java-modules/core-java-jvm-3/src/test/java/com/baeldung/resource/ClassLoaderGetResourceUnitTest.java @@ -1,10 +1,12 @@ package com.baeldung.resource; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.net.URL; +@Disabled class ClassLoaderGetResourceUnitTest { @Test 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 17/43] 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 18/43] 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 19/43] 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 20/43] 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 21/43] 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 22/43] 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 23/43] 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 24/43] 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 25/43] 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 fd1c28657032e30d25840730519a238fe24e52f3 Mon Sep 17 00:00:00 2001 From: Bhaskar Ghosh Dastidar Date: Thu, 19 Jan 2023 08:23:05 +0530 Subject: [PATCH 26/43] [JAVA-5730] convert list of objects to list of strings (#13166) * [JAVA-5730] convert list of objects to list of strings * [JAVA-5730] added new unit tests with null and non-null lists. modified pom.xml with java version to 16 * [JAVA-5730] simplified User class and formatted the codebase * [JAVA-5730] added module in jdk-9 and above profile * [JAVA-5730] removed arraylist module from other profiles of core-java pom * [JAVA-5730] java util opened for reflection surefire plugin Co-authored-by: Bhaskar --- .../core-java-collections-array-list/pom.xml | 33 +++++++ .../listofobjectstolistofstring/Node.java | 17 ++++ .../listofobjectstolistofstring/User.java | 14 +++ ...ConvertObjectListToStringListUnitTest.java | 92 +++++++++++++++++++ core-java-modules/pom.xml | 1 - pom.xml | 1 + 6 files changed, 157 insertions(+), 1 deletion(-) create mode 100644 core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/listofobjectstolistofstring/Node.java create mode 100644 core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/listofobjectstolistofstring/User.java create mode 100644 core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/listofobjectstolistofstring/ConvertObjectListToStringListUnitTest.java diff --git a/core-java-modules/core-java-collections-array-list/pom.xml b/core-java-modules/core-java-collections-array-list/pom.xml index 6b040739e8..e3a115854c 100644 --- a/core-java-modules/core-java-collections-array-list/pom.xml +++ b/core-java-modules/core-java-collections-array-list/pom.xml @@ -5,6 +5,33 @@ 4.0.0 core-java-collections-array-list 0.1.0-SNAPSHOT + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${maven-compiler-plugin.source} + ${maven-compiler-plugin.target} + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire.plugin.version} + + + --add-opens java.base/java.util=ALL-UNNAMED + + + + + + + 16 + 16 + 3.0.0-M3 + core-java-collections-array-list jar @@ -20,6 +47,12 @@ commons-collections4 ${commons-collections4.version} + + com.google.guava + guava + 31.1-jre + test + \ No newline at end of file diff --git a/core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/listofobjectstolistofstring/Node.java b/core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/listofobjectstolistofstring/Node.java new file mode 100644 index 0000000000..3e2c5693de --- /dev/null +++ b/core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/listofobjectstolistofstring/Node.java @@ -0,0 +1,17 @@ +package com.baeldung.listofobjectstolistofstring; + +public class Node { + + private final int x; + private final int y; + + public Node(int x, int y) { + this.x = x; + this.y = y; + } + + @Override + public String toString() { + return "Node (" + "x=" + x + ", y=" + y + ')'; + } +} diff --git a/core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/listofobjectstolistofstring/User.java b/core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/listofobjectstolistofstring/User.java new file mode 100644 index 0000000000..eb9298bce0 --- /dev/null +++ b/core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/listofobjectstolistofstring/User.java @@ -0,0 +1,14 @@ +package com.baeldung.listofobjectstolistofstring; + +public class User { + private final String fullName; + + public User(String fullName) { + this.fullName = fullName; + } + + @Override + public String toString() { + return "User (" + "full name='" + fullName + ')'; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/listofobjectstolistofstring/ConvertObjectListToStringListUnitTest.java b/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/listofobjectstolistofstring/ConvertObjectListToStringListUnitTest.java new file mode 100644 index 0000000000..1d393a2945 --- /dev/null +++ b/core-java-modules/core-java-collections-array-list/src/test/java/com/baeldung/listofobjectstolistofstring/ConvertObjectListToStringListUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.listofobjectstolistofstring; + +import com.google.common.collect.Lists; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +public class ConvertObjectListToStringListUnitTest { + + @Test + public void givenObjectList_whenForEachUsedToConvert_thenReturnSuccess() { + List outputList = new ArrayList<>(objectListWithNull().size()); + for (Object obj : objectListWithNull()) { + outputList.add(Objects.toString(obj, null)); + } + Assert.assertEquals(expectedStringListWithNull(), outputList); + } + + @Test + public void givenObjectList_whenUsingStreamsToConvert_thenReturnSuccess() { + List outputList; + outputList = objectListWithNull().stream() + .map((obj) -> Objects.toString(obj, null)) + .collect(Collectors.toList()); + Assert.assertEquals(expectedStringListWithNull(), outputList); + + } + + @Test + public void givenObjectList_whenUsingStreamsUnmodifiableListToConvert_thenReturnSuccess() { + List outputList; + outputList = objectListWithNull().stream() + .filter(Objects::nonNull) + .map((obj) -> Objects.toString(obj, null)) + .collect(Collectors.toUnmodifiableList()); + Assert.assertEquals(expectedStringListWithoutNull(), outputList); + + } + + @Test + public void givenObjectList_whenUsingGuavaTransform_thenReturnSuccess() { + List outputList; + outputList = Lists.transform(objectListWithNull(), obj -> Objects.toString(obj, null)); + Assert.assertEquals(expectedStringListWithNull(), outputList); + } + + @Test + public void givenObjectListWithNoNull_whenUsingToList_thenReturnSuccess() { + List outputList; + outputList = objectListWithoutNull().stream() + .map((obj) -> Objects.toString(obj, null)) + .toList(); + Assert.assertEquals(expectedStringListWithoutNull(), outputList); + } + + private List expectedStringListWithNull() { + List listOfStrings = new ArrayList<>(); + listOfStrings.add("1"); + listOfStrings.add("true"); + listOfStrings.add("hello"); + listOfStrings.add(Double.toString(273773.98)); + listOfStrings.add(null); + listOfStrings.add(new Node(2, 4).toString()); + listOfStrings.add(new User("John Doe").toString()); + return listOfStrings; + } + + private List objectListWithNull() { + List listOfStrings = new ArrayList<>(); + listOfStrings.add(1); + listOfStrings.add(true); + listOfStrings.add("hello"); + listOfStrings.add(Double.valueOf(273773.98)); + listOfStrings.add(null); + listOfStrings.add(new Node(2, 4)); + listOfStrings.add(new User("John Doe")); + return listOfStrings; + } + + private List expectedStringListWithoutNull() { + return List.of("1", "true", "hello", Double.toString(273773.98), new Node(2, 4).toString(), new User("John Doe").toString()); + } + + private List objectListWithoutNull() { + return List.of(1, true, "hello", Double.valueOf(273773.98), new Node(2, 4), new User("John Doe")); + } +} diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index cc137d08b6..bbbca6adf5 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -31,7 +31,6 @@ core-java-collections-2 core-java-collections-3 core-java-collections-4 - core-java-collections-array-list core-java-collections-conversions core-java-collections-conversions-2 core-java-collections-set-2 diff --git a/pom.xml b/pom.xml index c4e5c25d9d..0b19c6eee6 100644 --- a/pom.xml +++ b/pom.xml @@ -1133,6 +1133,7 @@ core-java-modules/core-java-collections-set core-java-modules/core-java-collections-list-4 + core-java-modules/core-java-collections-array-list core-java-modules/core-java-collections-maps-4 core-java-modules/core-java-collections-maps-5 core-java-modules/core-java-concurrency-simple From caa663239f09d534e08686a2933525833ce8524f Mon Sep 17 00:00:00 2001 From: Muhammad Asif Date: Thu, 19 Jan 2023 10:32:40 +0500 Subject: [PATCH 27/43] muasif80@gmail.com (#13262) * BAEL-6063 * Updated the unit test class name * Fixed the test * Made updates to method names for tests and some refactor of code * Updated the formatting using Baeldung formatter for Java * Removed the space around = and made line continuations 2 spaces --- .../data/persistence/search/Student.java | 75 +++++++++++++ .../search/StudentApplication.java | 16 +++ .../persistence/search/StudentRepository.java | 31 ++++++ .../src/main/resources/application.properties | 1 + .../search/StudentApplicationUnitTest.java | 100 ++++++++++++++++++ 5 files changed, 223 insertions(+) create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/search/Student.java create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/search/StudentApplication.java create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/search/StudentRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/search/StudentApplicationUnitTest.java diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/search/Student.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/search/Student.java new file mode 100644 index 0000000000..1d6eaa3b33 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/search/Student.java @@ -0,0 +1,75 @@ +package com.baeldung.spring.data.persistence.search; + +import java.util.Objects; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + private String name; + private int score; + + public Student() { + } + + public Student(String name, int score) { + + this.name = name; + this.score = score; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getScore() { + return score; + } + + public void setScore(int score) { + this.score = score; + } + + @Override + public String toString() { + return "Student [id=" + id + ", name=" + name + ", score=" + score + "]"; + } + + @Override + public int hashCode() { + return Objects.hash(id, name, score); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Student other = (Student) obj; + return id == other.id && Objects.equals(name, other.name) && score == other.score; + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/search/StudentApplication.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/search/StudentApplication.java new file mode 100644 index 0000000000..6aa895d067 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/search/StudentApplication.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.data.persistence.search; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class StudentApplication { + + private static final Logger log = LoggerFactory.getLogger(StudentApplication.class); + + public static void main(String[] args) { + SpringApplication.run(StudentApplication.class, args); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/search/StudentRepository.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/search/StudentRepository.java new file mode 100644 index 0000000000..29aade5886 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/search/StudentRepository.java @@ -0,0 +1,31 @@ +package com.baeldung.spring.data.persistence.search; + +import java.util.List; + +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface StudentRepository extends JpaRepository { + + Student findFirstByOrderByScoreDesc(); + + Student findFirstBy(Sort sort); + + Student findFirstByNameLike(String name, Sort sort); + + List findFirst3ByOrderByScoreDesc(); + + List findFirst2ByScoreBetween(int startScore, int endScore, Sort sort); + + Student findTopByOrderByScoreDesc(); + + Student findTopBy(Sort sort); + + Student findTopByNameLike(String name, Sort sort); + + List findTop3ByOrderByScoreDesc(); + + List findTop2ByScoreBetween(int startScore, int endScore, Sort sort); +} diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/application.properties index 30cc5abbcc..3ca0cc1242 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/resources/application.properties +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/application.properties @@ -3,3 +3,4 @@ spring.datasource.username=sa spring.datasource.password=sa spring.jpa.properties.hibernate.globally_quoted_identifiers=true +logging.level.com.baeldung.spring.data.persistence.search=debug \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/search/StudentApplicationUnitTest.java b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/search/StudentApplicationUnitTest.java new file mode 100644 index 0000000000..ea16b3597d --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/search/StudentApplicationUnitTest.java @@ -0,0 +1,100 @@ +package com.baeldung.spring.data.persistence.search; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Random; +import java.util.stream.Collectors; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.domain.Sort; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class StudentApplicationUnitTest { + + @Autowired + private StudentRepository studentRepo; + private List students; + + @Before + public void fillData() { + students = new ArrayList<>(); + int count = 10; + Random r = new Random(); + List scores = r.ints(0, 101) + .distinct() + .limit(count) + .boxed() + .collect(Collectors.toList()); + + for (int i = 0; i < count; i++) { + Integer score = scores.get(i); + Student s = new Student("Student-" + i, score); + students.add(s); + } + + studentRepo.saveAll(students); + Comparator c = Comparator.comparing(a -> a.getScore()); + c = c.reversed(); + students.sort(c); + } + + @After + public void clearData() { + studentRepo.deleteAll(); + } + + @Test + public void givenStudentScores_whenMoreThanOne_thenFindFirst() { + + Student student = studentRepo.findFirstByOrderByScoreDesc(); + Student s = students.get(0); + assertEquals(student, s); + } + + @Test + public void givenStudentScores_whenMoreThan3_thenFindFirstThree() { + + List firstThree = studentRepo.findFirst3ByOrderByScoreDesc(); + List sList = students.subList(0, 3); + assertArrayEquals(firstThree.toArray(), sList.toArray()); + } + + @Test + public void givenStudentScores_whenNameMatches_thenFindFirstStudent() { + + String matchString = "3"; + Student student = studentRepo.findFirstByNameLike("%" + matchString + "%", Sort.by("score") + .descending()); + Student s = students.stream() + .filter(a -> a.getName() + .contains(matchString)) + .findFirst() + .orElse(null); + assertEquals(student, s); + } + + @Test + public void givenStudentScores_whenBetweenRange_thenFindFirstTwoStudents() { + + List topTwoBetweenRange = studentRepo.findFirst2ByScoreBetween(50, 60, Sort.by("score") + .descending()); + List _students = students.stream() + .filter(a -> a.getScore() >= 50 && a.getScore() <= 60) + .limit(2) + .collect(Collectors.toList()); + assertArrayEquals(_students.toArray(), topTwoBetweenRange.toArray()); + } +} 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 28/43] 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 29/43] 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 30/43] 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 31/43] [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 32/43] 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 33/43] 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 34/43] 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 35/43] 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 36/43] 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 37/43] 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 38/43] 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 39/43] 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 40/43] 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 41/43] 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 42/43] 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 43/43] 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)