diff --git a/.gitignore b/.gitignore index 5dc7abec6a..7f1bab3751 100644 --- a/.gitignore +++ b/.gitignore @@ -107,4 +107,11 @@ spring-boot-modules/spring-boot-properties-3/*.log .sdkmanrc # Localstack -**/.localstack \ No newline at end of file +**/.localstack + +#libraries-2 +libraries-2/employee* +libraries-2/src/test/resources/crawler4j/** + +#web-modules/ninja +devDb*.db \ No newline at end of file diff --git a/apache-cxf-modules/cxf-introduction/pom.xml b/apache-cxf-modules/cxf-introduction/pom.xml index fe7b917c6f..fdcd100cc5 100644 --- a/apache-cxf-modules/cxf-introduction/pom.xml +++ b/apache-cxf-modules/cxf-introduction/pom.xml @@ -23,6 +23,16 @@ cxf-rt-transports-http-jetty ${cxf.version} + + jakarta.xml.ws + jakarta.xml.ws-api + ${jakarta-xml.version} + + + jakarta.jws + jakarta.jws-api + ${jakarta.jws.version} + @@ -37,4 +47,10 @@ + + 4.0.0 + 4.0.0 + 3.0.0 + + \ No newline at end of file diff --git a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Baeldung.java b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Baeldung.java index 472d38b8e1..cd482af0db 100644 --- a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Baeldung.java +++ b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Baeldung.java @@ -2,8 +2,8 @@ package com.baeldung.cxf.introduction; import java.util.Map; -import javax.jws.WebService; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import jakarta.jws.WebService; +import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; @WebService public interface Baeldung { diff --git a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/BaeldungImpl.java b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/BaeldungImpl.java index 240f6bb1da..04a6243cc2 100644 --- a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/BaeldungImpl.java +++ b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/BaeldungImpl.java @@ -3,7 +3,7 @@ package com.baeldung.cxf.introduction; import java.util.LinkedHashMap; import java.util.Map; -import javax.jws.WebService; +import jakarta.jws.WebService; @WebService(endpointInterface = "com.baeldung.cxf.introduction.Baeldung") public class BaeldungImpl implements Baeldung { diff --git a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java index 2ac649f4c5..f00a64a055 100644 --- a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java +++ b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java @@ -1,6 +1,6 @@ package com.baeldung.cxf.introduction; -import javax.xml.ws.Endpoint; +import jakarta.xml.ws.Endpoint; public class Server { public static void main(String args[]) throws InterruptedException { diff --git a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Student.java b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Student.java index cad8f94d97..0605956bbc 100644 --- a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Student.java +++ b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Student.java @@ -1,6 +1,6 @@ package com.baeldung.cxf.introduction; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter; @XmlJavaTypeAdapter(StudentAdapter.class) public interface Student { diff --git a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentAdapter.java b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentAdapter.java index 29b829d808..7885c953a5 100644 --- a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentAdapter.java +++ b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentAdapter.java @@ -1,6 +1,6 @@ package com.baeldung.cxf.introduction; -import javax.xml.bind.annotation.adapters.XmlAdapter; +import jakarta.xml.bind.annotation.adapters.XmlAdapter; public class StudentAdapter extends XmlAdapter { public StudentImpl marshal(Student student) throws Exception { diff --git a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentImpl.java b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentImpl.java index bc9dd27afe..041418befb 100644 --- a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentImpl.java +++ b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentImpl.java @@ -1,6 +1,6 @@ package com.baeldung.cxf.introduction; -import javax.xml.bind.annotation.XmlType; +import jakarta.xml.bind.annotation.XmlType; @XmlType(name = "Student") public class StudentImpl implements Student { diff --git a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMap.java b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMap.java index 4c40886c42..aa17b0cf4f 100644 --- a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMap.java +++ b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMap.java @@ -3,8 +3,8 @@ package com.baeldung.cxf.introduction; import java.util.ArrayList; import java.util.List; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlType; @XmlType(name = "StudentMap") public class StudentMap { diff --git a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMapAdapter.java b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMapAdapter.java index f156676a5f..3bf1bfd2ff 100644 --- a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMapAdapter.java +++ b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMapAdapter.java @@ -3,7 +3,7 @@ package com.baeldung.cxf.introduction; import java.util.LinkedHashMap; import java.util.Map; -import javax.xml.bind.annotation.adapters.XmlAdapter; +import jakarta.xml.bind.annotation.adapters.XmlAdapter; public class StudentMapAdapter extends XmlAdapter> { public StudentMap marshal(Map boundMap) throws Exception { diff --git a/apache-cxf-modules/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java b/apache-cxf-modules/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java index 60fc0a10e7..89b127a742 100644 --- a/apache-cxf-modules/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java +++ b/apache-cxf-modules/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java @@ -5,8 +5,8 @@ import static org.junit.Assert.assertEquals; import java.util.Map; import javax.xml.namespace.QName; -import javax.xml.ws.Service; -import javax.xml.ws.soap.SOAPBinding; +import jakarta.xml.ws.Service; +import jakarta.xml.ws.soap.SOAPBinding; import org.junit.Before; import org.junit.Test; diff --git a/apache-cxf-modules/cxf-jaxrs-implementation/pom.xml b/apache-cxf-modules/cxf-jaxrs-implementation/pom.xml index cc5eba4025..8418853b1e 100644 --- a/apache-cxf-modules/cxf-jaxrs-implementation/pom.xml +++ b/apache-cxf-modules/cxf-jaxrs-implementation/pom.xml @@ -16,12 +16,28 @@ org.apache.cxf cxf-rt-frontend-jaxrs - ${cxf.version} + 4.0.0 org.apache.cxf cxf-rt-transports-http-jetty - ${cxf.version} + 4.0.0 + + + jakarta.xml.ws + jakarta.xml.ws-api + ${jakarta-xml.version} + + + jakarta.jws + jakarta.jws-api + ${jakarta-jws.version} + + + jakarta.platform + jakarta.jakartaee-web-api + ${jakarta-platform.version} + compile org.apache.httpcomponents @@ -50,6 +66,9 @@ 4.5.2 + 4.0.0 + 3.0.0 + 9.0.0 \ No newline at end of file diff --git a/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java b/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java index dba9b9c661..9f2ba2e837 100644 --- a/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java +++ b/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java @@ -1,8 +1,8 @@ package com.baeldung.cxf.jaxrs.implementation; -import javax.ws.rs.*; -import javax.ws.rs.core.Response; -import javax.xml.bind.annotation.XmlRootElement; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.Response; +import jakarta.xml.bind.annotation.XmlRootElement; import java.util.ArrayList; import java.util.List; diff --git a/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java b/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java index a2fd6be435..e527180440 100644 --- a/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java +++ b/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java @@ -1,7 +1,7 @@ package com.baeldung.cxf.jaxrs.implementation; -import javax.ws.rs.*; -import javax.ws.rs.core.Response; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.Response; import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java b/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java index bd3dad0f5e..f6c4e32cdd 100644 --- a/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java +++ b/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java @@ -1,6 +1,6 @@ package com.baeldung.cxf.jaxrs.implementation; -import javax.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "Student") public class Student { diff --git a/apache-cxf-modules/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java b/apache-cxf-modules/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java index 29c34ae16b..a9f71930f2 100644 --- a/apache-cxf-modules/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java +++ b/apache-cxf-modules/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java @@ -7,7 +7,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; -import javax.xml.bind.JAXB; +import jakarta.xml.bind.JAXB; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpDelete; diff --git a/apache-cxf-modules/cxf-spring/pom.xml b/apache-cxf-modules/cxf-spring/pom.xml index ebbebd7f3b..1c87ae4bfb 100644 --- a/apache-cxf-modules/cxf-spring/pom.xml +++ b/apache-cxf-modules/cxf-spring/pom.xml @@ -40,10 +40,22 @@ spring-webmvc ${spring.version} + + com.sun.xml.ws + jaxws-ri + 2.3.3 + pom + javax.servlet javax.servlet-api - ${javax.servlet-api.version} + 4.0.1 + provided + + + javax.servlet + jstl + 1.2 @@ -103,8 +115,9 @@ - 4.3.4.RELEASE + 5.3.25 1.6.1 + 3.3.2 \ No newline at end of file diff --git a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/pom.xml b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/pom.xml index 26c8a87c2b..ce2b0059c3 100644 --- a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/pom.xml +++ b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/pom.xml @@ -23,6 +23,11 @@ cxf-rt-rs-sse ${cxf-version} + + jakarta.ws.rs + jakarta.ws.rs-api + ${jakarta-ws.version} + @@ -55,7 +60,8 @@ - 3.2.0 + 4.0.0 + 3.1.0 \ No newline at end of file diff --git a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java index 5d42b3a243..af9a9c7691 100644 --- a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java +++ b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java @@ -1,10 +1,10 @@ package com.baeldung.sse.jaxrs.client; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.sse.InboundSseEvent; -import javax.ws.rs.sse.SseEventSource; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; +import jakarta.ws.rs.client.WebTarget; +import jakarta.ws.rs.sse.InboundSseEvent; +import jakarta.ws.rs.sse.SseEventSource; import java.util.function.Consumer; public class SseClientApp { diff --git a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java index 9afc187a6d..4e3c236437 100644 --- a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java +++ b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java @@ -1,10 +1,10 @@ package com.baeldung.sse.jaxrs.client; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.sse.InboundSseEvent; -import javax.ws.rs.sse.SseEventSource; +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; +import jakarta.ws.rs.client.WebTarget; +import jakarta.ws.rs.sse.InboundSseEvent; +import jakarta.ws.rs.sse.SseEventSource; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; diff --git a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/pom.xml b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/pom.xml index 0467fd9e5d..3bd3e5cb27 100644 --- a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/pom.xml +++ b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/pom.xml @@ -15,16 +15,14 @@ - javax.ws.rs - javax.ws.rs-api - ${rs-api.version} - provided + jakarta.ws.rs + jakarta.ws.rs-api + ${jakarta-ws.version} - javax.enterprise - cdi-api - ${cdi-api.version} - provided + jakarta.enterprise + jakarta.enterprise.cdi-api + ${jakarta-cdi-api} javax.json.bind @@ -37,6 +35,11 @@ ${project.artifactId} + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + net.wasdev.wlp.maven.plugins liberty-maven-plugin @@ -78,9 +81,10 @@ 2.4.2 false 18.0.0.2 - 2.1 - 2.0 + 3.1.0 + 4.0.1 1.0 + 3.3.2 \ No newline at end of file diff --git a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java index 058d19f045..fdd1af632c 100644 --- a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java +++ b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java @@ -1,7 +1,7 @@ package com.baeldung.sse.jaxrs; -import javax.ws.rs.ApplicationPath; -import javax.ws.rs.core.Application; +import jakarta.ws.rs.ApplicationPath; +import jakarta.ws.rs.core.Application; @ApplicationPath("sse") public class AppConfig extends Application { diff --git a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java index 1f60168a1b..3e211f109b 100644 --- a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java +++ b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java @@ -1,15 +1,15 @@ package com.baeldung.sse.jaxrs; -import javax.enterprise.context.ApplicationScoped; -import javax.inject.Inject; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.sse.OutboundSseEvent; -import javax.ws.rs.sse.Sse; -import javax.ws.rs.sse.SseBroadcaster; -import javax.ws.rs.sse.SseEventSink; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.sse.OutboundSseEvent; +import jakarta.ws.rs.sse.Sse; +import jakarta.ws.rs.sse.SseBroadcaster; +import jakarta.ws.rs.sse.SseEventSink; @ApplicationScoped @Path("stock") diff --git a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java index 15818ead5d..721ef35678 100644 --- a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java +++ b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java @@ -1,11 +1,11 @@ package com.baeldung.sse.jaxrs; -import javax.enterprise.context.ApplicationScoped; -import javax.enterprise.context.Initialized; -import javax.enterprise.event.Event; -import javax.enterprise.event.Observes; -import javax.inject.Inject; -import javax.inject.Named; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.context.Initialized; +import jakarta.enterprise.event.Event; +import jakarta.enterprise.event.Observes; +import jakarta.inject.Inject; +import jakarta.inject.Named; import java.math.BigDecimal; import java.math.RoundingMode; import java.time.LocalDateTime; diff --git a/httpclient4/.gitignore b/apache-httpclient4/.gitignore similarity index 100% rename from httpclient4/.gitignore rename to apache-httpclient4/.gitignore diff --git a/httpclient4/README.md b/apache-httpclient4/README.md similarity index 96% rename from httpclient4/README.md rename to apache-httpclient4/README.md index 445db1108b..25791d05e6 100644 --- a/httpclient4/README.md +++ b/apache-httpclient4/README.md @@ -1,4 +1,4 @@ -## Apache HttpClient +## Apache HttpClient 4 This module contains articles about Apache HttpClient 4.5 diff --git a/httpclient4/pom.xml b/apache-httpclient4/pom.xml similarity index 99% rename from httpclient4/pom.xml rename to apache-httpclient4/pom.xml index 8f896283b3..6b449e3be1 100644 --- a/httpclient4/pom.xml +++ b/apache-httpclient4/pom.xml @@ -3,9 +3,9 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - httpclient4 + apache-httpclient4 0.1-SNAPSHOT - httpclient4 + apache-httpclient4 war diff --git a/httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java b/apache-httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java similarity index 100% rename from httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java rename to apache-httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java diff --git a/httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java b/apache-httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java similarity index 100% rename from httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java rename to apache-httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java diff --git a/httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java b/apache-httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java similarity index 100% rename from httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java rename to apache-httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java diff --git a/httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java b/apache-httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java similarity index 100% rename from httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java rename to apache-httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java diff --git a/httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java b/apache-httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java similarity index 100% rename from httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java rename to apache-httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java diff --git a/httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java b/apache-httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java similarity index 100% rename from httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java rename to apache-httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java diff --git a/httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java b/apache-httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java similarity index 100% rename from httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java rename to apache-httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java diff --git a/httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java b/apache-httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java similarity index 100% rename from httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java rename to apache-httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java diff --git a/httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java b/apache-httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java similarity index 100% rename from httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java rename to apache-httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java diff --git a/httpclient4/src/main/java/com/baeldung/spring/WebConfig.java b/apache-httpclient4/src/main/java/com/baeldung/spring/WebConfig.java similarity index 100% rename from httpclient4/src/main/java/com/baeldung/spring/WebConfig.java rename to apache-httpclient4/src/main/java/com/baeldung/spring/WebConfig.java diff --git a/httpclient4/src/main/java/com/baeldung/web/controller/BarController.java b/apache-httpclient4/src/main/java/com/baeldung/web/controller/BarController.java similarity index 100% rename from httpclient4/src/main/java/com/baeldung/web/controller/BarController.java rename to apache-httpclient4/src/main/java/com/baeldung/web/controller/BarController.java diff --git a/httpclient4/src/main/java/com/baeldung/web/controller/FooController.java b/apache-httpclient4/src/main/java/com/baeldung/web/controller/FooController.java similarity index 100% rename from httpclient4/src/main/java/com/baeldung/web/controller/FooController.java rename to apache-httpclient4/src/main/java/com/baeldung/web/controller/FooController.java diff --git a/httpclient4/src/main/java/com/baeldung/web/dto/Bar.java b/apache-httpclient4/src/main/java/com/baeldung/web/dto/Bar.java similarity index 100% rename from httpclient4/src/main/java/com/baeldung/web/dto/Bar.java rename to apache-httpclient4/src/main/java/com/baeldung/web/dto/Bar.java diff --git a/httpclient4/src/main/java/com/baeldung/web/dto/Foo.java b/apache-httpclient4/src/main/java/com/baeldung/web/dto/Foo.java similarity index 100% rename from httpclient4/src/main/java/com/baeldung/web/dto/Foo.java rename to apache-httpclient4/src/main/java/com/baeldung/web/dto/Foo.java diff --git a/httpclient4/src/main/resources/logback.xml b/apache-httpclient4/src/main/resources/logback.xml similarity index 100% rename from httpclient4/src/main/resources/logback.xml rename to apache-httpclient4/src/main/resources/logback.xml diff --git a/httpclient4/src/main/resources/webSecurityConfig.xml b/apache-httpclient4/src/main/resources/webSecurityConfig.xml similarity index 100% rename from httpclient4/src/main/resources/webSecurityConfig.xml rename to apache-httpclient4/src/main/resources/webSecurityConfig.xml diff --git a/httpclient4/src/main/webapp/WEB-INF/api-servlet.xml b/apache-httpclient4/src/main/webapp/WEB-INF/api-servlet.xml similarity index 100% rename from httpclient4/src/main/webapp/WEB-INF/api-servlet.xml rename to apache-httpclient4/src/main/webapp/WEB-INF/api-servlet.xml diff --git a/httpclient4/src/main/webapp/WEB-INF/web.xml b/apache-httpclient4/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from httpclient4/src/main/webapp/WEB-INF/web.xml rename to apache-httpclient4/src/main/webapp/WEB-INF/web.xml diff --git a/httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java similarity index 100% rename from httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java rename to apache-httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java diff --git a/httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java b/apache-httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java similarity index 100% rename from httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java rename to apache-httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java diff --git a/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java similarity index 100% rename from httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java rename to apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java diff --git a/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java similarity index 100% rename from httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java rename to apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java diff --git a/httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java similarity index 100% rename from httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java rename to apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java diff --git a/httpclient4/src/test/java/com/baeldung/httpclient/ResponseUtil.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/ResponseUtil.java similarity index 100% rename from httpclient4/src/test/java/com/baeldung/httpclient/ResponseUtil.java rename to apache-httpclient4/src/test/java/com/baeldung/httpclient/ResponseUtil.java diff --git a/httpclient4/src/test/resources/.gitignore b/apache-httpclient4/src/test/resources/.gitignore similarity index 100% rename from httpclient4/src/test/resources/.gitignore rename to apache-httpclient4/src/test/resources/.gitignore diff --git a/httpclient4/src/test/resources/test.in b/apache-httpclient4/src/test/resources/test.in similarity index 100% rename from httpclient4/src/test/resources/test.in rename to apache-httpclient4/src/test/resources/test.in diff --git a/apache-libraries/pom.xml b/apache-libraries/pom.xml index 3d78869865..b6418e6a04 100644 --- a/apache-libraries/pom.xml +++ b/apache-libraries/pom.xml @@ -118,11 +118,6 @@ curator-recipes ${curator.version} - - org.apache.zookeeper - zookeeper - ${zookeeper.version} - com.fasterxml.jackson.core jackson-core @@ -191,10 +186,8 @@ - 1.8 - 1.8 1.8.2 - 2.19.0 + 2.45.0 1.1.2 1.1.0.Final 1.2.0 diff --git a/core-groovy-modules/core-groovy-2/README.md b/core-groovy-modules/core-groovy-2/README.md index 9f81ac6c16..f128b43092 100644 --- a/core-groovy-modules/core-groovy-2/README.md +++ b/core-groovy-modules/core-groovy-2/README.md @@ -14,4 +14,4 @@ This module contains articles about core Groovy concepts - [A Quick Guide to Working with Web Services in Groovy](https://www.baeldung.com/groovy-web-services) - [Categories in Groovy](https://www.baeldung.com/groovy-categories) - [How to Determine the Data Type in Groovy](https://www.baeldung.com/groovy-determine-data-type) -- [[<-- Prev]](/core-groovy) +- [[<-- Prev]](/core-groovy-modules/core-groovy) diff --git a/core-groovy-modules/core-groovy-2/pom.xml b/core-groovy-modules/core-groovy-2/pom.xml index a177844a15..ca6a9a62c7 100644 --- a/core-groovy-modules/core-groovy-2/pom.xml +++ b/core-groovy-modules/core-groovy-2/pom.xml @@ -83,7 +83,7 @@ org.codehaus.groovy groovy-eclipse-batch - ${groovy.version}-01 + ${groovy-eclipse-batch.version} @@ -155,16 +155,18 @@ - central - https://jcenter.bintray.com + maven_central + Maven Central + https://repo.maven.apache.org/maven2/ 1.1.3 - 3.1.0 - 3.8.0 - 3.3.0-01 + 3.4.2 + 3.8.1 + 3.7.0 + 3.0.8-01 - \ No newline at end of file + diff --git a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/category/BaeldungCategory.groovy b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/category/BaeldungCategory.groovy index 479c39699f..ccb1c7fc95 100644 --- a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/category/BaeldungCategory.groovy +++ b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/category/BaeldungCategory.groovy @@ -1,17 +1,17 @@ -package com.baeldung.category; +package com.baeldung.category class BaeldungCategory { - public static String capitalize(String self) { - String capitalizedStr = self; + static String capitalize(String self) { + String capitalizedStr = self if (self.size() > 0) { - capitalizedStr = self.substring(0, 1).toUpperCase() + self.substring(1); + capitalizedStr = self.substring(0, 1).toUpperCase() + self.substring(1) } + return capitalizedStr } - - public static double toThePower(Number self, Number exponent) { - return Math.pow(self, exponent); - } + static double toThePower(Number self, Number exponent) { + return Math.pow(self, exponent) + } } diff --git a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/category/NumberCategory.groovy b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/category/NumberCategory.groovy index ccf2ed519b..4f38b87ec5 100644 --- a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/category/NumberCategory.groovy +++ b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/category/NumberCategory.groovy @@ -1,17 +1,15 @@ -package com.baeldung.category; - -import groovy.lang.Category +package com.baeldung.category @Category(Number) class NumberCategory { - public Number cube() { - return this*this*this + Number cube() { + return this**3 } - public int divideWithRoundUp(BigDecimal divisor, boolean isRoundUp) { + int divideWithRoundUp(BigDecimal divisor, boolean isRoundUp) { def mathRound = isRoundUp ? BigDecimal.ROUND_UP : BigDecimal.ROUND_DOWN - return (int)new BigDecimal(this).divide(divisor, 0, mathRound) + + return (int) new BigDecimal(this).divide(divisor, 0, mathRound) } - } diff --git a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/determinedatatype/Person.groovy b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/determinedatatype/Person.groovy index 3ac88b7952..40c935ce08 100644 --- a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/determinedatatype/Person.groovy +++ b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/determinedatatype/Person.groovy @@ -1,14 +1,19 @@ package com.baeldung.determinedatatype class Person { - - private int ageAsInt - private Double ageAsDouble - private String ageAsString - + + int ageAsInt + Double ageAsDouble + String ageAsString + Person() {} - Person(int ageAsInt) { this.ageAsInt = ageAsInt} - Person(Double ageAsDouble) { this.ageAsDouble = ageAsDouble} - Person(String ageAsString) { this.ageAsString = ageAsString} + + Person(int ageAsInt) { this.ageAsInt = ageAsInt } + + Person(Double ageAsDouble) { this.ageAsDouble = ageAsDouble } + + Person(String ageAsString) { this.ageAsString = ageAsString } +} + +class Student extends Person { } -class Student extends Person {} diff --git a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/Employee.groovy b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/Employee.groovy index f49d0f906b..cade7dab3c 100644 --- a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/Employee.groovy +++ b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/Employee.groovy @@ -1,18 +1,14 @@ package com.baeldung.metaprogramming -import groovy.transform.AutoClone -import groovy.transform.Canonical -import groovy.transform.EqualsAndHashCode -import groovy.transform.ToString -import groovy.transform.TupleConstructor -import groovy.util.logging.* +import groovy.transform.* +import groovy.util.logging.Log -@Canonical +@ToString(includePackage = false, excludes = ['id']) @TupleConstructor @EqualsAndHashCode -@ToString(includePackage=false, excludes=['id']) -@Log -@AutoClone +@Canonical +@AutoClone(style = AutoCloneStyle.SIMPLE) +@Log class Employee { long id @@ -30,16 +26,15 @@ class Employee { def propertyMissing(String propertyName, propertyValue) { println "property '$propertyName' is not available" log.info "$propertyName is not available" - "property '$propertyName' is not available" + "property '$propertyName' with value '$propertyValue' is not available" } - def methodMissing(String methodName, def methodArgs) { + def methodMissing(String methodName, Object methodArgs) { log.info "$methodName is not defined" "method '$methodName' is not defined" } - + def logEmp() { log.info "Employee: $lastName, $firstName is of $age years age" } - -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy index 0612ecb955..7e9f0111cd 100644 --- a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy +++ b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy @@ -2,32 +2,31 @@ package com.baeldung.metaprogramming.extension import com.baeldung.metaprogramming.Employee -import java.time.LocalDate import java.time.Year class BasicExtensions { - + static int getYearOfBirth(Employee self) { return Year.now().value - self.age } - + static String capitalize(String self) { return self.substring(0, 1).toUpperCase() + self.substring(1) } static void printCounter(Integer self) { - while (self>0) { + while (self > 0) { println self self-- } } - + static Long square(Long self) { - return self*self + return self * self } - + static BigDecimal cube(BigDecimal self) { - return self*self*self + return self * self * self } - -} \ No newline at end of file + +} diff --git a/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/category/CategoryUnitTest.groovy b/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/category/CategoryUnitTest.groovy index a1f67b1e2e..370dfb316e 100644 --- a/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/category/CategoryUnitTest.groovy +++ b/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/category/CategoryUnitTest.groovy @@ -1,17 +1,17 @@ package com.baeldung.category -import groovy.time.* +import groovy.time.TimeCategory +import groovy.xml.DOMBuilder +import groovy.xml.QName +import groovy.xml.dom.DOMCategory + import java.text.SimpleDateFormat -import groovy.xml.* -import groovy.xml.dom.* -import com.baeldung.category.BaeldungCategory -import com.baeldung.category.NumberCategory class CategoryUnitTest extends GroovyTestCase { void test_whenUsingTimeCategory_thenOperationOnDate() { def jan_1_2019 = new Date("01/01/2019") - use (TimeCategory) { + use(TimeCategory) { assert jan_1_2019 + 10.seconds == new Date("01/01/2019 00:00:10") assert jan_1_2019 + 20.minutes == new Date("01/01/2019 00:20:00") @@ -30,7 +30,7 @@ class CategoryUnitTest extends GroovyTestCase { void test_whenUsingTimeCategory_thenOperationOnNumber() { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy") - use (TimeCategory) { + use(TimeCategory) { assert sdf.format(5.days.from.now) == sdf.format(new Date() + 5.days) sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss") @@ -57,7 +57,7 @@ class CategoryUnitTest extends GroovyTestCase { def root = baeldungArticlesDom.documentElement - use (DOMCategory) { + use(DOMCategory) { assert root.article.size() == 2 def articles = root.article @@ -75,27 +75,26 @@ class CategoryUnitTest extends GroovyTestCase { assert root.article[2].title.text() == "Metaprogramming in Groovy" } } - + void test_whenUsingBaeldungCategory_thenCapitalizeString() { - use (BaeldungCategory) { + use(BaeldungCategory) { assert "norman".capitalize() == "Norman" - } + } } - + void test_whenUsingBaeldungCategory_thenOperationsOnNumber() { - use (BaeldungCategory) { + use(BaeldungCategory) { assert 50.toThePower(2) == 2500 assert 2.4.toThePower(4) == 33.1776 } } - + void test_whenUsingNumberCategory_thenOperationsOnNumber() { - use (NumberCategory) { + use(NumberCategory) { assert 3.cube() == 27 assert 25.divideWithRoundUp(6, true) == 5 assert 120.23.divideWithRoundUp(6.1, true) == 20 assert 150.9.divideWithRoundUp(12.1, false) == 12 } } - } diff --git a/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/determinedatatype/PersonTest.groovy b/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/determinedatatype/PersonTest.groovy index 4c6589f207..414ba52fc5 100644 --- a/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/determinedatatype/PersonTest.groovy +++ b/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/determinedatatype/PersonTest.groovy @@ -1,56 +1,68 @@ package com.baeldung.determinedatatype -import org.junit.Assert -import org.junit.Test -import com.baeldung.determinedatatype.Person +import spock.lang.Specification -public class PersonTest { - - @Test - public void givenWhenParameterTypeIsInteger_thenReturnTrue() { +class PersonTest extends Specification { + + def "givenWhenParameterTypeIsIntegerThenReturnTrue"() { + given: Person personObj = new Person(10) - Assert.assertTrue(personObj.ageAsInt instanceof Integer) - } - - @Test - public void givenWhenParameterTypeIsDouble_thenReturnTrue() { - Person personObj = new Person(10.0) - Assert.assertTrue((personObj.ageAsDouble).getClass() == Double) - } - - @Test - public void givenWhenParameterTypeIsString_thenReturnTrue() { - Person personObj = new Person("10 years") - Assert.assertTrue(personObj.ageAsString.class == String) - } - - @Test - public void givenClassName_WhenParameterIsInteger_thenReturnTrue() { - Assert.assertTrue(Person.class.getDeclaredField('ageAsInt').type == int.class) - } - - @Test - public void givenWhenObjectIsInstanceOfType_thenReturnTrue() { - Person personObj = new Person() - Assert.assertTrue(personObj instanceof Person) + + expect: + personObj.ageAsInt.class == Integer } - @Test - public void givenWhenInstanceIsOfSubtype_thenReturnTrue() { + def "givenWhenParameterTypeIsDouble_thenReturnTrue"() { + given: + Person personObj = new Person(10.0) + + expect: + personObj.ageAsDouble.class == Double + } + + def "givenWhenParameterTypeIsString_thenReturnTrue"() { + given: + Person personObj = new Person("10 years") + + expect: + personObj.ageAsString.class == String + } + + def "givenClassName_WhenParameterIsInteger_thenReturnTrue"() { + expect: + Person.class.getDeclaredField('ageAsInt').type == int.class + } + + def "givenWhenObjectIsInstanceOfType_thenReturnTrue"() { + given: + Person personObj = new Person() + + expect: + personObj.class == Person + } + + def "givenWhenInstanceIsOfSubtype_thenReturnTrue"() { + given: Student studentObj = new Student() - Assert.assertTrue(studentObj in Person) + + expect: + studentObj.class.superclass == Person } - - @Test - public void givenGroovyList_WhenFindClassName_thenReturnTrue() { - def ageList = ['ageAsString','ageAsDouble', 10] - Assert.assertTrue(ageList.class == ArrayList) - Assert.assertTrue(ageList.getClass() == ArrayList) + + def "givenGroovyList_WhenFindClassName_thenReturnTrue"() { + given: + def ageList = ['ageAsString', 'ageAsDouble', 10] + + expect: + ageList.class == ArrayList + ageList.getClass() == ArrayList } - - @Test - public void givenGrooyMap_WhenFindClassName_thenReturnTrue() { - def ageMap = [ageAsString: '10 years', ageAsDouble: 10.0] - Assert.assertFalse(ageMap.class == LinkedHashMap) + + def "givenGroovyMap_WhenFindClassName_thenReturnTrue"() { + given: + def ageMap = [ageAsString: '10 years', ageAsDouble: 10.0] + + expect: + ageMap.getClass() == LinkedHashMap } -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy b/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy index 4a8631eb95..6959c97533 100644 --- a/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy +++ b/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy @@ -1,123 +1,163 @@ package com.baeldung.metaprogramming +import spock.lang.Specification -import java.time.LocalDate -import java.time.Period import java.time.Year -class MetaprogrammingUnitTest extends GroovyTestCase { +class MetaprogrammingUnitTest extends Specification { - Employee emp = new Employee(firstName: "Norman", lastName: "Lewis") + Employee emp - void testPropertyMissing() { - assert emp.address == "property 'address' is not available" + void setup() { + emp = new Employee(firstName: "Norman", lastName: "Lewis") } - void testMethodMissing() { + def "testPropertyMissing"() { + expect: + emp.address == "property 'address' is not available" + } + + def "testMethodMissing"() { + given: Employee emp = new Employee() - try { - emp.getFullName() - } catch(MissingMethodException e) { - println "method is not defined" - } - assert emp.getFullName() == "method 'getFullName' is not defined" + + expect: + emp.getFullName() == "method 'getFullName' is not defined" } - void testMetaClassProperty() { + def "testMetaClassProperty"() { + when: Employee.metaClass.address = "" - emp = new Employee(firstName: "Norman", lastName: "Lewis", address: "US") - assert emp.address == "US" + + and: + emp = new Employee(firstName: "Norman", + lastName: "Lewis", + address: "US") + + then: + emp.address == "US" } - void testMetaClassMethod() { + def "testMetaClassMethod"() { + when: emp.metaClass.getFullName = { "$lastName, $firstName" } - assert emp.getFullName() == "Lewis, Norman" + + then: + emp.getFullName() == "Lewis, Norman" } - void testMetaClassConstructor() { - try { - Employee emp = new Employee("Norman") - } catch(GroovyRuntimeException e) { - assert e.message == "Could not find matching constructor for: com.baeldung.metaprogramming.Employee(String)" - } + def "testOnlyNameConstructor"() { + when: + new Employee("Norman") + then: + thrown(GroovyRuntimeException) + } + + def "testMetaClassConstructor"() { + when: Employee.metaClass.constructor = { String firstName -> new Employee(firstName: firstName) } + and: Employee norman = new Employee("Norman") - assert norman.firstName == "Norman" - assert norman.lastName == null + + then: + norman.firstName == "Norman" + norman.lastName == null } - void testJavaMetaClass() { + def "testJavaMetaClass"() { + when: String.metaClass.capitalize = { String str -> str.substring(0, 1).toUpperCase() + str.substring(1) } - assert "norman".capitalize() == "Norman" + + and: + String.metaClass.static.joinWith = { String delimiter, String... args -> + String.join(delimiter, args) + } + + then: + "norman".capitalize() == "Norman" + String.joinWith(" -> ", "a", "b", "c") == "a -> b -> c" } - void testEmployeeExtension() { + def "testEmployeeExtension"() { + given: def age = 28 def expectedYearOfBirth = Year.now() - age Employee emp = new Employee(age: age) - assert emp.getYearOfBirth() == expectedYearOfBirth.value + + expect: + emp.getYearOfBirth() == expectedYearOfBirth.value } - void testJavaClassesExtensions() { + def "testJavaClassesExtensions"() { + when: 5.printCounter() - assert 40l.square() == 1600l - - assert (2.98).cube() == 26.463592 + then: + 40L.square() == 1600L + (2.98).cube() == 26.463592 } - void testStaticEmployeeExtension() { + def "testStaticEmployeeExtension"() { assert Employee.getDefaultObj().firstName == "firstName" assert Employee.getDefaultObj().lastName == "lastName" assert Employee.getDefaultObj().age == 20 } - void testToStringAnnotation() { - Employee employee = new Employee() - employee.id = 1 - employee.firstName = "norman" - employee.lastName = "lewis" - employee.age = 28 + def "testToStringAnnotation"() { + when: + Employee employee = new Employee().tap { + id = 1 + firstName = "norman" + lastName = "lewis" + age = 28 + } - assert employee.toString() == "Employee(norman, lewis, 28)" + then: + employee.toString() == "Employee(norman, lewis, 28)" } - void testTupleConstructorAnnotation() { + def "testTupleConstructorAnnotation"() { + when: Employee norman = new Employee(1, "norman", "lewis", 28) - assert norman.toString() == "Employee(norman, lewis, 28)" - Employee snape = new Employee(2, "snape") - assert snape.toString() == "Employee(snape, null, 0)" + then: + norman.toString() == "Employee(norman, lewis, 28)" + snape.toString() == "Employee(snape, null, 0)" } - - void testEqualsAndHashCodeAnnotation() { + + def "testEqualsAndHashCodeAnnotation"() { + when: Employee norman = new Employee(1, "norman", "lewis", 28) Employee normanCopy = new Employee(1, "norman", "lewis", 28) - assert norman.equals(normanCopy) - assert norman.hashCode() == normanCopy.hashCode() - } - - void testAutoCloneAnnotation() { - try { - Employee norman = new Employee(1, "norman", "lewis", 28) - def normanCopy = norman.clone() - assert norman == normanCopy - } catch(CloneNotSupportedException e) { - e.printStackTrace() - } + + then: + norman == normanCopy + norman.hashCode() == normanCopy.hashCode() } - void testLoggingAnnotation() { + def "testAutoCloneAnnotation"() { + given: + Employee norman = new Employee(1, "norman", "lewis", 28) + + when: + def normanCopy = norman.clone() + + then: + norman == normanCopy + } + + def "testLoggingAnnotation"() { + given: Employee employee = new Employee(1, "Norman", "Lewis", 28) - employee.logEmp() + employee.logEmp() // INFO: Employee: Lewis, Norman is of 28 years age } } diff --git a/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/templateengine/TemplateEnginesUnitTest.groovy b/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/templateengine/TemplateEnginesUnitTest.groovy index 1846ae664c..800f3b119e 100644 --- a/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/templateengine/TemplateEnginesUnitTest.groovy +++ b/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/templateengine/TemplateEnginesUnitTest.groovy @@ -1,48 +1,62 @@ package com.baeldung.templateengine +import groovy.text.GStringTemplateEngine import groovy.text.SimpleTemplateEngine import groovy.text.StreamingTemplateEngine -import groovy.text.GStringTemplateEngine -import groovy.text.XmlTemplateEngine import groovy.text.XmlTemplateEngine import groovy.text.markup.MarkupTemplateEngine import groovy.text.markup.TemplateConfiguration +import spock.lang.Specification -class TemplateEnginesUnitTest extends GroovyTestCase { - - def bindMap = [user: "Norman", signature: "Baeldung"] - - void testSimpleTemplateEngine() { +class TemplateEnginesUnitTest extends Specification { + + final Map BIND_MAP = [user: "Norman", signature: "Baeldung"] + + def "testSimpleTemplateEngine"() { + given: def smsTemplate = 'Dear <% print user %>, Thanks for reading our Article. ${signature}' - def smsText = new SimpleTemplateEngine().createTemplate(smsTemplate).make(bindMap) - assert smsText.toString() == "Dear Norman, Thanks for reading our Article. Baeldung" + when: + def smsText = new SimpleTemplateEngine().createTemplate(smsTemplate).make(BIND_MAP) + + then: + smsText.toString() == "Dear Norman, Thanks for reading our Article. Baeldung" } - - void testStreamingTemplateEngine() { + + def "testStreamingTemplateEngine"() { + given: def articleEmailTemplate = new File('src/main/resources/articleEmail.template') - bindMap.articleText = """1. Overview -This is a tutorial article on Template Engines""" //can be a string larger than 64k - - def articleEmailText = new StreamingTemplateEngine().createTemplate(articleEmailTemplate).make(bindMap) - - assert articleEmailText.toString() == """Dear Norman, -Please read the requested article below. -1. Overview -This is a tutorial article on Template Engines -From, -Baeldung""" - + //can be a string larger than 64k + BIND_MAP.articleText = """|1. Overview + |This is a tutorial article on Template Engines""".stripMargin() + + when: + def articleEmailText = new StreamingTemplateEngine().createTemplate(articleEmailTemplate).make(BIND_MAP) + + then: + articleEmailText.toString() == """|Dear Norman, + |Please read the requested article below. + |1. Overview + |This is a tutorial article on Template Engines + |From, + |Baeldung""".stripMargin() } - - void testGStringTemplateEngine() { + + def "testGStringTemplateEngine"() { + given: def emailTemplate = new File('src/main/resources/email.template') - def emailText = new GStringTemplateEngine().createTemplate(emailTemplate).make(bindMap) - - assert emailText.toString() == "Dear Norman,\nThanks for subscribing our services.\nBaeldung" + + when: + def emailText = new GStringTemplateEngine().createTemplate(emailTemplate).make(BIND_MAP) + + then: + emailText.toString() == """|Dear Norman, + |Thanks for subscribing our services. + |Baeldung""".stripMargin() } - - void testXmlTemplateEngine() { + + def "testXmlTemplateEngine"() { + given: def emailXmlTemplate = ''' def emailContent = "Thanks for subscribing our services." @@ -51,11 +65,16 @@ Baeldung""" ${signature} ''' - def emailXml = new XmlTemplateEngine().createTemplate(emailXmlTemplate).make(bindMap) + + when: + def emailXml = new XmlTemplateEngine().createTemplate(emailXmlTemplate).make(BIND_MAP) + + then: println emailXml.toString() } - - void testMarkupTemplateEngineHtml() { + + def "testMarkupTemplateEngineHtml"() { + given: def emailHtmlTemplate = """html { head { title('Service Subscription Email') @@ -66,14 +85,16 @@ Baeldung""" p('Baeldung') } }""" - - + + when: def emailHtml = new MarkupTemplateEngine().createTemplate(emailHtmlTemplate).make() + + then: println emailHtml.toString() - } - - void testMarkupTemplateEngineXml() { + + def "testMarkupTemplateEngineXml"() { + given: def emailXmlTemplate = """xmlDeclaration() xs{ email { @@ -83,14 +104,18 @@ Baeldung""" } } """ - TemplateConfiguration config = new TemplateConfiguration() - config.autoIndent = true - config.autoEscape = true - config.autoNewLine = true + TemplateConfiguration config = new TemplateConfiguration().with { + autoIndent = true + autoEscape = true + autoNewLine = true + return it + } + + when: def emailXml = new MarkupTemplateEngine(config).createTemplate(emailXmlTemplate).make() - + + then: println emailXml.toString() } - -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy-collections/pom.xml b/core-groovy-modules/core-groovy-collections/pom.xml index 5269121140..6d43ce7d18 100644 --- a/core-groovy-modules/core-groovy-collections/pom.xml +++ b/core-groovy-modules/core-groovy-collections/pom.xml @@ -113,9 +113,11 @@ - central - http://jcenter.bintray.com + maven_central + Maven Central + https://repo.maven.apache.org/maven2/ - \ No newline at end of file + + diff --git a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/ListFindUnitTest.groovy b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/ListFindUnitTest.groovy index 82a2138be4..325cf18c5f 100644 --- a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/ListFindUnitTest.groovy +++ b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/ListFindUnitTest.groovy @@ -1,58 +1,57 @@ package com.baeldung.find -import com.baeldung.find.Person -import org.junit.Test +import spock.lang.Specification -import static org.junit.Assert.* +class ListFindUnitTest extends Specification { -class ListFindUnitTest { - - private final personList = [ - new Person("Regina", "Fitzpatrick", 25), - new Person("Abagail", "Ballard", 26), - new Person("Lucian", "Walter", 30), + final personList = [ + new Person("Regina", "Fitzpatrick", 25), + new Person("Abagail", "Ballard", 26), + new Person("Lucian", "Walter", 30), ] - @Test - void whenListContainsElement_thenCheckReturnsTrue() { + def "whenListContainsElement_thenCheckReturnsTrue"() { + given: def list = ['a', 'b', 'c'] - assertTrue(list.indexOf('a') > -1) - assertTrue(list.contains('a')) + expect: + list.indexOf('a') > -1 + list.contains('a') } - @Test - void whenListContainsElement_thenCheckWithMembershipOperatorReturnsTrue() { + def "whenListContainsElement_thenCheckWithMembershipOperatorReturnsTrue"() { + given: def list = ['a', 'b', 'c'] - assertTrue('a' in list) + expect: + 'a' in list } - @Test - void givenListOfPerson_whenUsingStreamMatching_thenShouldEvaluateList() { - assertTrue(personList.stream().anyMatch {it.age > 20}) - assertFalse(personList.stream().allMatch {it.age < 30}) + def "givenListOfPerson_whenUsingStreamMatching_thenShouldEvaluateList"() { + expect: + personList.stream().anyMatch { it.age > 20 } + !personList.stream().allMatch { it.age < 30 } } - @Test - void givenListOfPerson_whenUsingCollectionMatching_thenShouldEvaluateList() { - assertTrue(personList.any {it.age > 20}) - assertFalse(personList.every {it.age < 30}) + def "givenListOfPerson_whenUsingCollectionMatching_thenShouldEvaluateList"() { + expect: + personList.any { it.age > 20 } + !personList.every { it.age < 30 } } - @Test - void givenListOfPerson_whenUsingStreamFind_thenShouldReturnMatchingElements() { - assertTrue(personList.stream().filter {it.age > 20}.findAny().isPresent()) - assertFalse(personList.stream().filter {it.age > 30}.findAny().isPresent()) - assertTrue(personList.stream().filter {it.age > 20}.findAll().size() == 3) - assertTrue(personList.stream().filter {it.age > 30}.findAll().isEmpty()) + def "givenListOfPerson_whenUsingStreamFind_thenShouldReturnMatchingElements"() { + expect: + personList.stream().filter { it.age > 20 }.findAny().isPresent() + !personList.stream().filter { it.age > 30 }.findAny().isPresent() + personList.stream().filter { it.age > 20 }.findAll().size() == 3 + personList.stream().filter { it.age > 30 }.findAll().isEmpty() } - @Test - void givenListOfPerson_whenUsingCollectionFind_thenShouldReturnMatchingElements() { - assertNotNull(personList.find {it.age > 20}) - assertNull(personList.find {it.age > 30}) - assertTrue(personList.findAll {it.age > 20}.size() == 3) - assertTrue(personList.findAll {it.age > 30}.isEmpty()) + def "givenListOfPerson_whenUsingCollectionFind_thenShouldReturnMatchingElements"() { + expect: + personList.find { it.age > 20 } == new Person("Regina", "Fitzpatrick", 25) + personList.find { it.age > 30 } == null + personList.findAll { it.age > 20 }.size() == 3 + personList.findAll { it.age > 30 }.isEmpty() } } diff --git a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/MapFindUnitTest.groovy b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/MapFindUnitTest.groovy index 16e231182b..74d85ad71b 100644 --- a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/MapFindUnitTest.groovy +++ b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/MapFindUnitTest.groovy @@ -1,76 +1,81 @@ package com.baeldung.find -import com.baeldung.find.Person -import org.junit.Test +import spock.lang.Specification -import static org.junit.Assert.* +class MapFindUnitTest extends Specification { -class MapFindUnitTest { - - private final personMap = [ - Regina : new Person("Regina", "Fitzpatrick", 25), - Abagail: new Person("Abagail", "Ballard", 26), - Lucian : new Person("Lucian", "Walter", 30) + final personMap = [ + Regina: new Person("Regina", "Fitzpatrick", 25), + Abagail: new Person("Abagail", "Ballard", 26), + Lucian: new Person("Lucian", "Walter", 30) ] - @Test - void whenMapContainsKeyElement_thenCheckReturnsTrue() { + def "whenMapContainsKeyElement_thenCheckReturnsTrue"() { + given: def map = [a: 'd', b: 'e', c: 'f'] - assertTrue(map.containsKey('a')) - assertFalse(map.containsKey('e')) - assertTrue(map.containsValue('e')) + expect: + map.containsKey('a') + !map.containsKey('e') + map.containsValue('e') } - @Test - void whenMapContainsKeyElement_thenCheckByMembershipReturnsTrue() { + def "whenMapContainsKeyElement_thenCheckByMembershipReturnsTrue"() { + given: def map = [a: 'd', b: 'e', c: 'f'] - assertTrue('a' in map) - assertFalse('f' in map) + expect: + 'a' in map + 'f' !in map } - @Test - void whenMapContainsFalseBooleanValues_thenCheckReturnsFalse() { + def "whenMapContainsFalseBooleanValues_thenCheckReturnsFalse"() { + given: def map = [a: true, b: false, c: null] - assertTrue(map.containsKey('b')) - assertTrue('a' in map) - assertFalse('b' in map) - assertFalse('c' in map) + expect: + map.containsKey('b') + 'a' in map + 'b' !in map // get value of key 'b' and does the assertion + 'c' !in map } - @Test - void givenMapOfPerson_whenUsingStreamMatching_thenShouldEvaluateMap() { - assertTrue(personMap.keySet().stream().anyMatch {it == "Regina"}) - assertFalse(personMap.keySet().stream().allMatch {it == "Albert"}) - assertFalse(personMap.values().stream().allMatch {it.age < 30}) - assertTrue(personMap.entrySet().stream().anyMatch {it.key == "Abagail" && it.value.lastname == "Ballard"}) + def "givenMapOfPerson_whenUsingStreamMatching_thenShouldEvaluateMap"() { + expect: + personMap.keySet().stream() + .anyMatch { it == "Regina" } + !personMap.keySet().stream() + .allMatch { it == "Albert" } + !personMap.values().stream() + .allMatch { it.age < 30 } + personMap.entrySet().stream() + .anyMatch { it.key == "Abagail" && it.value.lastname == "Ballard" } } - @Test - void givenMapOfPerson_whenUsingCollectionMatching_thenShouldEvaluateMap() { - assertTrue(personMap.keySet().any {it == "Regina"}) - assertFalse(personMap.keySet().every {it == "Albert"}) - assertFalse(personMap.values().every {it.age < 30}) - assertTrue(personMap.any {firstname, person -> firstname == "Abagail" && person.lastname == "Ballard"}) + def "givenMapOfPerson_whenUsingCollectionMatching_thenShouldEvaluateMap"() { + expect: + personMap.keySet().any { it == "Regina" } + !personMap.keySet().every { it == "Albert" } + !personMap.values().every { it.age < 30 } + personMap.any { firstname, person -> firstname == "Abagail" && person.lastname == "Ballard" } } - @Test - void givenMapOfPerson_whenUsingCollectionFind_thenShouldReturnElements() { - assertNotNull(personMap.find {it.key == "Abagail" && it.value.lastname == "Ballard"}) - assertTrue(personMap.findAll {it.value.age > 20}.size() == 3) + def "givenMapOfPerson_whenUsingCollectionFind_thenShouldReturnElements"() { + expect: + personMap.find { it.key == "Abagail" && it.value.lastname == "Ballard" } + personMap.findAll { it.value.age > 20 }.size() == 3 } - @Test - void givenMapOfPerson_whenUsingStreamFind_thenShouldReturnElements() { - assertTrue( - personMap.entrySet().stream() - .filter {it.key == "Abagail" && it.value.lastname == "Ballard"} - .findAny().isPresent()) - assertTrue( - personMap.entrySet().stream() - .filter {it.value.age > 20} - .findAll().size() == 3) + def "givenMapOfPerson_whenUsingStreamFind_thenShouldReturnElements"() { + expect: + personMap.entrySet().stream() + .filter { it.key == "Abagail" && it.value.lastname == "Ballard" } + .findAny() + .isPresent() + + personMap.entrySet().stream() + .filter { it.value.age > 20 } + .findAll() + .size() == 3 } } diff --git a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/Person.groovy b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/Person.groovy index e65826363a..a9266c4079 100644 --- a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/Person.groovy +++ b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/Person.groovy @@ -1,37 +1,10 @@ package com.baeldung.find +import groovy.transform.Canonical + +@Canonical class Person { - private String firstname - private String lastname - private Integer age - - Person(String firstname, String lastname, Integer age) { - this.firstname = firstname - this.lastname = lastname - this.age = age - } - - String getFirstname() { - return firstname - } - - void setFirstname(String firstname) { - this.firstname = firstname - } - - String getLastname() { - return lastname - } - - void setLastname(String lastname) { - this.lastname = lastname - } - - Integer getAge() { - return age - } - - void setAge(Integer age) { - this.age = age - } + String firstname + String lastname + Integer age } diff --git a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/SetFindUnitTest.groovy b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/SetFindUnitTest.groovy index d2d03d5427..d82cf689d3 100644 --- a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/SetFindUnitTest.groovy +++ b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/SetFindUnitTest.groovy @@ -1,16 +1,15 @@ package com.baeldung.find -import org.junit.Test +import spock.lang.Specification -import static org.junit.Assert.assertTrue +class SetFindUnitTest extends Specification { -class SetFindUnitTest { - - @Test - void whenSetContainsElement_thenCheckReturnsTrue() { + def "whenSetContainsElement_thenCheckReturnsTrue"() { + given: def set = ['a', 'b', 'c'] as Set - assertTrue(set.contains('a')) - assertTrue('a' in set) + expect: + set.contains('a') + 'a' in set } -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/iteratemap/IterateMapUnitTest.groovy b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/iteratemap/IterateMapUnitTest.groovy index 970203ce85..4cbcaee2d8 100644 --- a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/iteratemap/IterateMapUnitTest.groovy +++ b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/iteratemap/IterateMapUnitTest.groovy @@ -1,85 +1,54 @@ package com.baeldung.iteratemap -import com.baeldung.find.Person -import org.junit.Test +import spock.lang.Specification -import static org.junit.Assert.* +class IterateMapUnitTest extends Specification { -class IterateMapUnitTest { - - @Test - void whenUsingEach_thenMapIsIterated() { - def map = [ - 'FF0000' : 'Red', - '00FF00' : 'Lime', - '0000FF' : 'Blue', - 'FFFF00' : 'Yellow' - ] + final Map map = [ + 'FF0000': 'Red', + '00FF00': 'Lime', + '0000FF': 'Blue', + 'FFFF00': 'Yellow', + 'E6E6FA': 'Lavender', + 'D8BFD8': 'Thistle', + 'DDA0DD': 'Plum', + ] + def "whenUsingEach_thenMapIsIterated"() { + expect: map.each { println "Hex Code: $it.key = Color Name: $it.value" } } - @Test - void whenUsingEachWithEntry_thenMapIsIterated() { - def map = [ - 'E6E6FA' : 'Lavender', - 'D8BFD8' : 'Thistle', - 'DDA0DD' : 'Plum', - ] - + def "whenUsingEachWithEntry_thenMapIsIterated"() { + expect: map.each { entry -> println "Hex Code: $entry.key = Color Name: $entry.value" } } - @Test - void whenUsingEachWithKeyAndValue_thenMapIsIterated() { - def map = [ - '000000' : 'Black', - 'FFFFFF' : 'White', - '808080' : 'Gray' - ] - + def "whenUsingEachWithKeyAndValue_thenMapIsIterated"() { + expect: map.each { key, val -> println "Hex Code: $key = Color Name $val" } } - @Test - void whenUsingEachWithIndexAndEntry_thenMapIsIterated() { - def map = [ - '800080' : 'Purple', - '4B0082' : 'Indigo', - '6A5ACD' : 'Slate Blue' - ] - + def "whenUsingEachWithIndexAndEntry_thenMapIsIterated"() { + expect: map.eachWithIndex { entry, index -> - def indent = ((index == 0 || index % 2 == 0) ? " " : "") + def indent = index % 2 == 0 ? " " : "" println "$indent Hex Code: $entry.key = Color Name: $entry.value" } } - @Test - void whenUsingEachWithIndexAndKeyAndValue_thenMapIsIterated() { - def map = [ - 'FFA07A' : 'Light Salmon', - 'FF7F50' : 'Coral', - 'FF6347' : 'Tomato', - 'FF4500' : 'Orange Red' - ] - + def "whenUsingEachWithIndexAndKeyAndValue_thenMapIsIterated"() { + expect: map.eachWithIndex { key, val, index -> - def indent = ((index == 0 || index % 2 == 0) ? " " : "") + def indent = index % 2 == 0 ? " " : "" println "$indent Hex Code: $key = Color Name: $val" } } - @Test - void whenUsingForLoop_thenMapIsIterated() { - def map = [ - '2E8B57' : 'Seagreen', - '228B22' : 'Forest Green', - '008000' : 'Green' - ] - + def "whenUsingForLoop_thenMapIsIterated"() { + expect: for (entry in map) { println "Hex Code: $entry.key = Color Name: $entry.value" } diff --git a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy index e4c0a0c177..5baa19f360 100644 --- a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy +++ b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy @@ -1,173 +1,171 @@ package com.baeldung.lists -import static groovy.test.GroovyAssert.* -import org.junit.Test +import spock.lang.Specification -class ListUnitTest { - - @Test - void testCreateList() { +class ListUnitTest extends Specification { + def "testCreateList"() { + when: def list = [1, 2, 3] - assertNotNull(list) - def listMix = ['A', "b", 1, true] - assertTrue(listMix == ['A', "b", 1, true]) - def linkedList = [1, 2, 3] as LinkedList - assertTrue(linkedList instanceof LinkedList) - ArrayList arrList = [1, 2, 3] - assertTrue(arrList.class == ArrayList) - def copyList = new ArrayList(arrList) - assertTrue(copyList == arrList) - def cloneList = arrList.clone() - assertTrue(cloneList == arrList) + + then: + list + listMix == ['A', "b", 1, true] + linkedList instanceof LinkedList + arrList.class == ArrayList + copyList == arrList + cloneList == arrList } - @Test - void testCreateEmptyList() { - + def "testCreateEmptyList"() { + when: def emptyList = [] - assertTrue(emptyList.size() == 0) + + then: + emptyList.isEmpty() } - @Test - void testCompareTwoLists() { - + def "testCompareTwoLists"() { + when: def list1 = [5, 6.0, 'p'] def list2 = [5, 6.0, 'p'] - assertTrue(list1 == list2) + + then: + list1 == list2 } - @Test - void testGetItemsFromList(){ - + def "testGetItemsFromList"() { + when: def list = ["Hello", "World"] - assertTrue(list.get(1) == "World") - assertTrue(list[1] == "World") - assertTrue(list[-1] == "World") - assertTrue(list.getAt(1) == "World") - assertTrue(list.getAt(-2) == "Hello") + then: + list.get(1) == "World" + list[1] == "World" + list[-1] == "World" + list.getAt(1) == "World" + list.getAt(-2) == "Hello" } - @Test - void testAddItemsToList() { + def "testAddItemsToList"() { + given: + def list1 = [] + def list2 = [] + def list3 = [1, 2] - def list = [] + when: + list1 << 1 // [1] + list1.add("Apple") // [1, "Apple"] - list << 1 - list.add("Apple") - assertTrue(list == [1, "Apple"]) + list2[2] = "Box" // [null, "Box"] + list2[4] = true // [null, "Box", null, true] - list[2] = "Box" - list[4] = true - assertTrue(list == [1, "Apple", "Box", null, true]) + list1.add(1, 6.0) // [1, 6.0, "Apple"] + list1 += list3 // [1, 6.0, "Apple", 1, 2] + list1 += 12 // [1, 6.0, "Apple", 1, 2, 12] - list.add(1, 6.0) - assertTrue(list == [1, 6.0, "Apple", "Box", null, true]) - - def list2 = [1, 2] - list += list2 - list += 12 - assertTrue(list == [1, 6.0, "Apple", "Box", null, true, 1, 2, 12]) + then: + list1 == [1, 6.0, "Apple", 1, 2, 12] + list2 == [null, null, "Box", null, true] } - @Test - void testUpdateItemsInList() { + def "testUpdateItemsInList"() { + given: + def list = [1, "Apple", 80, "App"] - def list =[1, "Apple", 80, "App"] + when: list[1] = "Box" - list.set(2,90) - assertTrue(list == [1, "Box", 90, "App"]) + list.set(2, 90) + + then: + list == [1, "Box", 90, "App"] } - @Test - void testRemoveItemsFromList(){ - + def "testRemoveItemsFromList"() { + given: def list = [1, 2, 3, 4, 5, 5, 6, 6, 7] - list.remove(3) - assertTrue(list == [1, 2, 3, 5, 5, 6, 6, 7]) + when: + list.remove(3) // [1, 2, 3, 5, 5, 6, 6, 7] + list.removeElement(5) // [1, 2, 3, 5, 6, 6, 7] + list = list - 6 // [1, 2, 3, 5, 7] - list.removeElement(5) - assertTrue(list == [1, 2, 3, 5, 6, 6, 7]) - - assertTrue(list - 6 == [1, 2, 3, 5, 7]) + then: + list == [1, 2, 3, 5, 7] } - @Test - void testIteratingOnAList(){ - + def "testIteratingOnAList"() { + given: def list = [1, "App", 3, 4] - list.each{ println it * 2} - list.eachWithIndex{ it, i -> println "$i : $it" } + expect: + list.each { println it * 2 } + list.eachWithIndex { it, i -> println "$i : $it" } } - @Test - void testCollectingToAnotherList(){ - + def "testCollectingToAnotherList"() { + given: def list = ["Kay", "Henry", "Justin", "Tom"] - assertTrue(list.collect{"Hi " + it} == ["Hi Kay", "Hi Henry", "Hi Justin", "Hi Tom"]) + + when: + def collect = list.collect { "Hi " + it } + + then: + collect == ["Hi Kay", "Hi Henry", "Hi Justin", "Hi Tom"] } - @Test - void testJoinItemsInAList(){ - assertTrue(["One", "Two", "Three"].join(",") == "One,Two,Three") + def "testJoinItemsInAList"() { + expect: + ["One", "Two", "Three"].join(",") == "One,Two,Three" } - @Test - void testFilteringOnLists(){ + def "testFilteringOnLists"() { + given: def filterList = [2, 1, 3, 4, 5, 6, 76] - - assertTrue(filterList.find{it > 3} == 4) - - assertTrue(filterList.findAll{it > 3} == [4, 5, 6, 76]) - - assertTrue(filterList.findAll{ it instanceof Number} == [2, 1, 3, 4, 5, 6, 76]) - - assertTrue(filterList.grep( Number )== [2, 1, 3, 4, 5, 6, 76]) - - assertTrue(filterList.grep{ it> 6 }== [76]) - def conditionList = [2, 1, 3, 4, 5, 6, 76] - assertFalse(conditionList.every{ it < 6}) - - assertTrue(conditionList.any{ it%2 == 0}) + expect: + filterList.find { it > 3 } == 4 + filterList.findAll { it > 3 } == [4, 5, 6, 76] + filterList.findAll { it instanceof Number } == [2, 1, 3, 4, 5, 6, 76] + filterList.grep(Number) == [2, 1, 3, 4, 5, 6, 76] + filterList.grep { it > 6 } == [76] + !(conditionList.every { it < 6 }) + conditionList.any { it % 2 == 0 } } - @Test - void testGetUniqueItemsInAList(){ - assertTrue([1, 3, 3, 4].toUnique() == [1, 3, 4]) - + def "testGetUniqueItemsInAList"() { + given: def uniqueList = [1, 3, 3, 4] - uniqueList.unique() - assertTrue(uniqueList == [1, 3, 4]) - assertTrue(["A", "B", "Ba", "Bat", "Cat"].toUnique{ it.size()} == ["A", "Ba", "Bat"]) + when: + uniqueList.unique(true) + + then: + [1, 3, 3, 4].toUnique() == [1, 3, 4] + uniqueList == [1, 3, 4] + ["A", "B", "Ba", "Bat", "Cat"].toUnique { it.size() } == ["A", "Ba", "Bat"] } - @Test - void testSorting(){ - - assertTrue([1, 2, 1, 0].sort() == [0, 1, 1, 2]) - Comparator mc = {a,b -> a == b? 0: a < b? 1 : -1} - + def "testSorting"() { + given: + Comparator naturalOrder = { a, b -> a == b ? 0 : a < b ? -1 : 1 } def list = [1, 2, 1, 0] - list.sort(mc) - assertTrue(list == [2, 1, 1, 0]) - def strList = ["na", "ppp", "as"] - assertTrue(strList.max() == "ppp") - - Comparator minc = {a,b -> a == b? 0: a < b? -1 : 1} def numberList = [3, 2, 0, 7] - assertTrue(numberList.min(minc) == 0) + + when: + list.sort(naturalOrder.reversed()) + + then: + list == [2, 1, 1, 0] + strList.max() == "ppp" + [1, 2, 1, 0].sort() == [0, 1, 1, 2] + numberList.min(naturalOrder) == 0 } -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/maps/MapTest.groovy b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/maps/MapTest.groovy index deb552c420..9529330089 100644 --- a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/maps/MapTest.groovy +++ b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/maps/MapTest.groovy @@ -1,148 +1,160 @@ -package com.baeldung.maps; +package com.baeldung.maps -import static groovy.test.GroovyAssert.* -import org.junit.Test +import spock.lang.Specification -class MapTest{ - - @Test - void createMap() { +class MapTest extends Specification { + def "createMap"() { + when: def emptyMap = [:] - assertNotNull(emptyMap) + def map = [name: "Jerry", age: 42, city: "New York"] - assertTrue(emptyMap instanceof java.util.LinkedHashMap) - - def map = [name:"Jerry", age: 42, city: "New York"] - assertTrue(map.size() == 3) + then: + emptyMap != null + emptyMap instanceof java.util.LinkedHashMap + map.size() == 3 } - @Test - void addItemsToMap() { - - def map = [name:"Jerry"] - - map["age"] = 42 - - map.city = "New York" - + def "addItemsToMap"() { + given: + def map = [name: "Jerry"] def hobbyLiteral = "hobby" def hobbyMap = [(hobbyLiteral): "Singing"] + def appendToMap = [:] + + when: + map["age"] = 42 + map.city = "New York" + map.putAll(hobbyMap) - assertTrue(map == [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]) - assertTrue(hobbyMap.hobby == "Singing") - assertTrue(hobbyMap[hobbyLiteral] == "Singing") - - map.plus([1:20]) // returns new map + appendToMap.plus([1: 20]) + appendToMap << [2: 30] - map << [2:30] + then: + map == [name: "Jerry", age: 42, city: "New York", hobby: "Singing"] + hobbyMap.hobby == "Singing" + hobbyMap[hobbyLiteral] == "Singing" + + appendToMap == [2: 30] // plus(Map) returns new instance of Map } - @Test - void getItemsFromMap() { - - def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"] - - assertTrue(map["name"] == "Jerry") - - assertTrue(map.name == "Jerry") - + def "getItemsFromMap"() { + when: + def map = [name: "Jerry", age: 42, city: "New York", hobby: "Singing"] def propertyAge = "age" - assertTrue(map[propertyAge] == 42) + + then: + map["name"] == "Jerry" + map.name == "Jerry" + map[propertyAge] == 42 + map."$propertyAge" == 42 } - @Test - void removeItemsFromMap() { + def "removeItemsFromMap"() { + given: + def map = [1: 20, a: 30, 2: 42, 4: 34, ba: 67, 6: 39, 7: 49] + def removeAllKeysOfTypeString = [1: 20, a: 30, ba: 67, 6: 39, 7: 49] + def retainAllEntriesWhereValueIsEven = [1: 20, a: 30, ba: 67, 6: 39, 7: 49] - def map = [1:20, a:30, 2:42, 4:34, ba:67, 6:39, 7:49] + when: + def minusMap = map - [2: 42, 4: 34] + removeAllKeysOfTypeString.removeAll { it.key instanceof String } + retainAllEntriesWhereValueIsEven.retainAll { it.value % 2 == 0 } - def minusMap = map.minus([2:42, 4:34]); - assertTrue(minusMap == [1:20, a:30, ba:67, 6:39, 7:49]) - - minusMap.removeAll{it -> it.key instanceof String} - assertTrue( minusMap == [ 1:20, 6:39, 7:49]) - - minusMap.retainAll{it -> it.value %2 == 0} - assertTrue( minusMap == [1:20]) + then: + minusMap == [1: 20, a: 30, ba: 67, 6: 39, 7: 49] + removeAllKeysOfTypeString == [1: 20, 6: 39, 7: 49] + retainAllEntriesWhereValueIsEven == [1: 20, a: 30] } - @Test - void iteratingOnMaps(){ - def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"] + def "iteratingOnMaps"() { + when: + def map = [name: "Jerry", age: 42, city: "New York", hobby: "Singing"] - map.each{ entry -> println "$entry.key: $entry.value" } - - map.eachWithIndex{ entry, i -> println "$i $entry.key: $entry.value" } - - map.eachWithIndex{ key, value, i -> println "$i $key: $value" } + then: + map.each { entry -> println "$entry.key: $entry.value" } + map.eachWithIndex { entry, i -> println "$i $entry.key: $entry.value" } + map.eachWithIndex { key, value, i -> println "$i $key: $value" } } - @Test - void filteringAndSearchingMaps(){ - def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"] + def "filteringAndSearchingMaps"() { + given: + def map = [name: "Jerry", age: 42, city: "New York", hobby: "Singing"] - assertTrue(map.find{ it.value == "New York"}.key == "city") + when: + def find = map.find { it.value == "New York" } + def finaAll = map.findAll { it.value == "New York" } + def grep = map.grep { it.value == "New York" } + def every = map.every { it -> it.value instanceof String } + def any = map.any { it -> it.value instanceof String } - assertTrue(map.findAll{ it.value == "New York"} == [city : "New York"]) + then: + find.key == "city" - map.grep{it.value == "New York"}.each{ it -> assertTrue(it.key == "city" && it.value == "New York")} + finaAll instanceof Map + finaAll == [city: "New York"] - assertTrue(map.every{it -> it.value instanceof String} == false) + grep instanceof Collection + grep.each { it -> assert it.key == "city" && it.value == "New York" } - assertTrue(map.any{it -> it.value instanceof String} == true) + every instanceof Boolean + !every + + any instanceof Boolean + any } - @Test - void collect(){ - - def map = [1: [name:"Jerry", age: 42, city: "New York"], - 2: [name:"Long", age: 25, city: "New York"], - 3: [name:"Dustin", age: 29, city: "New York"], - 4: [name:"Dustin", age: 34, city: "New York"]] - - def names = map.collect{entry -> entry.value.name} // returns only list - assertTrue(names == ["Jerry", "Long", "Dustin", "Dustin"]) - - def uniqueNames = map.collect([] as HashSet){entry -> entry.value.name} - assertTrue(uniqueNames == ["Jerry", "Long", "Dustin"] as Set) - - def idNames = map.collectEntries{key, value -> [key, value.name]} - assertTrue(idNames == [1:"Jerry", 2: "Long", 3:"Dustin", 4: "Dustin"]) - - def below30Names = map.findAll{it.value.age < 30}.collect{key, value -> value.name} - assertTrue(below30Names == ["Long", "Dustin"]) + def "collect"() { + given: + def map = [ + 1: [name: "Jerry", age: 42, city: "New York"], + 2: [name: "Long", age: 25, city: "New York"], + 3: [name: "Dustin", age: 29, city: "New York"], + 4: [name: "Dustin", age: 34, city: "New York"] + ] + when: + def names = map.collect { entry -> entry.value.name } // returns only list + def uniqueNames = map.collect { entry -> entry.value.name } + .unique() + def idNames = map.collectEntries { key, value -> [key, value.name] } + def below30Names = map.findAll { it.value.age < 30 } + .collect { key, value -> value.name } + then: + names == ["Jerry", "Long", "Dustin", "Dustin"] + uniqueNames == ["Jerry", "Long", "Dustin"] + idNames == [1: "Jerry", 2: "Long", 3: "Dustin", 4: "Dustin"] + below30Names == ["Long", "Dustin"] } - @Test - void group(){ - def map = [1:20, 2: 40, 3: 11, 4: 93] - - def subMap = map.groupBy{it.value % 2} - println subMap - assertTrue(subMap == [0:[1:20, 2:40 ], 1:[3:11, 4:93]]) + def "group"() { + given: + def map = [1: 20, 2: 40, 3: 11, 4: 93] + when: + def subMap = map.groupBy { it.value % 2 } def keySubMap = map.subMap([1, 2]) - assertTrue(keySubMap == [1:20, 2:40]) + then: + subMap == [0: [1: 20, 2: 40], 1: [3: 11, 4: 93]] + keySubMap == [1: 20, 2: 40] } - @Test - void sorting(){ - def map = [ab:20, a: 40, cb: 11, ba: 93] + def "sorting"() { + given: + def map = [ab: 20, a: 40, cb: 11, ba: 93] + when: def naturallyOrderedMap = map.sort() - assertTrue([a:40, ab:20, ba:93, cb:11] == naturallyOrderedMap) - def compSortedMap = map.sort({ k1, k2 -> k1 <=> k2 } as Comparator) - assertTrue([a:40, ab:20, ba:93, cb:11] == compSortedMap) - def cloSortedMap = map.sort({ it1, it2 -> it1.value <=> it1.value }) - assertTrue([cb:11, ab:20, a:40, ba:93] == cloSortedMap) + then: + naturallyOrderedMap == [a: 40, ab: 20, ba: 93, cb: 11] + compSortedMap == [a: 40, ab: 20, ba: 93, cb: 11] + cloSortedMap == [cb: 11, ab: 20, a: 40, ba: 93] } - } diff --git a/core-groovy-modules/core-groovy-strings/pom.xml b/core-groovy-modules/core-groovy-strings/pom.xml index e51ebfbd4b..fac0f25219 100644 --- a/core-groovy-modules/core-groovy-strings/pom.xml +++ b/core-groovy-modules/core-groovy-strings/pom.xml @@ -103,9 +103,10 @@ - central - https://jcenter.bintray.com + maven_central + Maven Central + https://repo.maven.apache.org/maven2/ - \ No newline at end of file + diff --git a/core-groovy-modules/core-groovy-strings/src/test/groovy/com/baeldung/removeprefix/RemovePrefixTest.groovy b/core-groovy-modules/core-groovy-strings/src/test/groovy/com/baeldung/removeprefix/RemovePrefixTest.groovy index 61b81fe1b2..8b7ce9c355 100644 --- a/core-groovy-modules/core-groovy-strings/src/test/groovy/com/baeldung/removeprefix/RemovePrefixTest.groovy +++ b/core-groovy-modules/core-groovy-strings/src/test/groovy/com/baeldung/removeprefix/RemovePrefixTest.groovy @@ -1,70 +1,74 @@ package com.baeldung.removeprefix -import org.junit.Assert -import org.junit.Test +import spock.lang.Specification -class RemovePrefixTest { +class RemovePrefixTest extends Specification { - - @Test - public void whenCasePrefixIsRemoved_thenReturnTrue() { + def "whenCasePrefixIsRemoved_thenReturnTrue"() { + given: def trimPrefix = { it.startsWith('Groovy-') ? it.minus('Groovy-') : it } - + + when: def actual = trimPrefix("Groovy-Tutorials at Baeldung") def expected = "Tutorials at Baeldung" - Assert.assertEquals(expected, actual) + then: + expected == actual } - @Test - public void whenPrefixIsRemoved_thenReturnTrue() { - + def "whenPrefixIsRemoved_thenReturnTrue"() { + given: String prefix = "groovy-" String trimPrefix = "Groovy-Tutorials at Baeldung" - def actual; - if(trimPrefix.startsWithIgnoreCase(prefix)) { + + when: + def actual + if (trimPrefix.startsWithIgnoreCase(prefix)) { actual = trimPrefix.substring(prefix.length()) } - def expected = "Tutorials at Baeldung" - Assert.assertEquals(expected, actual) + then: + expected == actual } - @Test - public void whenPrefixIsRemovedUsingRegex_thenReturnTrue() { - + def "whenPrefixIsRemovedUsingRegex_thenReturnTrue"() { + given: def regex = ~"^([Gg])roovy-" String trimPrefix = "Groovy-Tutorials at Baeldung" + + when: String actual = trimPrefix - regex - def expected = "Tutorials at Baeldung" - Assert.assertEquals(expected, actual) + then: + expected == actual } - @Test - public void whenPrefixIsRemovedUsingReplaceFirst_thenReturnTrue() { - def regex = ~"^groovy" - String trimPrefix = "groovyTutorials at Baeldung's groovy page" + def "whenPrefixIsRemovedUsingReplaceFirst_thenReturnTrue"() { + given: + def regex = ~"^groovy" + String trimPrefix = "groovyTutorials at Baeldung's groovy page" + + when: String actual = trimPrefix.replaceFirst(regex, "") - def expected = "Tutorials at Baeldung's groovy page" - - Assert.assertEquals(expected, actual) + + then: + expected == actual } - @Test - public void whenPrefixIsRemovedUsingReplaceAll_thenReturnTrue() { - + def "whenPrefixIsRemovedUsingReplaceAll_thenReturnTrue"() { + given: String trimPrefix = "groovyTutorials at Baeldung groovy" + + when: String actual = trimPrefix.replaceAll(/^groovy/, "") - def expected = "Tutorials at Baeldung groovy" - Assert.assertEquals(expected, actual) + then: + expected == actual } - -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/pom.xml b/core-groovy-modules/core-groovy/pom.xml index 413fbde106..cf6cca9e18 100644 --- a/core-groovy-modules/core-groovy/pom.xml +++ b/core-groovy-modules/core-groovy/pom.xml @@ -3,6 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + core-groovy 1.0-SNAPSHOT core-groovy @@ -103,9 +104,10 @@ - central - https://jcenter.bintray.com + maven_central + Maven Central + https://repo.maven.apache.org/maven2/ - \ No newline at end of file + diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy index 4239fa534c..1418947cc7 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy @@ -10,13 +10,14 @@ class ReadFile { int readFileLineByLine(String filePath) { File file = new File(filePath) def line, noOfLines = 0; + file.withReader { reader -> - while ((line = reader.readLine())!=null) - { + while ((line = reader.readLine()) != null) { println "${line}" noOfLines++ } } + return noOfLines } @@ -26,9 +27,7 @@ class ReadFile { * @return */ List readFileInList(String filePath) { - File file = new File(filePath) - def lines = file.readLines() - return lines + return new File(filePath).readLines() } /** @@ -37,9 +36,7 @@ class ReadFile { * @return */ String readFileString(String filePath) { - File file = new File(filePath) - String fileContent = file.text - return fileContent + return new File(filePath).text } /** @@ -48,9 +45,7 @@ class ReadFile { * @return */ String readFileStringWithCharset(String filePath) { - File file = new File(filePath) - String utf8Content = file.getText("UTF-8") - return utf8Content + return new File(filePath).getText("UTF-8") } /** @@ -59,49 +54,44 @@ class ReadFile { * @return */ byte[] readBinaryFile(String filePath) { - File file = new File(filePath) - byte[] binaryContent = file.bytes - return binaryContent + return new File(filePath).bytes } - + /** * More Examples of reading a file * @return */ def moreExamples() { - + //with reader with utf-8 new File("src/main/resources/utf8Content.html").withReader('UTF-8') { reader -> def line - while ((line = reader.readLine())!=null) { + while ((line = reader.readLine()) != null) { println "${line}" } } - - //collect api - def list = new File("src/main/resources/fileContent.txt").collect {it} - - //as operator + + // collect api + def list = new File("src/main/resources/fileContent.txt").collect { it } + + // as operator def array = new File("src/main/resources/fileContent.txt") as String[] - - //eachline - new File("src/main/resources/fileContent.txt").eachLine { line -> - println line - } - + + // eachline + new File("src/main/resources/fileContent.txt").eachLine { println it } + //newInputStream with eachLine - def is = new File("src/main/resources/fileContent.txt").newInputStream() - is.eachLine { - println it + + // try-with-resources automatically closes BufferedInputStream resource + try (def inputStream = new File("src/main/resources/fileContent.txt").newInputStream()) { + inputStream.eachLine { println it } } - is.close() - - //withInputStream + + // withInputStream new File("src/main/resources/fileContent.txt").withInputStream { stream -> stream.eachLine { line -> println line } } } - -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/strings/Concatenate.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/strings/Concatenate.groovy index b3a0852a0b..4a7c3f8529 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/strings/Concatenate.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/strings/Concatenate.groovy @@ -1,9 +1,10 @@ package com.baeldung.strings; class Concatenate { + String first = 'Hello' String last = 'Groovy' - + String doSimpleConcat() { return 'My name is ' + first + ' ' + last } @@ -23,21 +24,28 @@ class Concatenate { String doConcatUsingLeftShiftOperator() { return 'My name is ' << first << ' ' << last } - + String doConcatUsingArrayJoinMethod() { return ['My name is', first, last].join(' ') } String doConcatUsingArrayInjectMethod() { - return [first,' ', last] - .inject(new StringBuffer('My name is '), { initial, name -> initial.append(name); return initial }).toString() + return [first, ' ', last] + .inject(new StringBuffer('My name is '), { initial, name -> initial.append(name) }) + .toString() } - + String doConcatUsingStringBuilder() { - return new StringBuilder().append('My name is ').append(first).append(' ').append(last) + return new StringBuilder().append('My name is ') + .append(first) + .append(' ') + .append(last) } String doConcatUsingStringBuffer() { - return new StringBuffer().append('My name is ').append(first).append(' ').append(last) + return new StringBuffer().append('My name is ') + .append(first) + .append(' ') + .append(last) } -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/AnimalTrait.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/AnimalTrait.groovy index 6ec5cda571..a3fed81c8b 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/AnimalTrait.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/AnimalTrait.groovy @@ -1,8 +1,8 @@ package com.baeldung.traits trait AnimalTrait { - + String basicBehavior() { return "Animalistic!!" } -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Dog.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Dog.groovy index 3e0677ba18..fc53b1bef9 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Dog.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Dog.groovy @@ -1,9 +1,8 @@ package com.baeldung.traits class Dog implements WalkingTrait, SpeakingTrait { - + String speakAndWalk() { WalkingTrait.super.speakAndWalk() } - -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Employee.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Employee.groovy index b3e4285476..16f1fab984 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Employee.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Employee.groovy @@ -1,12 +1,14 @@ package com.baeldung.traits class Employee implements UserTrait { - + + @Override String name() { return 'Bob' } + @Override String lastName() { return "Marley" } -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Human.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Human.groovy index e78d59bbfd..5417334269 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Human.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Human.groovy @@ -1,6 +1,6 @@ package com.baeldung.traits interface Human { - + String lastName() -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/SpeakingTrait.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/SpeakingTrait.groovy index f437a94bd9..969982e8e0 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/SpeakingTrait.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/SpeakingTrait.groovy @@ -1,13 +1,12 @@ package com.baeldung.traits trait SpeakingTrait { - + String basicAbility() { return "Speaking!!" } - + String speakAndWalk() { return "Speak and walk!!" } - -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/UserTrait.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/UserTrait.groovy index 0d395bffcd..1d1d188460 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/UserTrait.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/UserTrait.groovy @@ -1,36 +1,35 @@ package com.baeldung.traits trait UserTrait implements Human { - + + String email + String address + + abstract String name() + String sayHello() { return "Hello!" } - - abstract String name() - + String showName() { - return "Hello, ${name()}!" + return "Hello, ${name()}!" } private String greetingMessage() { return 'Hello, from a private method!' } - + String greet() { def msg = greetingMessage() println msg msg } - + def self() { - return this + return this } - + String showLastName() { return "Hello, ${lastName()}!" } - - String email - String address } - \ No newline at end of file diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/VehicleTrait.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/VehicleTrait.groovy index f5ae8fab30..e29561157c 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/VehicleTrait.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/VehicleTrait.groovy @@ -1,9 +1,9 @@ package com.baeldung trait VehicleTrait extends WheelTrait { - + String showWheels() { - return "Num of Wheels $noOfWheels" + return "Num of Wheels $noOfWheels" } - -} \ No newline at end of file + +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WalkingTrait.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WalkingTrait.groovy index 66cff8809f..84be49ec25 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WalkingTrait.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WalkingTrait.groovy @@ -1,13 +1,13 @@ package com.baeldung.traits trait WalkingTrait { - + String basicAbility() { return "Walking!!" } - + String speakAndWalk() { return "Walk and speak!!" } - -} \ No newline at end of file + +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WheelTrait.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WheelTrait.groovy index 364d5b883e..7f2448e185 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WheelTrait.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WheelTrait.groovy @@ -1,7 +1,6 @@ package com.baeldung trait WheelTrait { - + int noOfWheels - -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy index da1dfc10ba..87cfc79761 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy @@ -1,71 +1,76 @@ package com.baeldung.file import spock.lang.Specification -import spock.lang.Ignore class ReadFileUnitTest extends Specification { ReadFile readFile - void setup () { + void setup() { readFile = new ReadFile() } - def 'Should return number of lines in File using ReadFile.readFileLineByLine given filePath' () { + def 'Should return number of lines in File using ReadFile.readFileLineByLine given filePath'() { given: - def filePath = "src/main/resources/fileContent.txt" + def filePath = "src/main/resources/fileContent.txt" + when: - def noOfLines = readFile.readFileLineByLine(filePath) + def noOfLines = readFile.readFileLineByLine(filePath) + then: - noOfLines - noOfLines instanceof Integer - assert noOfLines, 3 - } - - def 'Should return File Content in list of lines using ReadFile.readFileInList given filePath' () { - given: - def filePath = "src/main/resources/fileContent.txt" - when: - def lines = readFile.readFileInList(filePath) - then: - lines - lines instanceof List - assert lines.size(), 3 - } - - def 'Should return file content in string using ReadFile.readFileString given filePath' () { - given: - def filePath = "src/main/resources/fileContent.txt" - when: - def fileContent = readFile.readFileString(filePath) - then: - fileContent - fileContent instanceof String - fileContent.contains("""Line 1 : Hello World!!! -Line 2 : This is a file content. -Line 3 : String content""") - + noOfLines + noOfLines instanceof Integer + noOfLines == 3 } - def 'Should return UTF-8 encoded file content in string using ReadFile.readFileStringWithCharset given filePath' () { + def 'Should return File Content in list of lines using ReadFile.readFileInList given filePath'() { given: - def filePath = "src/main/resources/utf8Content.html" + def filePath = "src/main/resources/fileContent.txt" + when: - def encodedContent = readFile.readFileStringWithCharset(filePath) + def lines = readFile.readFileInList(filePath) + then: - encodedContent - encodedContent instanceof String + lines + lines instanceof List + lines.size() == 3 } - - def 'Should return binary file content in byte array using ReadFile.readBinaryFile given filePath' () { + + def 'Should return file content in string using ReadFile.readFileString given filePath'() { given: - def filePath = "src/main/resources/sample.png" + def filePath = "src/main/resources/fileContent.txt" + when: - def binaryContent = readFile.readBinaryFile(filePath) + def fileContent = readFile.readFileString(filePath) + then: - binaryContent - binaryContent instanceof byte[] - binaryContent.length == 329 + fileContent + fileContent instanceof String + fileContent.contains(["Line 1 : Hello World!!!", "Line 2 : This is a file content.", "Line 3 : String content"].join("\r\n")) } - -} \ No newline at end of file + + def 'Should return UTF-8 encoded file content in string using ReadFile.readFileStringWithCharset given filePath'() { + given: + def filePath = "src/main/resources/utf8Content.html" + + when: + def encodedContent = readFile.readFileStringWithCharset(filePath) + + then: + encodedContent + encodedContent instanceof String + } + + def 'Should return binary file content in byte array using ReadFile.readBinaryFile given filePath'() { + given: + def filePath = "src/main/resources/sample.png" + + when: + def binaryContent = readFile.readBinaryFile(filePath) + + then: + binaryContent + binaryContent instanceof byte[] + binaryContent.length == 329 + } +} diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/groovy/sql/SqlTest.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/groovy/sql/SqlTest.groovy index ac96a55773..da982744e9 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/groovy/sql/SqlTest.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/groovy/sql/SqlTest.groovy @@ -1,28 +1,29 @@ package com.baeldung.groovy.sql import groovy.sql.GroovyResultSet -import groovy.sql.GroovyRowResult import groovy.sql.Sql -import groovy.transform.CompileStatic -import static org.junit.Assert.* import org.junit.Test +import static org.junit.Assert.* + class SqlTest { - final Map dbConnParams = [url: 'jdbc:hsqldb:mem:testDB', user: 'sa', password: '', driver: 'org.hsqldb.jdbc.JDBCDriver'] + final Map dbConnParams = [url: 'jdbc:hsqldb:mem:testDB', + user: 'sa', + password: '', + driver: 'org.hsqldb.jdbc.JDBCDriver'] @Test void whenNewSqlInstance_thenDbIsAccessed() { def sql = Sql.newInstance(dbConnParams) sql.close() - sql.close() } @Test void whenTableDoesNotExist_thenSelectFails() { try { Sql.withInstance(dbConnParams) { Sql sql -> - sql.eachRow('select * from PROJECT') {} + sql.eachRow('SELECT * FROM PROJECT') {} } fail("An exception should have been thrown") @@ -34,12 +35,12 @@ class SqlTest { @Test void whenTableCreated_thenSelectIsPossible() { Sql.withInstance(dbConnParams) { Sql sql -> - def result = sql.execute 'create table PROJECT_1 (id integer not null, name varchar(50), url varchar(100))' + def result = sql.execute 'CREATE TABLE PROJECT_1 (ID INTEGER NOT NULL, NAME VARCHAR(50), URL VARCHAR(100))' assertEquals(0, sql.updateCount) assertFalse(result) - result = sql.execute('select * from PROJECT_1') + result = sql.execute('SELECT * FROM PROJECT_1') assertTrue(result) } @@ -48,7 +49,7 @@ class SqlTest { @Test void whenIdentityColumn_thenInsertReturnsNewId() { Sql.withInstance(dbConnParams) { Sql sql -> - sql.execute 'create table PROJECT_2 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_2 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' def ids = sql.executeInsert("INSERT INTO PROJECT_2 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')") assertEquals(0, ids[0][0]) @@ -62,9 +63,10 @@ class SqlTest { @Test void whenUpdate_thenNumberOfAffectedRows() { Sql.withInstance(dbConnParams) { Sql sql -> - sql.execute 'create table PROJECT_3 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_3 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' sql.executeInsert("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')") sql.executeInsert("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')") + def count = sql.executeUpdate("UPDATE PROJECT_3 SET URL = 'https://' + URL") assertEquals(2, count) @@ -74,7 +76,7 @@ class SqlTest { @Test void whenEachRow_thenResultSetHasProperties() { Sql.withInstance(dbConnParams) { Sql sql -> - sql.execute 'create table PROJECT_4 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_4 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' sql.executeInsert("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')") sql.executeInsert("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')") @@ -93,7 +95,7 @@ class SqlTest { @Test void whenPagination_thenSubsetIsReturned() { Sql.withInstance(dbConnParams) { Sql sql -> - sql.execute 'create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')") sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')") def rows = sql.rows('SELECT * FROM PROJECT_5 ORDER BY NAME', 1, 1) @@ -106,9 +108,11 @@ class SqlTest { @Test void whenParameters_thenReplacement() { Sql.withInstance(dbConnParams) { Sql sql -> - sql.execute 'create table PROJECT_6 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' - sql.execute('INSERT INTO PROJECT_6 (NAME, URL) VALUES (?, ?)', 'tutorials', 'github.com/eugenp/tutorials') - sql.execute("INSERT INTO PROJECT_6 (NAME, URL) VALUES (:name, :url)", [name: 'REST with Spring', url: 'github.com/eugenp/REST-With-Spring']) + sql.execute 'CREATE TABLE PROJECT_6 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute('INSERT INTO PROJECT_6 (NAME, URL) VALUES (?, ?)', + 'tutorials', 'github.com/eugenp/tutorials') + sql.execute("INSERT INTO PROJECT_6 (NAME, URL) VALUES (:name, :url)", + [name: 'REST with Spring', url: 'github.com/eugenp/REST-With-Spring']) def rows = sql.rows("SELECT * FROM PROJECT_6 WHERE NAME = 'tutorials'") @@ -123,7 +127,7 @@ class SqlTest { @Test void whenParametersInGString_thenReplacement() { Sql.withInstance(dbConnParams) { Sql sql -> - sql.execute 'create table PROJECT_7 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_7 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' sql.execute "INSERT INTO PROJECT_7 (NAME, URL) VALUES (${'tutorials'}, ${'github.com/eugenp/tutorials'})" def name = 'REST with Spring' def url = 'github.com/eugenp/REST-With-Spring' @@ -143,7 +147,7 @@ class SqlTest { void whenTransactionRollback_thenNoDataInserted() { Sql.withInstance(dbConnParams) { Sql sql -> sql.withTransaction { - sql.execute 'create table PROJECT_8 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_8 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' sql.executeInsert("INSERT INTO PROJECT_8 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')") sql.executeInsert("INSERT INTO PROJECT_8 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')") sql.rollback() @@ -159,7 +163,7 @@ class SqlTest { void whenTransactionRollbackThenCommit_thenOnlyLastInserted() { Sql.withInstance(dbConnParams) { Sql sql -> sql.withTransaction { - sql.execute 'create table PROJECT_9 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_9 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')") sql.rollback() sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')") @@ -179,11 +183,12 @@ class SqlTest { Sql.withInstance(dbConnParams) { Sql sql -> try { sql.withTransaction { - sql.execute 'create table PROJECT_10 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_10 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' sql.executeInsert("INSERT INTO PROJECT_10 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')") throw new Exception('rollback') } - } catch (ignored) {} + } catch (ignored) { + } def rows = sql.rows("SELECT * FROM PROJECT_10") @@ -196,11 +201,12 @@ class SqlTest { Sql.withInstance(dbConnParams) { Sql sql -> try { sql.cacheConnection { - sql.execute 'create table PROJECT_11 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_11 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' sql.executeInsert("INSERT INTO PROJECT_11 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')") throw new Exception('This does not rollback') } - } catch (ignored) {} + } catch (ignored) { + } def rows = sql.rows("SELECT * FROM PROJECT_11") @@ -211,7 +217,7 @@ class SqlTest { /*@Test void whenModifyResultSet_thenDataIsChanged() { Sql.withInstance(dbConnParams) { Sql sql -> - sql.execute 'create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')") sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')") diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/json/JsonParserTest.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/json/JsonParserTest.groovy index e65550a3be..fa7b2fd3c8 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/json/JsonParserTest.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/json/JsonParserTest.groovy @@ -1,5 +1,6 @@ package com.baeldung.json +import groovy.json.JsonGenerator import spock.lang.Specification import java.text.SimpleDateFormat @@ -8,20 +9,42 @@ class JsonParserTest extends Specification { JsonParser jsonParser - void setup () { + void setup() { jsonParser = new JsonParser() } - def 'Should parse to Account given Json String' () { + def 'Should parse to Account given Json String'() { given: - def json = '{"id":"1234","value":15.6}' + def json = '{"id":"1234","value":15.6}' + when: - def account = jsonParser.toObject(json) + def account = jsonParser.toObject(json) + then: - account - account instanceof Account - account.id == '1234' - account.value == 15.6 + account + account instanceof Account + account.id == '1234' + account.value == 15.6 + } + + def 'Should format date and exclude value field'() { + given: + def account = new Account( + id: '123', + value: 15.6, + createdAt: new SimpleDateFormat('MM/dd/yyyy').parse('14/01/2023') + ) + + def jsonGenerator = new JsonGenerator.Options() + .dateFormat('MM/dd/yyyy') + .excludeFieldsByName('value') + .build() + + when: + def accountToJson = jsonGenerator.toJson(account) + + then: + accountToJson == '{"createdAt":"01/31/2024","id":"123"}' } /*def 'Should parse to Account given Json String with date property' () { @@ -52,15 +75,20 @@ class JsonParserTest extends Specification { json == '{"value":15.6,"createdAt":"2018-01-01T00:00:00+0000","id":"123"}' }*/ - def 'Should prettify given a json string' () { + def 'Should prettify given a json string'() { given: - String json = '{"value":15.6,"createdAt":"01/01/2018","id":"123456"}' + String json = '{"value":15.6,"createdAt":"01/01/2018","id":"123456"}' + when: - def jsonPretty = jsonParser.prettyfy(json) + def jsonPretty = jsonParser.prettyfy(json) + then: - jsonPretty - jsonPretty == '{\n "value": 15.6,\n "createdAt": "01/01/2018",\n "id": "123456"\n}' + jsonPretty + jsonPretty == '''\ +{ + "value": 15.6, + "createdAt": "01/01/2018", + "id": "123456" +}''' } - - } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/ConcatenateTest.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/ConcatenateTest.groovy index 3ef4a5d460..e4a178a14b 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/ConcatenateTest.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/ConcatenateTest.groovy @@ -1,101 +1,88 @@ -import com.baeldung.strings.Concatenate; +import com.baeldung.strings.Concatenate +import spock.lang.Specification -class ConcatenateTest extends GroovyTestCase { - - void testSimpleConcat() { - def name = new Concatenate() - name.first = 'Joe'; - name.last = 'Smith'; - def expected = 'My name is Joe Smith' - assertToString(name.doSimpleConcat(), expected) - } - - void testConcatUsingGString() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingGString(), expected) - } - - void testConcatUsingGStringClosures() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingGStringClosures(), expected) - } - - void testConcatUsingStringConcatMethod() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingStringConcatMethod(), expected) +class ConcatenateTest extends Specification { + + final Concatenate NAME = new Concatenate(first: 'Joe', last: 'Smith') + final String EXPECTED = "My name is Joe Smith"; + + def "SimpleConcat"() { + expect: + NAME.doSimpleConcat() == EXPECTED } - void testConcatUsingLeftShiftOperator() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingLeftShiftOperator(), expected) + def "ConcatUsingGString"() { + expect: + NAME.doConcatUsingGString() == EXPECTED } - void testConcatUsingArrayJoinMethod() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingArrayJoinMethod(), expected) + def "ConcatUsingGStringClosures"() { + expect: + NAME.doConcatUsingGStringClosures() == EXPECTED } - void testConcatUsingArrayInjectMethod() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingArrayInjectMethod(), expected) + def "ConcatUsingStringConcatMethod"() { + expect: + NAME.doConcatUsingStringConcatMethod() == EXPECTED } - void testConcatUsingStringBuilder() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingStringBuilder(), expected) + def "ConcatUsingLeftShiftOperator"() { + expect: + NAME.doConcatUsingLeftShiftOperator() == EXPECTED } - void testConcatUsingStringBuffer() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingStringBuffer(), expected) + def "ConcatUsingArrayJoinMethod"() { + expect: + NAME.doConcatUsingArrayJoinMethod() == EXPECTED } - void testConcatMultilineUsingStringConcatMethod() { - def name = new Concatenate() - name.first = '''Joe + def "ConcatUsingArrayInjectMethod"() { + expect: + NAME.doConcatUsingArrayInjectMethod() == EXPECTED + } + + def "ConcatUsingStringBuilder"() { + expect: + NAME.doConcatUsingStringBuilder() == EXPECTED + } + + def "ConcatUsingStringBuffer"() { + expect: + NAME.doConcatUsingStringBuffer() == EXPECTED + } + + def "ConcatMultilineUsingStringConcatMethod"() { + when: + NAME.first = '''Joe Smith - '''; - name.last = 'Junior'; + ''' + NAME.last = 'Junior' + + then: def expected = '''My name is Joe Smith - Junior'''; - assertToString(name.doConcatUsingStringConcatMethod(), expected) + Junior''' + NAME.doConcatUsingStringConcatMethod() == expected } - void testGStringvsClosure(){ - def first = "Joe"; - def last = "Smith"; - def eagerGString = "My name is $first $last" - def lazyGString = "My name is ${-> first} ${-> last}" + def "GStringvsClosure"() { + given: + def eagerGString = "My name is $NAME.first $NAME.last" + def lazyGString = "My name is ${-> NAME.first} ${-> NAME.last}" - assert eagerGString == "My name is Joe Smith" - assert lazyGString == "My name is Joe Smith" - first = "David"; - assert eagerGString == "My name is Joe Smith" - assert lazyGString == "My name is David Smith" - } + expect: + eagerGString == "My name is Joe Smith" + lazyGString == "My name is Joe Smith" + } + + def "LazyVsEager"() { + given: + def eagerGString = "My name is $NAME.first $NAME.last" + def lazyGString = "My name is ${-> NAME.first} ${-> NAME.last}" + NAME.first = "David" + + expect: + eagerGString == "My name is Joe Smith" + lazyGString == "My name is David Smith" + } } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/StringMatchingSpec.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/StringMatchingSpec.groovy index 3865bc73fa..89202d9500 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/StringMatchingSpec.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/StringMatchingSpec.groovy @@ -13,7 +13,7 @@ class StringMatchingSpec extends Specification { expect: p instanceof Pattern - and: "you can use slash strings to avoid escaping of blackslash" + and: "you can use slash strings to avoid escaping of backslash" def digitPattern = ~/\d*/ digitPattern.matcher('4711').matches() } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy index 48cf48fa8a..cce6ede989 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy @@ -1,110 +1,119 @@ package com.baeldung.stringtoint -import org.junit.Test +import spock.lang.Specification import java.text.DecimalFormat -import static org.junit.Assert.assertEquals -import static org.junit.Assert.assertNull +class ConvertStringToInt extends Specification { -class ConvertStringToInt { + final String STRING_NUM = "123" + final int EXPECTED_INT = 123 - @Test - void givenString_whenUsingAsInteger_thenConvertToInteger() { - def stringNum = "123" + def "givenString_whenUsingAsInteger_thenConvertToInteger"() { + given: def invalidString = "123a" - Integer expectedInteger = 123 - Integer integerNum = stringNum as Integer + Integer integerNum = STRING_NUM as Integer + + when: def intNum = invalidString?.isInteger() ? invalidString as Integer : null - assertNull(null, intNum) - assertEquals(integerNum, expectedInteger) + then: + intNum == null + integerNum == EXPECTED_INT } - @Test - void givenString_whenUsingAsInt_thenConvertToInt() { - def stringNum = "123" - int expectedInt = 123 - int intNum = stringNum as int + def "givenString_whenUsingAsInt_thenConvertToInt"() { + given: + int intNum = STRING_NUM as int - assertEquals(intNum, expectedInt) + expect: + intNum == EXPECTED_INT } - @Test - void givenString_whenUsingToInteger_thenConvertToInteger() { - def stringNum = "123" - int expectedInt = 123 - int intNum = stringNum.toInteger() + def "givenString_whenUsingToInteger_thenConvertToInteger"() { + given: + int intNum = STRING_NUM.toInteger() - assertEquals(intNum, expectedInt) + expect: + intNum == EXPECTED_INT } - @Test - void givenString_whenUsingParseInt_thenConvertToInteger() { - def stringNum = "123" - int expectedInt = 123 - int intNum = Integer.parseInt(stringNum) + def "givenString_whenUsingParseInt_thenConvertToInteger"() { + given: + int intNum = Integer.parseInt(STRING_NUM) - assertEquals(intNum, expectedInt) + expect: + intNum == EXPECTED_INT } - @Test - void givenString_whenUsingValueOf_thenConvertToInteger() { - def stringNum = "123" - int expectedInt = 123 - int intNum = Integer.valueOf(stringNum) + def "givenString_whenUsingValueOf_thenConvertToInteger"() { + given: + int intNum = Integer.valueOf(STRING_NUM) - assertEquals(intNum, expectedInt) + expect: + intNum == EXPECTED_INT } - @Test - void givenString_whenUsingIntValue_thenConvertToInteger() { - def stringNum = "123" - int expectedInt = 123 - int intNum = new Integer(stringNum).intValue() + def "givenString_whenUsingIntValue_thenConvertToInteger"() { + given: + int intNum = Integer.valueOf(STRING_NUM).intValue() - assertEquals(intNum, expectedInt) + expect: + intNum == EXPECTED_INT } - @Test - void givenString_whenUsingNewInteger_thenConvertToInteger() { - def stringNum = "123" - int expectedInt = 123 - int intNum = new Integer(stringNum) + def "givenString_whenUsingNewInteger_thenConvertToInteger"() { + given: + Integer intNum = Integer.valueOf(STRING_NUM) - assertEquals(intNum, expectedInt) + expect: + intNum == EXPECTED_INT } - @Test - void givenString_whenUsingDecimalFormat_thenConvertToInteger() { - def stringNum = "123" - int expectedInt = 123 + def "givenString_whenUsingDecimalFormat_thenConvertToInteger"() { + given: DecimalFormat decimalFormat = new DecimalFormat("#") - int intNum = decimalFormat.parse(stringNum).intValue() - assertEquals(intNum, expectedInt) + when: + int intNum = decimalFormat.parse(STRING_NUM).intValue() + + then: + intNum == EXPECTED_INT } - @Test(expected = NumberFormatException.class) - void givenInvalidString_whenUsingAs_thenThrowNumberFormatException() { + def "givenInvalidString_whenUsingAs_thenThrowNumberFormatException"() { + given: def invalidString = "123a" + + when: invalidString as Integer + + then: + thrown(NumberFormatException) } - @Test(expected = NullPointerException.class) - void givenNullString_whenUsingToInteger_thenThrowNullPointerException() { + def "givenNullString_whenUsingToInteger_thenThrowNullPointerException"() { + given: def invalidString = null + + when: invalidString.toInteger() + + then: + thrown(NullPointerException) } - @Test - void givenString_whenUsingIsInteger_thenCheckIfCorrectValue() { + def "givenString_whenUsingIsInteger_thenCheckIfCorrectValue"() { + given: def invalidString = "123a" def validString = "123" + + when: def invalidNum = invalidString?.isInteger() ? invalidString as Integer : false def correctNum = validString?.isInteger() ? validString as Integer : false - assertEquals(false, invalidNum) - assertEquals(123, correctNum) + then: + !invalidNum + correctNum == 123 } } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/CharacterInGroovy.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/CharacterInGroovy.groovy index c043723d95..30365ec9d7 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/CharacterInGroovy.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/CharacterInGroovy.groovy @@ -1,19 +1,18 @@ package groovy.com.baeldung.stringtypes -import org.junit.Assert -import org.junit.Test +import spock.lang.Specification -class CharacterInGroovy { +class CharacterInGroovy extends Specification { - @Test - void 'character'() { + def 'character'() { + given: char a = 'A' as char char b = 'B' as char char c = (char) 'C' - Assert.assertTrue(a instanceof Character) - Assert.assertTrue(b instanceof Character) - Assert.assertTrue(c instanceof Character) + expect: + a instanceof Character + b instanceof Character + c instanceof Character } - } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/DoubleQuotedString.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/DoubleQuotedString.groovy index a730244d0a..e1074145f4 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/DoubleQuotedString.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/DoubleQuotedString.groovy @@ -1,67 +1,76 @@ package groovy.com.baeldung.stringtypes -import org.junit.Assert -import org.junit.Test +import spock.lang.Specification -class DoubleQuotedString { +class DoubleQuotedString extends Specification { - @Test - void 'escape double quoted string'() { + def 'escape double quoted string'() { + given: def example = "Hello \"world\"!" - println(example) + expect: + example == 'Hello "world"!' } - @Test - void 'String ang GString'() { + def 'String ang GString'() { + given: def string = "example" def stringWithExpression = "example${2}" - Assert.assertTrue(string instanceof String) - Assert.assertTrue(stringWithExpression instanceof GString) - Assert.assertTrue(stringWithExpression.toString() instanceof String) + expect: + string instanceof String + stringWithExpression instanceof GString + stringWithExpression.toString() instanceof String } - @Test - void 'placeholder with variable'() { + def 'placeholder with variable'() { + given: def name = "John" + + when: def helloName = "Hello $name!".toString() - Assert.assertEquals("Hello John!", helloName) + then: + helloName == "Hello John!" } - @Test - void 'placeholder with expression'() { + def 'placeholder with expression'() { + given: def result = "result is ${2 * 2}".toString() - Assert.assertEquals("result is 4", result) + expect: + result == "result is 4" } - @Test - void 'placeholder with dotted access'() { + def 'placeholder with dotted access'() { + given: def person = [name: 'John'] + when: def myNameIs = "I'm $person.name, and you?".toString() - Assert.assertEquals("I'm John, and you?", myNameIs) + then: + myNameIs == "I'm John, and you?" } - @Test - void 'placeholder with method call'() { + def 'placeholder with method call'() { + given: def name = 'John' + when: def result = "Uppercase name: ${name.toUpperCase()}".toString() - Assert.assertEquals("Uppercase name: JOHN", result) + then: + result == "Uppercase name: JOHN" } - @Test - void 'GString and String hashcode'() { + def 'GString and String hashcode'() { + given: def string = "2+2 is 4" def gstring = "2+2 is ${4}" - Assert.assertTrue(string.hashCode() != gstring.hashCode()) + expect: + string.hashCode() != gstring.hashCode() } - } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/SingleQuotedString.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/SingleQuotedString.groovy index 569991b788..924515570c 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/SingleQuotedString.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/SingleQuotedString.groovy @@ -1,15 +1,14 @@ package groovy.com.baeldung.stringtypes -import org.junit.Assert -import org.junit.Test +import spock.lang.Specification -class SingleQuotedString { +class SingleQuotedString extends Specification { - @Test - void 'single quoted string'() { - def example = 'Hello world' + def 'single quoted string'() { + given: + def example = 'Hello world!' - Assert.assertEquals('Hello world!', 'Hello' + ' world!') + expect: + example == 'Hello' + ' world!' } - } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/Strings.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/Strings.groovy index e45f352285..9d29210d81 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/Strings.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/Strings.groovy @@ -1,26 +1,29 @@ package groovy.com.baeldung.stringtypes -import org.junit.Assert -import org.junit.Test +import spock.lang.Specification -class Strings { +class Strings extends Specification { - @Test - void 'string interpolation '() { + def 'string interpolation '() { + given: def name = "Kacper" + when: def result = "Hello ${name}!" - Assert.assertEquals("Hello Kacper!", result.toString()) + then: + result.toString() == "Hello Kacper!" } - @Test - void 'string concatenation'() { + def 'string concatenation'() { + given: def first = "first" def second = "second" + when: def concatenation = first + second - Assert.assertEquals("firstsecond", concatenation) + then: + concatenation == "firstsecond" } } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/traits/TraitsUnitTest.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/traits/TraitsUnitTest.groovy index 85130e8f07..b47cba6437 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/traits/TraitsUnitTest.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/traits/TraitsUnitTest.groovy @@ -7,108 +7,111 @@ class TraitsUnitTest extends Specification { Employee employee Dog dog - void setup () { + void setup() { employee = new Employee() dog = new Dog() } - def 'Should return msg string when using Employee.sayHello method provided by UserTrait' () { + def 'Should return msg string when using Employee.sayHello method provided by UserTrait'() { when: - def msg = employee.sayHello() + def msg = employee.sayHello() + then: - msg - msg instanceof String - assert msg == "Hello!" + msg + msg instanceof String + msg == "Hello!" } - - def 'Should return displayMsg string when using Employee.showName method' () { + + def 'Should return displayMsg string when using Employee.showName method'() { when: - def displayMsg = employee.showName() + def displayMsg = employee.showName() + then: - displayMsg - displayMsg instanceof String - assert displayMsg == "Hello, Bob!" + displayMsg + displayMsg instanceof String + displayMsg == "Hello, Bob!" } - - def 'Should return greetMsg string when using Employee.greet method' () { + + def 'Should return greetMsg string when using Employee.greet method'() { when: - def greetMsg = employee.greet() + def greetMsg = employee.greet() + then: - greetMsg - greetMsg instanceof String - assert greetMsg == "Hello, from a private method!" + greetMsg + greetMsg instanceof String + greetMsg == "Hello, from a private method!" } - - def 'Should return MissingMethodException when using Employee.greetingMessage method' () { + + def 'Should return MissingMethodException when using Employee.greetingMessage method'() { when: - def exception - try { - employee.greetingMessage() - }catch(Exception e) { - exception = e - } - + employee.greetingMessage() + then: - exception - exception instanceof groovy.lang.MissingMethodException - assert exception.message == "No signature of method: com.baeldung.traits.Employee.greetingMessage()"+ - " is applicable for argument types: () values: []" + thrown(MissingMethodException) + specificationContext.thrownException.message == + "No signature of method: com.baeldung.traits.Employee.greetingMessage() is applicable for argument types: () values: []" } - - def 'Should return employee instance when using Employee.whoAmI method' () { + + def 'Should return employee instance when using Employee.whoAmI method'() { when: - def emp = employee.self() + def emp = employee.self() + then: - emp - emp instanceof Employee - assert emp.is(employee) + emp + emp instanceof Employee + emp.is(employee) } - - def 'Should display lastName when using Employee.showLastName method' () { + + def 'Should display lastName when using Employee.showLastName method'() { when: - def lastNameMsg = employee.showLastName() + def lastNameMsg = employee.showLastName() + then: - lastNameMsg - lastNameMsg instanceof String - assert lastNameMsg == "Hello, Marley!" + lastNameMsg + lastNameMsg instanceof String + lastNameMsg == "Hello, Marley!" } - - def 'Should be able to define properties of UserTrait in Employee instance' () { + + def 'Should be able to define properties of UserTrait in Employee instance'() { when: - employee = new Employee(email: "a@e.com", address: "baeldung.com") + employee = new Employee(email: "a@e.com", address: "baeldung.com") + then: - employee - employee instanceof Employee - assert employee.email == "a@e.com" - assert employee.address == "baeldung.com" + employee + employee instanceof Employee + employee.email == "a@e.com" + employee.address == "baeldung.com" } - - def 'Should execute basicAbility method from SpeakingTrait and return msg string' () { + + def 'Should execute basicAbility method from SpeakingTrait and return msg string'() { when: - def speakMsg = dog.basicAbility() + def speakMsg = dog.basicAbility() + then: - speakMsg - speakMsg instanceof String - assert speakMsg == "Speaking!!" + speakMsg + speakMsg instanceof String + speakMsg == "Speaking!!" } - - def 'Should verify multiple inheritance with traits and execute overridden traits method' () { + + def 'Should verify multiple inheritance with traits and execute overridden traits method'() { when: - def walkSpeakMsg = dog.speakAndWalk() - println walkSpeakMsg + def walkSpeakMsg = dog.speakAndWalk() + println walkSpeakMsg + then: - walkSpeakMsg - walkSpeakMsg instanceof String - assert walkSpeakMsg == "Walk and speak!!" + walkSpeakMsg + walkSpeakMsg instanceof String + walkSpeakMsg == "Walk and speak!!" } - - def 'Should implement AnimalTrait at runtime and access basicBehavior method' () { + + def 'Should implement AnimalTrait at runtime and access basicBehavior method'() { when: - def dogInstance = new Dog() as AnimalTrait - def basicBehaviorMsg = dogInstance.basicBehavior() + def dogInstance = new Dog() as AnimalTrait + def basicBehaviorMsg = dogInstance.basicBehavior() + then: - basicBehaviorMsg - basicBehaviorMsg instanceof String - assert basicBehaviorMsg == "Animalistic!!" + basicBehaviorMsg + basicBehaviorMsg instanceof String + basicBehaviorMsg == "Animalistic!!" } -} \ No newline at end of file +} diff --git a/core-groovy-modules/pom.xml b/core-groovy-modules/pom.xml index e1ff538942..6faa7f94c8 100644 --- a/core-groovy-modules/pom.xml +++ b/core-groovy-modules/pom.xml @@ -21,12 +21,12 @@ - 2.5.7 - 2.5.6 - 2.5.6 - 2.4.0 - 1.1-groovy-2.4 - 1.6 + 3.0.15 + 3.0.15 + 3.0.15 + 2.7.1 + 2.3-groovy-3.0 + 2.1.0 - \ No newline at end of file + diff --git a/core-java-modules/core-java-17/README.md b/core-java-modules/core-java-17/README.md index 9f39b0289f..1af860b7c4 100644 --- a/core-java-modules/core-java-17/README.md +++ b/core-java-modules/core-java-17/README.md @@ -6,3 +6,4 @@ - [New Features in Java 17](https://www.baeldung.com/java-17-new-features) - [Random Number Generators in Java 17](https://www.baeldung.com/java-17-random-number-generators) - [Sealed Classes and Interfaces in Java](https://www.baeldung.com/java-sealed-classes-interfaces) +- [Migrate From Java 8 to Java 17](https://www.baeldung.com/java-migrate-8-to-17) diff --git a/core-java-modules/core-java-17/src/main/java/com/baeldung/java8to17/Address.java b/core-java-modules/core-java-17/src/main/java/com/baeldung/java8to17/Address.java new file mode 100644 index 0000000000..b654ffe2c5 --- /dev/null +++ b/core-java-modules/core-java-17/src/main/java/com/baeldung/java8to17/Address.java @@ -0,0 +1,40 @@ +package com.baeldung.java8to17; + +public class Address { + + private String street; + private String city; + private String pin; + + public Address(String street, String city, String pin) { + super(); + this.street = street; + this.city = city; + this.pin = pin; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getPin() { + return pin; + } + + public void setPin(String pin) { + this.pin = pin; + } + +} diff --git a/core-java-modules/core-java-17/src/main/java/com/baeldung/java8to17/Circle.java b/core-java-modules/core-java-17/src/main/java/com/baeldung/java8to17/Circle.java new file mode 100644 index 0000000000..1e346653cf --- /dev/null +++ b/core-java-modules/core-java-17/src/main/java/com/baeldung/java8to17/Circle.java @@ -0,0 +1,4 @@ +package com.baeldung.java8to17; + +public record Circle(double radius) implements Shape { +} \ No newline at end of file diff --git a/core-java-modules/core-java-17/src/main/java/com/baeldung/java8to17/Person.java b/core-java-modules/core-java-17/src/main/java/com/baeldung/java8to17/Person.java new file mode 100644 index 0000000000..a6c9f50fc8 --- /dev/null +++ b/core-java-modules/core-java-17/src/main/java/com/baeldung/java8to17/Person.java @@ -0,0 +1,30 @@ +package com.baeldung.java8to17; + +public class Person { + + private String name; + private Address address; + + public Person(String name, Address address) { + super(); + this.name = name; + this.address = address; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + +} diff --git a/core-java-modules/core-java-17/src/main/java/com/baeldung/java8to17/Rectangle.java b/core-java-modules/core-java-17/src/main/java/com/baeldung/java8to17/Rectangle.java new file mode 100644 index 0000000000..79d2f0358b --- /dev/null +++ b/core-java-modules/core-java-17/src/main/java/com/baeldung/java8to17/Rectangle.java @@ -0,0 +1,4 @@ +package com.baeldung.java8to17; + +public record Rectangle(double length, double width) implements Shape { +} \ No newline at end of file diff --git a/core-java-modules/core-java-17/src/main/java/com/baeldung/java8to17/Shape.java b/core-java-modules/core-java-17/src/main/java/com/baeldung/java8to17/Shape.java new file mode 100644 index 0000000000..60b5193468 --- /dev/null +++ b/core-java-modules/core-java-17/src/main/java/com/baeldung/java8to17/Shape.java @@ -0,0 +1,5 @@ +package com.baeldung.java8to17; + +public interface Shape { + +} diff --git a/core-java-modules/core-java-17/src/main/java/com/baeldung/java8to17/Student.java b/core-java-modules/core-java-17/src/main/java/com/baeldung/java8to17/Student.java new file mode 100644 index 0000000000..056bc4b7d5 --- /dev/null +++ b/core-java-modules/core-java-17/src/main/java/com/baeldung/java8to17/Student.java @@ -0,0 +1,5 @@ +package com.baeldung.java8to17; + +public record Student(int rollNo, String name) { + +} diff --git a/core-java-modules/core-java-17/src/test/java/com/baeldung/java17/Java8to17ExampleUnitTest.java b/core-java-modules/core-java-17/src/test/java/com/baeldung/java17/Java8to17ExampleUnitTest.java new file mode 100644 index 0000000000..950fc70988 --- /dev/null +++ b/core-java-modules/core-java-17/src/test/java/com/baeldung/java17/Java8to17ExampleUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.java17; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertThrows; + +import java.util.Arrays; + +import org.junit.jupiter.api.Test; + +import com.baeldung.java8to17.Address; +import com.baeldung.java8to17.Circle; +import com.baeldung.java8to17.Person; +import com.baeldung.java8to17.Rectangle; +import com.baeldung.java8to17.Student; + +public class Java8to17ExampleUnitTest { + + @Test + void givenMultiLineText_whenUsingTextBlock_thenStringIsReturned() { + String value = """ + This is a + Multi-line + Text + """; + + assertThat(value).isEqualTo("This is a\nMulti-line\nText\n"); + } + + @Test + void givenString_whenUsingUtilFunctions_thenReturnsExpectedResult() { + assertThat(" ".isBlank()); + assertThat("Twinkle ".repeat(2)).isEqualTo("Twinkle Twinkle "); + assertThat("Format Line".indent(4)).isEqualTo(" Format Line\n"); + assertThat("Line 1 \n Line2".lines()).asList().size().isEqualTo(2); + assertThat(" Text with white spaces ".strip()).isEqualTo("Text with white spaces"); + assertThat("Car, Bus, Train".transform(s1 -> Arrays.asList(s1.split(","))).get(0)).isEqualTo("Car"); + } + + @Test + void givenDataModel_whenUsingRecordType_thenBehavesLikeDTO() { + Student student = new Student(10, "Priya"); + Student student2 = new Student(10, "Priya"); + + assertThat(student.rollNo()).isEqualTo(10); + assertThat(student.name()).isEqualTo("Priya"); + assertThat(student.equals(student2)); + assertThat(student.hashCode()).isEqualTo(student2.hashCode()); + } + + @Test + void givenObject_whenThrowingNPE_thenReturnsHelpfulMessage() { + Person student = new Person("Lakshmi", new Address("35, West Street", null, null)); + + Exception exception = assertThrows(NullPointerException.class, () -> { + student.getAddress().getCity().toLowerCase(); + }); + + assertThat(exception.getMessage()).isEqualTo( + "Cannot invoke \"String.toLowerCase()\" because the return value of \"com.baeldung.java8to17.Address.getCity()\" is null"); + } + + @Test + void givenGenericObject_whenUsingPatternMatching_thenReturnsTargetType() { + String city = null; + Object obj = new Address("35, West Street", "Chennai", "6000041"); + + if (obj instanceof Address address) { + city = address.getCity(); + } + + assertThat(city).isEqualTo("Chennai"); + } + + @Test + void givenGenericObject_whenUsingSwitchExpression_thenPatternMatchesRightObject() { + Object shape = new Rectangle(10, 20); + + double circumference = switch (shape) { + case Rectangle r -> 2 * r.length() + 2 * r.width(); + case Circle c -> 2 * c.radius() * Math.PI; + default -> throw new IllegalArgumentException("Unknown shape"); + }; + + assertThat(circumference).isEqualTo(60); + } + +} diff --git a/core-java-modules/core-java-8-2/README.md b/core-java-modules/core-java-8-2/README.md index c0bc63f21f..cad4a4f1fa 100644 --- a/core-java-modules/core-java-8-2/README.md +++ b/core-java-modules/core-java-8-2/README.md @@ -10,4 +10,5 @@ This module contains articles about Java 8 core features - [Interface With Default Methods vs Abstract Class](https://www.baeldung.com/java-interface-default-method-vs-abstract-class) - [Convert Between Byte Array and UUID in Java](https://www.baeldung.com/java-byte-array-to-uuid) - [Create a Simple “Rock-Paper-Scissors” Game in Java](https://www.baeldung.com/java-rock-paper-scissors) +- [VarArgs vs Array Input Parameters in Java](https://www.baeldung.com/varargs-vs-array) - [[<-- Prev]](/core-java-modules/core-java-8) diff --git a/core-java-modules/core-java-annotations/src/main/java/com/baeldung/annotations/ClassWithSuppressWarningsNames.java b/core-java-modules/core-java-annotations/src/main/java/com/baeldung/annotations/ClassWithSuppressWarningsNames.java index aad7cf49eb..d0a325a155 100644 --- a/core-java-modules/core-java-annotations/src/main/java/com/baeldung/annotations/ClassWithSuppressWarningsNames.java +++ b/core-java-modules/core-java-annotations/src/main/java/com/baeldung/annotations/ClassWithSuppressWarningsNames.java @@ -17,7 +17,7 @@ public class ClassWithSuppressWarningsNames implements Serializable { list.add(Integer.valueOf(value)); } - @SuppressWarnings("deprecated") + @SuppressWarnings("deprecation") void suppressDeprecatedWarning() { ClassWithSuppressWarningsNames cls = new ClassWithSuppressWarningsNames(); cls.deprecatedMethod(); // no warning here diff --git a/core-java-modules/core-java-collections-5/README.md b/core-java-modules/core-java-collections-5/README.md new file mode 100644 index 0000000000..0d9b12b842 --- /dev/null +++ b/core-java-modules/core-java-collections-5/README.md @@ -0,0 +1,7 @@ +========= + +## Core Java Collections Cookbooks and Examples + +### Relevant Articles: +- [Introduction to Roaring Bitmap](https://www.baeldung.com/java-roaring-bitmap-intro) +- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4) diff --git a/core-java-modules/core-java-collections-5/pom.xml b/core-java-modules/core-java-collections-5/pom.xml new file mode 100644 index 0000000000..67c9f7120c --- /dev/null +++ b/core-java-modules/core-java-collections-5/pom.xml @@ -0,0 +1,58 @@ + + + 4.0.0 + core-java-collections-5 + 0.0.1-SNAPSHOT + core-java-collections-5 + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + + + org.junit.platform + junit-platform-runner + ${junit-platform.version} + test + + + org.junit.jupiter + junit-jupiter + ${junit.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit.version} + test + + + org.roaringbitmap + RoaringBitmap + ${roaringbitmap.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + + + 5.9.2 + 0.9.38 + 1.36 + + diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/roaringbitmap/BitSetsBenchmark.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/roaringbitmap/BitSetsBenchmark.java new file mode 100644 index 0000000000..4968afb752 --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/roaringbitmap/BitSetsBenchmark.java @@ -0,0 +1,82 @@ +package com.baeldung.roaringbitmap; + +import java.util.BitSet; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.roaringbitmap.RoaringBitmap; + +@State(Scope.Thread) +public class BitSetsBenchmark { + private RoaringBitmap rb1; + private BitSet bs1; + private RoaringBitmap rb2; + private BitSet bs2; + private final static int SIZE = 10_000_000; + + @Setup + public void setup() { + rb1 = new RoaringBitmap(); + bs1 = new BitSet(SIZE); + rb2 = new RoaringBitmap(); + bs2 = new BitSet(SIZE); + for (int i = 0; i < SIZE / 2; i++) { + rb1.add(i); + bs1.set(i); + } + for (int i = SIZE / 2; i < SIZE; i++) { + rb2.add(i); + bs2.set(i); + } + } + + @Benchmark + public RoaringBitmap roaringBitmapUnion() { + return RoaringBitmap.or(rb1, rb2); + } + + @Benchmark + public BitSet bitSetUnion() { + BitSet result = (BitSet) bs1.clone(); + result.or(bs2); + return result; + } + + @Benchmark + public RoaringBitmap roaringBitmapIntersection() { + return RoaringBitmap.and(rb1, rb2); + } + + @Benchmark + public BitSet bitSetIntersection() { + BitSet result = (BitSet) bs1.clone(); + result.and(bs2); + return result; + } + + @Benchmark + public RoaringBitmap roaringBitmapDifference() { + return RoaringBitmap.andNot(rb1, rb2); + } + + @Benchmark + public BitSet bitSetDifference() { + BitSet result = (BitSet) bs1.clone(); + result.andNot(bs2); + return result; + } + + @Benchmark + public RoaringBitmap roaringBitmapXOR() { + return RoaringBitmap.xor(rb1, rb2); + } + + @Benchmark + public BitSet bitSetXOR() { + BitSet result = (BitSet) bs1.clone(); + result.xor(bs2); + return result; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/roaringbitmap/BitSetsBenchmarkRunner.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/roaringbitmap/BitSetsBenchmarkRunner.java new file mode 100644 index 0000000000..49d556df7e --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/roaringbitmap/BitSetsBenchmarkRunner.java @@ -0,0 +1,9 @@ +package com.baeldung.roaringbitmap; + +import java.io.IOException; + +public class BitSetsBenchmarkRunner { + public static void main(String... args) throws IOException { + org.openjdk.jmh.Main.main(args); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/roaringbitmap/RoaringBitmapBenchmarkUnitTest.java b/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/roaringbitmap/RoaringBitmapBenchmarkUnitTest.java new file mode 100644 index 0000000000..07170512d9 --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/roaringbitmap/RoaringBitmapBenchmarkUnitTest.java @@ -0,0 +1,45 @@ +package com.baeldung.roaringbitmap; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; +import org.roaringbitmap.RoaringBitmap; + +class RoaringBitmapBenchmarkUnitTest { + @Test + public void givenTwoRoaringBitmap_whenUsingOr_thenWillGetSetsUnion() { + RoaringBitmap expected = RoaringBitmap.bitmapOf(1, 2, 3, 4, 5, 6, 7, 8); + RoaringBitmap A = RoaringBitmap.bitmapOf(1, 2, 3, 4, 5); + RoaringBitmap B = RoaringBitmap.bitmapOf(4, 5, 6, 7, 8); + RoaringBitmap union = RoaringBitmap.or(A, B); + assertEquals(expected, union); + } + + @Test + public void givenTwoRoaringBitmap_whenUsingAnd_thenWillGetSetsIntersection() { + RoaringBitmap expected = RoaringBitmap.bitmapOf(4, 5); + RoaringBitmap A = RoaringBitmap.bitmapOfRange(1, 6); + RoaringBitmap B = RoaringBitmap.bitmapOf(4, 5, 6, 7, 8); + RoaringBitmap intersection = RoaringBitmap.and(A, B); + assertEquals(expected, intersection); + } + + @Test + public void givenTwoRoaringBitmap_whenUsingAndNot_thenWillGetSetsDifference() { + RoaringBitmap expected = RoaringBitmap.bitmapOf(1, 2, 3); + RoaringBitmap A = new RoaringBitmap(); + A.add(1L, 6L); + RoaringBitmap B = RoaringBitmap.bitmapOf(4, 5, 6, 7, 8); + RoaringBitmap difference = RoaringBitmap.andNot(A, B); + assertEquals(expected, difference); + } + + @Test + public void givenTwoRoaringBitmap_whenUsingXOR_thenWillGetSetsSymmetricDifference() { + RoaringBitmap expected = RoaringBitmap.bitmapOf(1, 2, 3, 6, 7, 8); + RoaringBitmap A = RoaringBitmap.bitmapOfRange(1, 6); + RoaringBitmap B = RoaringBitmap.bitmapOfRange(4, 9); + RoaringBitmap xor = RoaringBitmap.xor(A, B); + assertEquals(expected, xor); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-conversions-2/README.md b/core-java-modules/core-java-collections-conversions-2/README.md index 742b52aad5..904e876032 100644 --- a/core-java-modules/core-java-collections-conversions-2/README.md +++ b/core-java-modules/core-java-collections-conversions-2/README.md @@ -10,4 +10,5 @@ This module contains articles about conversions among Collection types and array - [Arrays.asList vs new ArrayList(Arrays.asList())](https://www.baeldung.com/java-arrays-aslist-vs-new-arraylist) - [Iterate Over a Set in Java](https://www.baeldung.com/java-iterate-set) - [Convert a List of Integers to a List of Strings](https://www.baeldung.com/java-convert-list-integers-to-list-strings) +- [Combining Two Lists Into a Map in Java](https://www.baeldung.com/java-combine-two-lists-into-map) - More articles: [[<-- prev]](../core-java-collections-conversions) diff --git a/core-java-modules/core-java-collections-list-5/README.md b/core-java-modules/core-java-collections-list-5/README.md index 78959e7d5d..d8cd989600 100644 --- a/core-java-modules/core-java-collections-list-5/README.md +++ b/core-java-modules/core-java-collections-list-5/README.md @@ -4,3 +4,4 @@ This module contains articles about the Java List collection ### Relevant Articles: - [Java List Interface](https://www.baeldung.com/java-list-interface) +- [Finding All Duplicates in a List in Java](https://www.baeldung.com/java-list-find-duplicates) diff --git a/core-java-modules/core-java-collections-list-5/src/main/java/com/baeldung/listduplicate/ListDuplicate.java b/core-java-modules/core-java-collections-list-5/src/main/java/com/baeldung/listduplicate/ListDuplicate.java new file mode 100644 index 0000000000..5e3e845916 --- /dev/null +++ b/core-java-modules/core-java-collections-list-5/src/main/java/com/baeldung/listduplicate/ListDuplicate.java @@ -0,0 +1,69 @@ +package com.baeldung.listduplicate; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +public class ListDuplicate { + public List listDuplicateUsingSet(List list) { + List duplicates = new ArrayList<>(); + Set set = new HashSet<>(); + for (Integer i : list) { + if (set.contains(i)) { + duplicates.add(i); + } else { + set.add(i); + } + } + return duplicates; + } + + public List listDuplicateUsingMap(List list) { + List duplicates = new ArrayList<>(); + Map frequencyMap = new HashMap<>(); + for (Integer number : list) { + frequencyMap.put(number, frequencyMap.getOrDefault(number, 0) + 1); + } + for (int number : frequencyMap.keySet()) { + if (frequencyMap.get(number) != 1) { + duplicates.add(number); + } + } + return duplicates; + } + + public List listDuplicateUsingFilterAndSetAdd(List list) { + Set elements = new HashSet(); + return list.stream() + .filter(n -> !elements.add(n)) + .collect(Collectors.toList()); + } + + public List listDuplicateUsingCollectionsFrequency(List list) { + List duplicates = new ArrayList<>(); + Set set = list.stream() + .filter(i -> Collections.frequency(list, i) > 1) + .collect(Collectors.toSet()); + duplicates.addAll(set); + return duplicates; + } + + public List listDuplicateUsingMapAndCollectorsGroupingBy(List list) { + List duplicates = new ArrayList<>(); + Set set = list.stream() + .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) + .entrySet() + .stream() + .filter(m -> m.getValue() > 1) + .map(Map.Entry::getKey) + .collect(Collectors.toSet()); + duplicates.addAll(set); + return duplicates; + } +} diff --git a/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/listduplicate/ListDuplicateUnitTest.java b/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/listduplicate/ListDuplicateUnitTest.java new file mode 100644 index 0000000000..0d81387aea --- /dev/null +++ b/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/listduplicate/ListDuplicateUnitTest.java @@ -0,0 +1,68 @@ +package com.baeldung.listduplicate; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +public class ListDuplicateUnitTest { + private static ListDuplicate listDuplicate; + + @BeforeClass + public static void setup() { + listDuplicate = new ListDuplicate(); + } + + @Test + public void givenList_whenUsingSet_thenReturnDuplicateElements() { + List list = Arrays.asList(1, 2, 3, 3, 4, 4, 5); + List duplicates = listDuplicate.listDuplicateUsingSet(list); + Assert.assertEquals(duplicates.size(), 2); + Assert.assertEquals(duplicates.contains(3), true); + Assert.assertEquals(duplicates.contains(4), true); + Assert.assertEquals(duplicates.contains(1), false); + } + + @Test + public void givenList_whenUsingFrequencyMap_thenReturnDuplicateElements() { + List list = Arrays.asList(1, 2, 3, 3, 4, 4, 5); + List duplicates = listDuplicate.listDuplicateUsingMap(list); + Assert.assertEquals(duplicates.size(), 2); + Assert.assertEquals(duplicates.contains(3), true); + Assert.assertEquals(duplicates.contains(4), true); + Assert.assertEquals(duplicates.contains(1), false); + } + + @Test + public void givenList_whenUsingFilterAndSetAdd_thenReturnDuplicateElements() { + List list = Arrays.asList(1, 2, 3, 3, 4, 4, 5); + List duplicates = listDuplicate.listDuplicateUsingFilterAndSetAdd(list); + Assert.assertEquals(duplicates.size(), 2); + Assert.assertEquals(duplicates.contains(3), true); + Assert.assertEquals(duplicates.contains(4), true); + Assert.assertEquals(duplicates.contains(1), false); + } + + @Test + public void givenList_whenUsingCollectionsFrequency_thenReturnDuplicateElements() { + List list = Arrays.asList(1, 2, 3, 3, 4, 4, 5); + List duplicates = listDuplicate.listDuplicateUsingCollectionsFrequency(list); + Assert.assertEquals(duplicates.size(), 2); + Assert.assertEquals(duplicates.contains(3), true); + Assert.assertEquals(duplicates.contains(4), true); + Assert.assertEquals(duplicates.contains(1), false); + } + + @Test + public void givenList_whenUsingMapAndCollectorsGroupingBy_thenReturnDuplicateElements() { + List list = Arrays.asList(1, 2, 3, 3, 4, 4, 5); + List duplicates = listDuplicate.listDuplicateUsingCollectionsFrequency(list); + Assert.assertEquals(duplicates.size(), 2); + Assert.assertEquals(duplicates.contains(3), true); + Assert.assertEquals(duplicates.contains(4), true); + Assert.assertEquals(duplicates.contains(1), false); + } + +} diff --git a/core-java-modules/core-java-concurrency-basic-3/README.md b/core-java-modules/core-java-concurrency-basic-3/README.md index 477f37e00a..46480c6b01 100644 --- a/core-java-modules/core-java-concurrency-basic-3/README.md +++ b/core-java-modules/core-java-concurrency-basic-3/README.md @@ -5,4 +5,5 @@ This module contains articles about basic Java concurrency. ### Relevant Articles: - [How to Handle InterruptedException in Java](https://www.baeldung.com/java-interrupted-exception) +- [Thread.sleep() vs Awaitility.await()](https://www.baeldung.com/java-thread-sleep-vs-awaitility-await) - [[<-- Prev]](../core-java-concurrency-basic-2) diff --git a/core-java-modules/core-java-lang-oop-constructors/README.md b/core-java-modules/core-java-lang-oop-constructors/README.md index a552a79721..2f414c6bf5 100644 --- a/core-java-modules/core-java-lang-oop-constructors/README.md +++ b/core-java-modules/core-java-lang-oop-constructors/README.md @@ -12,3 +12,4 @@ This module contains article about constructors in Java - [Java Implicit Super Constructor is Undefined Error](https://www.baeldung.com/java-implicit-super-constructor-is-undefined-error) - [Constructor Specification in Java](https://www.baeldung.com/java-constructor-specification) - [Static vs. Instance Initializer Block in Java](https://www.baeldung.com/java-static-instance-initializer-blocks) +- [Accessing Private Constructor in Java](https://www.baeldung.com/java-private-constructor-access) diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/ClonableRabbit.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/ClonableRabbit.java new file mode 100644 index 0000000000..0d97e010fb --- /dev/null +++ b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/ClonableRabbit.java @@ -0,0 +1,18 @@ +package com.baeldung.objectcreation.objects; + +public class ClonableRabbit implements Cloneable { + + String name = ""; + + public ClonableRabbit(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } +} diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/Rabbit.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/Rabbit.java new file mode 100644 index 0000000000..c8a8159544 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/Rabbit.java @@ -0,0 +1,17 @@ +package com.baeldung.objectcreation.objects; + +public class Rabbit { + + String name = ""; + + public Rabbit() { + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/RabbitType.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/RabbitType.java new file mode 100644 index 0000000000..b7afe5fe2f --- /dev/null +++ b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/RabbitType.java @@ -0,0 +1,7 @@ +package com.baeldung.objectcreation.objects; + +public enum RabbitType { + PET, + TAME, + WILD +} diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/SerializableRabbit.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/SerializableRabbit.java new file mode 100644 index 0000000000..cb5f2d0b71 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/objects/SerializableRabbit.java @@ -0,0 +1,21 @@ +package com.baeldung.objectcreation.objects; + +import java.io.Serializable; + +public class SerializableRabbit implements Serializable { + + private static final long serialVersionUID = 2589844379773087465L; + + String name = ""; + + public SerializableRabbit() { + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/utils/CreateRabbits.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/utils/CreateRabbits.java new file mode 100644 index 0000000000..8b3c84e89c --- /dev/null +++ b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/objectcreation/utils/CreateRabbits.java @@ -0,0 +1,71 @@ +package com.baeldung.objectcreation.utils; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.lang.reflect.InvocationTargetException; +import java.util.function.Supplier; + +import com.baeldung.objectcreation.objects.ClonableRabbit; +import com.baeldung.objectcreation.objects.Rabbit; +import com.baeldung.objectcreation.objects.RabbitType; +import com.baeldung.objectcreation.objects.SerializableRabbit; + +public final class CreateRabbits { + + public static Rabbit createRabbitUsingNewOperator() { + Rabbit rabbit = new Rabbit(); + + return rabbit; + } + + public static Rabbit createRabbitUsingClassForName() throws InstantiationException, IllegalAccessException, ClassNotFoundException { + Rabbit rabbit = (Rabbit) Class.forName("com.baeldung.objectcreation.objects.Rabbit").newInstance(); + + return rabbit; + } + + public static Rabbit createRabbitUsingClassNewInstance() throws InstantiationException, IllegalAccessException { + Rabbit rabbit = Rabbit.class.newInstance(); + + return rabbit; + } + + public static Rabbit createRabbitUsingConstructorNewInstance() throws InstantiationException, IllegalAccessException, IllegalArgumentException, + InvocationTargetException, NoSuchMethodException, SecurityException { + Rabbit rabbit = Rabbit.class.getConstructor().newInstance(); + + return rabbit; + } + + public static ClonableRabbit createRabbitUsingClone(ClonableRabbit originalRabbit) throws CloneNotSupportedException { + ClonableRabbit clonedRabbit = (ClonableRabbit) originalRabbit.clone(); + + return clonedRabbit; + } + + public static SerializableRabbit createRabbitUsingDeserialization(File file) throws IOException, ClassNotFoundException { + try (FileInputStream fis = new FileInputStream(file); + ObjectInputStream ois = new ObjectInputStream(fis);) { + return (SerializableRabbit) ois.readObject(); + } + } + + public static Rabbit createRabbitUsingSupplier() { + Supplier rabbitSupplier = Rabbit::new; + Rabbit rabbit = rabbitSupplier.get(); + + return rabbit; + } + + public static Rabbit[] createRabbitArray() { + Rabbit[] rabbitArray = new Rabbit[10]; + + return rabbitArray; + } + + public static RabbitType createRabbitTypeEnum() { + return RabbitType.PET; //any RabbitType could be returned here, PET is just an example. + } +} diff --git a/core-java-modules/core-java-lang-oop-constructors/src/test/java/com/baeldung/objectcreation/CreateRabbitsUnitTest.java b/core-java-modules/core-java-lang-oop-constructors/src/test/java/com/baeldung/objectcreation/CreateRabbitsUnitTest.java new file mode 100644 index 0000000000..653beba096 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-constructors/src/test/java/com/baeldung/objectcreation/CreateRabbitsUnitTest.java @@ -0,0 +1,100 @@ +package com.baeldung.objectcreation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.lang.reflect.InvocationTargetException; + +import org.junit.Test; + +import com.baeldung.objectcreation.objects.ClonableRabbit; +import com.baeldung.objectcreation.objects.Rabbit; +import com.baeldung.objectcreation.objects.RabbitType; +import com.baeldung.objectcreation.objects.SerializableRabbit; +import com.baeldung.objectcreation.utils.CreateRabbits; + +public class CreateRabbitsUnitTest { + + @Test + public void whenUsingNewOperator_thenRabbitIsReturned() { + assertTrue(CreateRabbits.createRabbitUsingNewOperator() instanceof Rabbit); + } + + @Test + public void whenUsingClassForName_thenRabbitIsReturned() throws InstantiationException, IllegalAccessException, ClassNotFoundException { + assertTrue(CreateRabbits.createRabbitUsingClassForName() instanceof Rabbit); + } + + @Test + public void whenUsingClassNewInstance_thenRabbitIsReturned() throws InstantiationException, IllegalAccessException { + assertTrue(CreateRabbits.createRabbitUsingClassNewInstance() instanceof Rabbit); + } + + @Test + public void whenUsingConstructorNewInstance_thenRabbitIsReturned() throws InstantiationException, IllegalAccessException, IllegalArgumentException, + InvocationTargetException, NoSuchMethodException, SecurityException { + assertTrue(CreateRabbits.createRabbitUsingConstructorNewInstance() instanceof Rabbit); + } + + @Test + public void givenClonableRabbit_whenUsingCloneMethod_thenClonedRabbitIsReturned() throws CloneNotSupportedException { + //given + ClonableRabbit originalRabbit = new ClonableRabbit("Peter"); + + //when + ClonableRabbit clonedRabbit = CreateRabbits.createRabbitUsingClone(originalRabbit); + + //then + assertTrue(clonedRabbit instanceof ClonableRabbit); + assertNotEquals(originalRabbit, clonedRabbit); + assertEquals("Peter", clonedRabbit.getName()); + } + + @Test + public void givenSerializedRabbit_whenDeserializing_thenNewRabbitIsReturned() throws IOException, ClassNotFoundException { + //given + SerializableRabbit originalRabbit = new SerializableRabbit(); + originalRabbit.setName("Peter"); + + File resourcesFolder = new File("src/test/resources"); + resourcesFolder.mkdirs(); //creates the directory in case it doesn't exist + + File file = new File(resourcesFolder, "rabbit.ser"); + + try (FileOutputStream fileOutputStream = new FileOutputStream(file); + ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);) { + objectOutputStream.writeObject(originalRabbit); + } + + //when + SerializableRabbit newRabbit = CreateRabbits.createRabbitUsingDeserialization(file); + + //then + assertTrue(newRabbit instanceof SerializableRabbit); + assertNotEquals(originalRabbit, newRabbit); + assertEquals("Peter", newRabbit.getName()); + + //clean up + file.delete(); + } + + @Test + public void whenUsingSupplier_thenRabbitIsReturned() { + assertTrue(CreateRabbits.createRabbitUsingSupplier() instanceof Rabbit); + } + + @Test + public void whenUsingArrays_thenRabbitArrayIsReturned() { + assertTrue(CreateRabbits.createRabbitArray() instanceof Rabbit[]); + } + + @Test + public void whenUsingEnums_thenRabbitTypeIsReturned() { + assertTrue(CreateRabbits.createRabbitTypeEnum() instanceof RabbitType); + } +} diff --git a/core-java-modules/core-java-networking-4/pom.xml b/core-java-modules/core-java-networking-4/pom.xml index 29531a5767..a3694cfea8 100644 --- a/core-java-modules/core-java-networking-4/pom.xml +++ b/core-java-modules/core-java-networking-4/pom.xml @@ -20,6 +20,12 @@ commons-validator ${apache.commons-validator.version} + + org.jsoup + jsoup + ${jsoup.version} + + @@ -28,6 +34,7 @@ 1.7 + 1.15.4 \ No newline at end of file diff --git a/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/downloadwebpage/DownloadWebpageUnitTest.java b/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/downloadwebpage/DownloadWebpageUnitTest.java new file mode 100644 index 0000000000..23b8928ecb --- /dev/null +++ b/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/downloadwebpage/DownloadWebpageUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.downloadwebpage; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; +import org.junit.jupiter.api.Test; + +class DownloadWebpageUnitTest { + + @Test + public void givenURLConnection_whenRetrieveWebpage_thenWebpageIsNotNullAndContainsHtmlTag() throws IOException { + URL url = new URL("https://example.com"); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + StringBuilder responseBuilder = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + responseBuilder.append(line); + } + + assertNotNull(responseBuilder); + assertTrue(responseBuilder.toString() + .contains("")); + } + + } + + @Test + public void givenJsoup_whenRetrievingWebpage_thenWebpageDocumentIsNotNullAndContainsHtmlTag() throws IOException { + + Document document = Jsoup.connect("https://example.com") + .get(); + String webpage = document.html(); + + assertNotNull(webpage); + assertTrue(webpage.contains("")); + + } + +} diff --git a/core-java-modules/core-java-security-algorithms/src/test/java/com/baeldung/aes/AESUtilUnitTest.java b/core-java-modules/core-java-security-algorithms/src/test/java/com/baeldung/aes/AESUtilUnitTest.java index 531c20ca79..04499a4fed 100644 --- a/core-java-modules/core-java-security-algorithms/src/test/java/com/baeldung/aes/AESUtilUnitTest.java +++ b/core-java-modules/core-java-security-algorithms/src/test/java/com/baeldung/aes/AESUtilUnitTest.java @@ -48,7 +48,7 @@ class AESUtilUnitTest implements WithAssertions { IvParameterSpec ivParameterSpec = AESUtil.generateIv(); File inputFile = Paths.get("src/test/resources/baeldung.txt") .toFile(); - File encryptedFile = new File("classpath:baeldung.encrypted"); + File encryptedFile = new File("baeldung.encrypted"); File decryptedFile = new File("document.decrypted"); // when @@ -57,8 +57,8 @@ class AESUtilUnitTest implements WithAssertions { // then assertThat(inputFile).hasSameTextualContentAs(decryptedFile); - encryptedFile.delete(); - decryptedFile.delete(); + encryptedFile.deleteOnExit(); + decryptedFile.deleteOnExit(); } @Test diff --git a/core-java-modules/core-java-streams-4/README.md b/core-java-modules/core-java-streams-4/README.md index 67b16ac153..c6717ec5fe 100644 --- a/core-java-modules/core-java-streams-4/README.md +++ b/core-java-modules/core-java-streams-4/README.md @@ -9,3 +9,4 @@ - [Stream to Iterable in Java](https://www.baeldung.com/java-stream-to-iterable) - [Understanding the Difference Between Stream.of() and IntStream.range()](https://www.baeldung.com/java-stream-of-and-intstream-range) - [Check if Object Is an Array in Java](https://www.baeldung.com/java-check-if-object-is-an-array) +- [Mapping an Array of Integers to Strings Using Java Streams](https://www.baeldung.com/java-stream-integer-array-to-strings) diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 1033213cd1..a96489ec6f 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -31,6 +31,7 @@ core-java-collections-2 core-java-collections-3 core-java-collections-4 + core-java-collections-5 core-java-collections-conversions core-java-collections-conversions-2 core-java-collections-set-2 diff --git a/couchbase/pom.xml b/couchbase/pom.xml index e87975a53c..095bda3610 100644 --- a/couchbase/pom.xml +++ b/couchbase/pom.xml @@ -64,11 +64,16 @@ ${commons-lang3.version} test + + javax.annotation + javax.annotation-api + 1.3.2 + - 2.5.0 - 4.3.5.RELEASE + 2.7.2 + 5.3.25 \ No newline at end of file diff --git a/custom-pmd/pom.xml b/custom-pmd/pom.xml index 550f96de33..38a5e30404 100644 --- a/custom-pmd/pom.xml +++ b/custom-pmd/pom.xml @@ -44,10 +44,10 @@ - 3.7.0 - 6.0.1 - 1.8 - 1.8 + 3.10.0 + 6.53.0 + 11 + 11 \ No newline at end of file diff --git a/custom-pmd/src/main/java/com/baeldung/pmd/UnitTestNamingConventionRule.java b/custom-pmd/src/main/java/com/baeldung/pmd/UnitTestNamingConventionRule.java index e30164ac4f..a652bd1bfa 100644 --- a/custom-pmd/src/main/java/com/baeldung/pmd/UnitTestNamingConventionRule.java +++ b/custom-pmd/src/main/java/com/baeldung/pmd/UnitTestNamingConventionRule.java @@ -18,8 +18,9 @@ public class UnitTestNamingConventionRule extends AbstractJavaRule { "UnitTest", "jmhTest"); + @Override public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { - String className = node.getImage(); + String className = node.getSimpleName(); Objects.requireNonNull(className); if (className.endsWith("SpringContextTest")) { diff --git a/dependency-exclusion/core-java-exclusions/pom.xml b/dependency-exclusion/core-java-exclusions/pom.xml new file mode 100644 index 0000000000..cf1b36656d --- /dev/null +++ b/dependency-exclusion/core-java-exclusions/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + core-java-exclusions + 0.0.0-SNAPSHOT + core-java-exclusions + jar + + + com.baeldung.dependency-exclusion + dependency-exclusion + 0.0.1-SNAPSHOT + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire-version} + + alphabetical + 1 + + + junit + false + + + + + + + org.apache.maven.surefire + surefire-junit47 + dummy + + + + + + + + + junit + junit + test + + + + diff --git a/dependency-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java b/dependency-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java new file mode 100644 index 0000000000..ed2400f9ac --- /dev/null +++ b/dependency-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java @@ -0,0 +1,12 @@ +package com.sample.project.tests; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class ExcludeDirectDependencyUnitTest { + @Test + public void basicUnitTest() { + assertTrue(true); + } +} diff --git a/dependency-exclusion/dummy-surefire-junit47/pom.xml b/dependency-exclusion/dummy-surefire-junit47/pom.xml new file mode 100644 index 0000000000..5859ddbe72 --- /dev/null +++ b/dependency-exclusion/dummy-surefire-junit47/pom.xml @@ -0,0 +1,9 @@ + + + 4.0.0 + org.apache.maven.surefire + surefire-junit47 + dummy + diff --git a/dependency-exclusion/pom.xml b/dependency-exclusion/pom.xml new file mode 100644 index 0000000000..ac83cc161a --- /dev/null +++ b/dependency-exclusion/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + com.baeldung.dependency-exclusion + dependency-exclusion + dependency-exclusion + pom + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + 2.22.2 + + + + dummy-surefire-junit47 + core-java-exclusions + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + -parameters + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire-version} + + 1 + + + + org.apache.maven.surefire + surefire-junit-platform + ${surefire-version} + + + + + + + + + + + junit + junit + 4.13 + + + + + diff --git a/dependeny-exclusion/core-java-exclusions/pom.xml b/dependeny-exclusion/core-java-exclusions/pom.xml new file mode 100644 index 0000000000..cf1f6d1e1b --- /dev/null +++ b/dependeny-exclusion/core-java-exclusions/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + core-java-exclusions + 0.0.0-SNAPSHOT + core-java-exclusions + jar + + + com.baeldung.dependency-exclusion + dependency-exclusion + 0.0.1-SNAPSHOT + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire-version} + + alphabetical + 1 + + + junit + false + + + + + + + org.apache.maven.surefire + surefire-junit47 + dummy + + + + + + + + + junit + junit + test + + + + diff --git a/dependeny-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java b/dependeny-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java new file mode 100644 index 0000000000..ed2400f9ac --- /dev/null +++ b/dependeny-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java @@ -0,0 +1,12 @@ +package com.sample.project.tests; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class ExcludeDirectDependencyUnitTest { + @Test + public void basicUnitTest() { + assertTrue(true); + } +} diff --git a/dependeny-exclusion/dummy-surefire-junit47/pom.xml b/dependeny-exclusion/dummy-surefire-junit47/pom.xml new file mode 100644 index 0000000000..5859ddbe72 --- /dev/null +++ b/dependeny-exclusion/dummy-surefire-junit47/pom.xml @@ -0,0 +1,9 @@ + + + 4.0.0 + org.apache.maven.surefire + surefire-junit47 + dummy + diff --git a/dependeny-exclusion/pom.xml b/dependeny-exclusion/pom.xml new file mode 100644 index 0000000000..ac83cc161a --- /dev/null +++ b/dependeny-exclusion/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + com.baeldung.dependency-exclusion + dependency-exclusion + dependency-exclusion + pom + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + 2.22.2 + + + + dummy-surefire-junit47 + core-java-exclusions + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + -parameters + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire-version} + + 1 + + + + org.apache.maven.surefire + surefire-junit-platform + ${surefire-version} + + + + + + + + + + + junit + junit + 4.13 + + + + + diff --git a/drools/pom.xml b/drools/pom.xml index daaf1fa8a7..12aaf1318a 100644 --- a/drools/pom.xml +++ b/drools/pom.xml @@ -8,9 +8,8 @@ com.baeldung - parent-spring-4 - 0.0.1-SNAPSHOT - ../parent-spring-4 + parent-modules + 1.0.0-SNAPSHOT @@ -57,10 +56,10 @@ - 4.4.6 - 7.4.1.Final - 3.13 - 7.10.0.Final + 4.4.16 + 8.32.0.Final + 5.2.3 + 8.32.0.Final - \ No newline at end of file + diff --git a/drools/src/main/java/com/baeldung/drools/backward_chaining/BackwardChaining.java b/drools/src/main/java/com/baeldung/drools/backward_chaining/BackwardChaining.java index 6f15ee510b..3baabbeb0f 100644 --- a/drools/src/main/java/com/baeldung/drools/backward_chaining/BackwardChaining.java +++ b/drools/src/main/java/com/baeldung/drools/backward_chaining/BackwardChaining.java @@ -11,7 +11,6 @@ public class BackwardChaining { Result result = new BackwardChaining().backwardChaining(); System.out.println(result.getValue()); result.getFacts() - .stream() .forEach(System.out::println); } diff --git a/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java b/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java index cf5d56f246..bbc1f3170a 100644 --- a/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java +++ b/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java @@ -10,26 +10,25 @@ import org.kie.internal.builder.DecisionTableConfiguration; import org.kie.internal.builder.DecisionTableInputType; import org.kie.internal.builder.KnowledgeBuilderFactory; import org.kie.internal.io.ResourceFactory; -import java.io.IOException; import java.util.Arrays; import java.util.List; public class DroolsBeanFactory { private static final String RULES_PATH = "com/baeldung/drools/rules/"; - private KieServices kieServices=KieServices.Factory.get(); + private KieServices kieServices = KieServices.Factory.get(); - private KieFileSystem getKieFileSystem() throws IOException{ + private KieFileSystem getKieFileSystem() { KieFileSystem kieFileSystem = kieServices.newKieFileSystem(); - List rules=Arrays.asList("BackwardChaining.drl","SuggestApplicant.drl","Product_rules.xls"); - for(String rule:rules){ + List rules = Arrays.asList("BackwardChaining.drl", "SuggestApplicant.drl", "Product_rules.xls"); + for(String rule:rules) { kieFileSystem.write(ResourceFactory.newClassPathResource(rule)); } return kieFileSystem; } - public KieContainer getKieContainer() throws IOException { + public KieContainer getKieContainer() { getKieRepository(); KieBuilder kb = kieServices.newKieBuilder(getKieFileSystem()); @@ -44,14 +43,10 @@ public class DroolsBeanFactory { private void getKieRepository() { final KieRepository kieRepository = kieServices.getRepository(); - kieRepository.addKieModule(new KieModule() { - public ReleaseId getReleaseId() { - return kieRepository.getDefaultReleaseId(); - } - }); + kieRepository.addKieModule(kieRepository::getDefaultReleaseId); } - public KieSession getKieSession(){ + public KieSession getKieSession() { getKieRepository(); KieFileSystem kieFileSystem = kieServices.newKieFileSystem(); @@ -59,7 +54,6 @@ public class DroolsBeanFactory { kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/SuggestApplicant.drl")); kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/Product_rules.xls")); - KieBuilder kb = kieServices.newKieBuilder(kieFileSystem); kb.buildAll(); KieModule kieModule = kb.getKieModule(); @@ -67,7 +61,6 @@ public class DroolsBeanFactory { KieContainer kContainer = kieServices.newKieContainer(kieModule.getReleaseId()); return kContainer.newKieSession(); - } public KieSession getKieSession(Resource dt) { diff --git a/drools/src/main/java/com/baeldung/drools/optaplanner/CourseSchedule.java b/drools/src/main/java/com/baeldung/drools/optaplanner/CourseSchedule.java index 7b2ba117a1..d0ae5318b9 100644 --- a/drools/src/main/java/com/baeldung/drools/optaplanner/CourseSchedule.java +++ b/drools/src/main/java/com/baeldung/drools/optaplanner/CourseSchedule.java @@ -6,7 +6,7 @@ import java.util.List; import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty; import org.optaplanner.core.api.domain.solution.PlanningScore; import org.optaplanner.core.api.domain.solution.PlanningSolution; -import org.optaplanner.core.api.domain.solution.drools.ProblemFactCollectionProperty; +import org.optaplanner.core.api.domain.solution.ProblemFactCollectionProperty; import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider; import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore; import org.slf4j.Logger; diff --git a/drools/src/main/java/com/baeldung/drools/optaplanner/ScoreCalculator.java b/drools/src/main/java/com/baeldung/drools/optaplanner/ScoreCalculator.java index 86501cdccd..c9d2b4df99 100644 --- a/drools/src/main/java/com/baeldung/drools/optaplanner/ScoreCalculator.java +++ b/drools/src/main/java/com/baeldung/drools/optaplanner/ScoreCalculator.java @@ -2,14 +2,13 @@ package com.baeldung.drools.optaplanner; import java.util.HashSet; -import org.optaplanner.core.api.score.Score; import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore; -import org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator; +import org.optaplanner.core.api.score.calculator.EasyScoreCalculator; -public class ScoreCalculator implements EasyScoreCalculator { +public class ScoreCalculator implements EasyScoreCalculator { @Override - public Score calculateScore(CourseSchedule courseSchedule) { + public HardSoftScore calculateScore(CourseSchedule courseSchedule) { int hardScore = 0; int softScore = 0; @@ -27,6 +26,6 @@ public class ScoreCalculator implements EasyScoreCalculator { } } - return HardSoftScore.valueOf(hardScore, softScore); + return HardSoftScore.of(hardScore, softScore); } } diff --git a/drools/src/main/java/com/baeldung/drools/service/ApplicantService.java b/drools/src/main/java/com/baeldung/drools/service/ApplicantService.java index f74298ef05..06f84358b0 100644 --- a/drools/src/main/java/com/baeldung/drools/service/ApplicantService.java +++ b/drools/src/main/java/com/baeldung/drools/service/ApplicantService.java @@ -3,19 +3,20 @@ package com.baeldung.drools.service; import com.baeldung.drools.config.DroolsBeanFactory; import com.baeldung.drools.model.Applicant; import com.baeldung.drools.model.SuggestedRole; -import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; -import java.io.IOException; - public class ApplicantService { - KieSession kieSession=new DroolsBeanFactory().getKieSession(); + KieSession kieSession = new DroolsBeanFactory().getKieSession(); - public SuggestedRole suggestARoleForApplicant(Applicant applicant,SuggestedRole suggestedRole) throws IOException { - kieSession.insert(applicant); - kieSession.setGlobal("suggestedRole",suggestedRole); - kieSession.fireAllRules(); + public SuggestedRole suggestARoleForApplicant(Applicant applicant,SuggestedRole suggestedRole) { + try { + kieSession.insert(applicant); + kieSession.setGlobal("suggestedRole", suggestedRole); + kieSession.fireAllRules(); + } finally { + kieSession.dispose(); + } System.out.println(suggestedRole.getRole()); return suggestedRole; diff --git a/drools/src/main/java/com/baeldung/drools/service/ProductService.java b/drools/src/main/java/com/baeldung/drools/service/ProductService.java index be5e43ed7b..401f5a600f 100644 --- a/drools/src/main/java/com/baeldung/drools/service/ProductService.java +++ b/drools/src/main/java/com/baeldung/drools/service/ProductService.java @@ -2,18 +2,21 @@ package com.baeldung.drools.service; import com.baeldung.drools.config.DroolsBeanFactory; import com.baeldung.drools.model.Product; -import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; public class ProductService { - private KieSession kieSession=new DroolsBeanFactory().getKieSession(); + private KieSession kieSession = new DroolsBeanFactory().getKieSession(); public Product applyLabelToProduct(Product product){ - kieSession.insert(product); - kieSession.fireAllRules(); + try { + kieSession.insert(product); + kieSession.fireAllRules(); + } finally { + kieSession.dispose(); + } System.out.println(product.getLabel()); - return product; + return product; } diff --git a/drools/src/main/resources/courseScheduleSolverConfigDrools.xml b/drools/src/main/resources/courseScheduleSolverConfigDrools.xml index 7cf95fdcd3..74112d9c7d 100644 --- a/drools/src/main/resources/courseScheduleSolverConfigDrools.xml +++ b/drools/src/main/resources/courseScheduleSolverConfigDrools.xml @@ -1,7 +1,9 @@ - - + + com.baeldung.drools.optaplanner.CourseSchedule + com.baeldung.drools.optaplanner.Lecture + courseSchedule.drl diff --git a/drools/src/main/resources/courseScheduleSolverConfiguration.xml b/drools/src/main/resources/courseScheduleSolverConfiguration.xml index dfedb8f2fd..4214b0943a 100644 --- a/drools/src/main/resources/courseScheduleSolverConfiguration.xml +++ b/drools/src/main/resources/courseScheduleSolverConfiguration.xml @@ -1,7 +1,9 @@ - + com.baeldung.drools.optaplanner.CourseSchedule + com.baeldung.drools.optaplanner.Lecture + com.baeldung.drools.optaplanner.ScoreCalculator diff --git a/drools/src/test/java/com/baeldung/drools/optaplanner/OptaPlannerUnitTest.java b/drools/src/test/java/com/baeldung/drools/optaplanner/OptaPlannerUnitTest.java index 1880e30b86..36b24349c7 100644 --- a/drools/src/test/java/com/baeldung/drools/optaplanner/OptaPlannerUnitTest.java +++ b/drools/src/test/java/com/baeldung/drools/optaplanner/OptaPlannerUnitTest.java @@ -21,13 +21,12 @@ public class OptaPlannerUnitTest { unsolvedCourseSchedule.getLectureList().add(new Lecture()); } - unsolvedCourseSchedule.getPeriodList().addAll(Arrays.asList(new Integer[] { 1, 2, 3 })); - unsolvedCourseSchedule.getRoomList().addAll(Arrays.asList(new Integer[] { 1, 2 })); + unsolvedCourseSchedule.getPeriodList().addAll(Arrays.asList(1, 2, 3)); + unsolvedCourseSchedule.getRoomList().addAll(Arrays.asList(1, 2)); } @Test public void test_whenCustomJavaSolver() { - SolverFactory solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfiguration.xml"); Solver solver = solverFactory.buildSolver(); CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule); @@ -38,7 +37,6 @@ public class OptaPlannerUnitTest { @Test public void test_whenDroolsSolver() { - SolverFactory solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfigDrools.xml"); Solver solver = solverFactory.buildSolver(); CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule); diff --git a/feign/README.md b/feign/README.md index 2dea14ca52..8079c46e9e 100644 --- a/feign/README.md +++ b/feign/README.md @@ -7,3 +7,8 @@ This module contains articles about Feign - [Intro to Feign](https://www.baeldung.com/intro-to-feign) - [Retrying Feign Calls](https://www.baeldung.com/feign-retry) - [Setting Request Headers Using Feign](https://www.baeldung.com/java-feign-request-headers) +- [File Upload With Open Feign](https://www.baeldung.com/java-feign-file-upload) +- [Feign Logging Configuration](https://www.baeldung.com/java-feign-logging) +- [Retrieve Original Message From Feign ErrorDecoder](https://www.baeldung.com/feign-retrieve-original-message) +- [RequestLine with Feign Client](https://www.baeldung.com/feign-requestline) +- [Propagating Exceptions With OpenFeign and Spring](https://www.baeldung.com/spring-openfeign-propagate-exception) \ No newline at end of file diff --git a/feign/pom.xml b/feign/pom.xml index 3ac816fc1d..7338cf7508 100644 --- a/feign/pom.xml +++ b/feign/pom.xml @@ -64,6 +64,22 @@ spring-boot-starter-test test + + io.github.openfeign.form + feign-form-spring + ${feign.form.spring.version} + + + org.springframework.cloud + spring-cloud-starter-openfeign + ${spring.cloud.openfeign.version} + + + com.github.tomakehurst + wiremock-jre8 + ${wire.mock.version} + test + @@ -118,6 +134,9 @@ 11.8 1.6.3 + 3.8.0 + 3.1.2 + 2.33.2 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/ExampleApplication.java b/feign/src/main/java/com/baeldung/core/ExampleApplication.java similarity index 90% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/ExampleApplication.java rename to feign/src/main/java/com/baeldung/core/ExampleApplication.java index c7f07f6667..391e808ede 100644 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/ExampleApplication.java +++ b/feign/src/main/java/com/baeldung/core/ExampleApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign; +package com.baeldung.core; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/EmployeeClient.java b/feign/src/main/java/com/baeldung/core/client/EmployeeClient.java similarity index 73% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/EmployeeClient.java rename to feign/src/main/java/com/baeldung/core/client/EmployeeClient.java index 569401bdcf..0ff8637a94 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/EmployeeClient.java +++ b/feign/src/main/java/com/baeldung/core/client/EmployeeClient.java @@ -1,6 +1,7 @@ -package com.baeldung.cloud.openfeign.client; +package com.baeldung.core.client; + +import com.baeldung.core.model.Employee; -import com.baeldung.cloud.openfeign.model.Employee; import feign.Headers; import feign.Param; import feign.RequestLine; diff --git a/feign/src/main/java/com/baeldung/core/client/FormClient.java b/feign/src/main/java/com/baeldung/core/client/FormClient.java new file mode 100644 index 0000000000..074402aef3 --- /dev/null +++ b/feign/src/main/java/com/baeldung/core/client/FormClient.java @@ -0,0 +1,37 @@ +package com.baeldung.core.client; + +import java.util.Map; + +import org.springframework.beans.factory.ObjectFactory; +import org.springframework.boot.autoconfigure.http.HttpMessageConverters; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.cloud.openfeign.support.SpringEncoder; +import org.springframework.context.annotation.Bean; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; + +import com.baeldung.core.defaulterrorhandling.model.FormData; + +import feign.codec.Encoder; +import feign.form.spring.SpringFormEncoder; + +@FeignClient(name = "form-client", url = "http://localhost:8085/api", configuration = FormFeignEncoderConfig.class) +public interface FormClient { + + @PostMapping(value = "/form", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) + void postFormData(@RequestBody FormData data); + + @PostMapping(value = "/form/map", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) + void postFormMapData(Map data); + +} + +class FormFeignEncoderConfig { + + @Bean + public Encoder encoder(ObjectFactory converters) { + return new SpringFormEncoder(new SpringEncoder(converters)); + } + +} \ No newline at end of file diff --git a/feign/src/main/java/com/baeldung/core/client/UserClient.java b/feign/src/main/java/com/baeldung/core/client/UserClient.java new file mode 100644 index 0000000000..a16f924ad5 --- /dev/null +++ b/feign/src/main/java/com/baeldung/core/client/UserClient.java @@ -0,0 +1,13 @@ +package com.baeldung.core.client; + +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; + +import com.baeldung.core.config.FeignConfig; + +@FeignClient(name = "user-client", url="https://jsonplaceholder.typicode.com", configuration = FeignConfig.class) +public interface UserClient { + + @GetMapping(value = "/users") + String getUsers(); +} \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/config/FeignConfig.java b/feign/src/main/java/com/baeldung/core/config/FeignConfig.java similarity index 79% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/config/FeignConfig.java rename to feign/src/main/java/com/baeldung/core/config/FeignConfig.java index d51e97b9e4..43da2fce0e 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/config/FeignConfig.java +++ b/feign/src/main/java/com/baeldung/core/config/FeignConfig.java @@ -1,7 +1,8 @@ -package com.baeldung.cloud.openfeign.config; +package com.baeldung.core.config; + +import org.springframework.context.annotation.Bean; import feign.Logger; -import org.springframework.context.annotation.Bean; public class FeignConfig { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/controller/EmployeeController.java b/feign/src/main/java/com/baeldung/core/controller/EmployeeController.java similarity index 81% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/controller/EmployeeController.java rename to feign/src/main/java/com/baeldung/core/controller/EmployeeController.java index 65897ad48e..7f7d39240e 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/controller/EmployeeController.java +++ b/feign/src/main/java/com/baeldung/core/controller/EmployeeController.java @@ -1,13 +1,15 @@ -package com.baeldung.cloud.openfeign.controller; +package com.baeldung.core.controller; -import com.baeldung.cloud.openfeign.client.EmployeeClient; -import com.baeldung.cloud.openfeign.model.Employee; -import feign.Feign; -import feign.form.spring.SpringFormEncoder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import com.baeldung.core.client.EmployeeClient; +import com.baeldung.core.model.Employee; + +import feign.Feign; +import feign.form.spring.SpringFormEncoder; + @RestController public class EmployeeController { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClient.java b/feign/src/main/java/com/baeldung/core/customizederrorhandling/client/ProductClient.java similarity index 70% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClient.java rename to feign/src/main/java/com/baeldung/core/customizederrorhandling/client/ProductClient.java index 8a6c5d5846..113051722b 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClient.java +++ b/feign/src/main/java/com/baeldung/core/customizederrorhandling/client/ProductClient.java @@ -1,13 +1,13 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.client; - -import com.baeldung.cloud.openfeign.customizederrorhandling.config.FeignConfig; -import com.baeldung.cloud.openfeign.defaulterrorhandling.model.Product; +package com.baeldung.core.customizederrorhandling.client; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; +import com.baeldung.core.customizederrorhandling.config.FeignConfig; +import com.baeldung.core.defaulterrorhandling.model.Product; + @FeignClient(name = "product-client-2", url = "http://localhost:8081/product/", configuration = FeignConfig.class) public interface ProductClient { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/config/CustomErrorDecoder.java b/feign/src/main/java/com/baeldung/core/customizederrorhandling/config/CustomErrorDecoder.java similarity index 65% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/config/CustomErrorDecoder.java rename to feign/src/main/java/com/baeldung/core/customizederrorhandling/config/CustomErrorDecoder.java index 3750e6288d..5466b61b3a 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/config/CustomErrorDecoder.java +++ b/feign/src/main/java/com/baeldung/core/customizederrorhandling/config/CustomErrorDecoder.java @@ -1,8 +1,9 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.config; +package com.baeldung.core.customizederrorhandling.config; + +import com.baeldung.core.customizederrorhandling.exception.ProductNotFoundException; +import com.baeldung.core.customizederrorhandling.exception.ProductServiceNotAvailableException; +import com.baeldung.core.exception.BadRequestException; -import com.baeldung.cloud.openfeign.exception.BadRequestException; -import com.baeldung.cloud.openfeign.customizederrorhandling.exception.ProductNotFoundException; -import com.baeldung.cloud.openfeign.customizederrorhandling.exception.ProductServiceNotAvailableException; import feign.Response; import feign.codec.ErrorDecoder; diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/config/FeignConfig.java b/feign/src/main/java/com/baeldung/core/customizederrorhandling/config/FeignConfig.java similarity index 81% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/config/FeignConfig.java rename to feign/src/main/java/com/baeldung/core/customizederrorhandling/config/FeignConfig.java index 5cddd521f1..980b8b5b38 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/config/FeignConfig.java +++ b/feign/src/main/java/com/baeldung/core/customizederrorhandling/config/FeignConfig.java @@ -1,8 +1,9 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.config; +package com.baeldung.core.customizederrorhandling.config; + +import org.springframework.context.annotation.Bean; import feign.Logger; import feign.codec.ErrorDecoder; -import org.springframework.context.annotation.Bean; public class FeignConfig { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductController.java b/feign/src/main/java/com/baeldung/core/customizederrorhandling/controller/ProductController.java similarity index 52% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductController.java rename to feign/src/main/java/com/baeldung/core/customizederrorhandling/controller/ProductController.java index 9b7a5aea1d..6d6f784e66 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductController.java +++ b/feign/src/main/java/com/baeldung/core/customizederrorhandling/controller/ProductController.java @@ -1,12 +1,13 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.controller; +package com.baeldung.core.customizederrorhandling.controller; -import com.baeldung.cloud.openfeign.customizederrorhandling.client.ProductClient; - - -import com.baeldung.cloud.openfeign.defaulterrorhandling.model.Product; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import com.baeldung.core.customizederrorhandling.client.ProductClient; +import com.baeldung.core.defaulterrorhandling.model.Product; @RestController("product_controller2") @RequestMapping(value = "myapp2") diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ErrorResponse.java b/feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ErrorResponse.java similarity index 94% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ErrorResponse.java rename to feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ErrorResponse.java index c72e3db68b..6e739e5e40 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ErrorResponse.java +++ b/feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ErrorResponse.java @@ -1,10 +1,11 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.exception; +package com.baeldung.core.customizederrorhandling.exception; + +import java.util.Date; + +import org.springframework.http.HttpStatus; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; -import org.springframework.http.HttpStatus; - -import java.util.Date; public class ErrorResponse { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ProductExceptionHandler.java b/feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ProductExceptionHandler.java similarity index 92% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ProductExceptionHandler.java rename to feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ProductExceptionHandler.java index 2ed709bc34..c83d917570 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ProductExceptionHandler.java +++ b/feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ProductExceptionHandler.java @@ -1,6 +1,5 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.exception; +package com.baeldung.core.customizederrorhandling.exception; -import com.baeldung.cloud.openfeign.exception.BadRequestException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ProductNotFoundException.java b/feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ProductNotFoundException.java similarity index 68% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ProductNotFoundException.java rename to feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ProductNotFoundException.java index 337cb89f7b..fa993ce700 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ProductNotFoundException.java +++ b/feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ProductNotFoundException.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.exception; +package com.baeldung.core.customizederrorhandling.exception; public class ProductNotFoundException extends RuntimeException { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ProductServiceNotAvailableException.java b/feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ProductServiceNotAvailableException.java similarity index 70% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ProductServiceNotAvailableException.java rename to feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ProductServiceNotAvailableException.java index ce30f8c310..887d2cd91d 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/customizederrorhandling/exception/ProductServiceNotAvailableException.java +++ b/feign/src/main/java/com/baeldung/core/customizederrorhandling/exception/ProductServiceNotAvailableException.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.exception; +package com.baeldung.core.customizederrorhandling.exception; public class ProductServiceNotAvailableException extends RuntimeException { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/client/ProductClient.java b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/client/ProductClient.java similarity index 70% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/client/ProductClient.java rename to feign/src/main/java/com/baeldung/core/defaulterrorhandling/client/ProductClient.java index 2cef3d4238..4eb435331d 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/client/ProductClient.java +++ b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/client/ProductClient.java @@ -1,13 +1,13 @@ -package com.baeldung.cloud.openfeign.defaulterrorhandling.client; - -import com.baeldung.cloud.openfeign.defaulterrorhandling.config.FeignConfig; -import com.baeldung.cloud.openfeign.defaulterrorhandling.model.Product; +package com.baeldung.core.defaulterrorhandling.client; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; +import com.baeldung.core.defaulterrorhandling.config.FeignConfig; +import com.baeldung.core.defaulterrorhandling.model.Product; + @FeignClient(name = "product-client", url = "http://localhost:8084/product/", configuration = FeignConfig.class) public interface ProductClient { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/config/FeignConfig.java b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/config/FeignConfig.java similarity index 74% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/config/FeignConfig.java rename to feign/src/main/java/com/baeldung/core/defaulterrorhandling/config/FeignConfig.java index f2329ebe0b..cef8cbb6d9 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/config/FeignConfig.java +++ b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/config/FeignConfig.java @@ -1,7 +1,8 @@ -package com.baeldung.cloud.openfeign.defaulterrorhandling.config; +package com.baeldung.core.defaulterrorhandling.config; + +import org.springframework.context.annotation.Bean; import feign.Logger; -import org.springframework.context.annotation.Bean; public class FeignConfig { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/ProductController.java b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/controller/ProductController.java similarity index 52% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/ProductController.java rename to feign/src/main/java/com/baeldung/core/defaulterrorhandling/controller/ProductController.java index df352f8d52..80f571f29a 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/ProductController.java +++ b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/controller/ProductController.java @@ -1,10 +1,13 @@ -package com.baeldung.cloud.openfeign.defaulterrorhandling.controller; +package com.baeldung.core.defaulterrorhandling.controller; -import com.baeldung.cloud.openfeign.defaulterrorhandling.client.ProductClient; - -import com.baeldung.cloud.openfeign.defaulterrorhandling.model.Product; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.core.defaulterrorhandling.client.ProductClient; +import com.baeldung.core.defaulterrorhandling.model.Product; @RestController("product_controller1") @RequestMapping(value ="myapp1") diff --git a/feign/src/main/java/com/baeldung/core/defaulterrorhandling/model/FormData.java b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/model/FormData.java new file mode 100644 index 0000000000..6210451f2d --- /dev/null +++ b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/model/FormData.java @@ -0,0 +1,12 @@ +package com.baeldung.core.defaulterrorhandling.model; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class FormData { + + int id; + String name; +} diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/model/Product.java b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/model/Product.java similarity index 82% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/model/Product.java rename to feign/src/main/java/com/baeldung/core/defaulterrorhandling/model/Product.java index 25a1662c99..35d860332e 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/defaulterrorhandling/model/Product.java +++ b/feign/src/main/java/com/baeldung/core/defaulterrorhandling/model/Product.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.defaulterrorhandling.model; +package com.baeldung.core.defaulterrorhandling.model; public class Product { diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/exception/BadRequestException.java b/feign/src/main/java/com/baeldung/core/exception/BadRequestException.java similarity index 75% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/exception/BadRequestException.java rename to feign/src/main/java/com/baeldung/core/exception/BadRequestException.java index 7c2daf43fe..4553bb5576 100644 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/exception/BadRequestException.java +++ b/feign/src/main/java/com/baeldung/core/exception/BadRequestException.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.exception; +package com.baeldung.core.exception; public class BadRequestException extends Exception { @@ -15,7 +15,7 @@ public class BadRequestException extends Exception { @Override public String toString() { - return "BadRequestException: " + getMessage(); + return "BadRequestException: "+getMessage(); } } diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/exception/NotFoundException.java b/feign/src/main/java/com/baeldung/core/exception/NotFoundException.java similarity index 86% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/exception/NotFoundException.java rename to feign/src/main/java/com/baeldung/core/exception/NotFoundException.java index 19f6204b86..07f4e0862f 100644 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/exception/NotFoundException.java +++ b/feign/src/main/java/com/baeldung/core/exception/NotFoundException.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.exception; +package com.baeldung.core.exception; public class NotFoundException extends Exception { diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/ExceptionMessage.java b/feign/src/main/java/com/baeldung/core/fileupload/config/ExceptionMessage.java similarity index 95% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/ExceptionMessage.java rename to feign/src/main/java/com/baeldung/core/fileupload/config/ExceptionMessage.java index 45a555b2ea..8301705ca6 100644 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/ExceptionMessage.java +++ b/feign/src/main/java/com/baeldung/core/fileupload/config/ExceptionMessage.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.fileupload.config; +package com.baeldung.core.fileupload.config; public class ExceptionMessage { private String timestamp; diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/FeignSupportConfig.java b/feign/src/main/java/com/baeldung/core/fileupload/config/FeignSupportConfig.java similarity index 57% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/FeignSupportConfig.java rename to feign/src/main/java/com/baeldung/core/fileupload/config/FeignSupportConfig.java index 802077a3d7..c8c9eb1acc 100644 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/FeignSupportConfig.java +++ b/feign/src/main/java/com/baeldung/core/fileupload/config/FeignSupportConfig.java @@ -1,6 +1,5 @@ -package com.baeldung.cloud.openfeign.fileupload.config; +package com.baeldung.core.fileupload.config; -import org.springframework.beans.factory.ObjectFactory; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.cloud.openfeign.support.SpringEncoder; import org.springframework.context.annotation.Bean; @@ -13,12 +12,7 @@ import feign.form.spring.SpringFormEncoder; public class FeignSupportConfig { @Bean public Encoder multipartFormEncoder() { - return new SpringFormEncoder(new SpringEncoder(new ObjectFactory() { - @Override - public HttpMessageConverters getObject() { - return new HttpMessageConverters(new RestTemplate().getMessageConverters()); - } - })); + return new SpringFormEncoder(new SpringEncoder(() -> new HttpMessageConverters(new RestTemplate().getMessageConverters()))); } @Bean diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/RetreiveMessageErrorDecoder.java b/feign/src/main/java/com/baeldung/core/fileupload/config/RetreiveMessageErrorDecoder.java similarity index 82% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/RetreiveMessageErrorDecoder.java rename to feign/src/main/java/com/baeldung/core/fileupload/config/RetreiveMessageErrorDecoder.java index 5ebd7b6887..fc2c8da0ed 100644 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/RetreiveMessageErrorDecoder.java +++ b/feign/src/main/java/com/baeldung/core/fileupload/config/RetreiveMessageErrorDecoder.java @@ -1,10 +1,10 @@ -package com.baeldung.cloud.openfeign.fileupload.config; +package com.baeldung.core.fileupload.config; import java.io.IOException; import java.io.InputStream; -import com.baeldung.cloud.openfeign.exception.BadRequestException; -import com.baeldung.cloud.openfeign.exception.NotFoundException; +import com.baeldung.core.exception.BadRequestException; +import com.baeldung.core.exception.NotFoundException; import com.fasterxml.jackson.databind.ObjectMapper; import feign.Response; @@ -12,9 +12,10 @@ import feign.codec.ErrorDecoder; public class RetreiveMessageErrorDecoder implements ErrorDecoder { private final ErrorDecoder errorDecoder = new Default(); + @Override public Exception decode(String methodKey, Response response) { - ExceptionMessage message = null; + ExceptionMessage message; try (InputStream bodyIs = response.body() .asInputStream()) { ObjectMapper mapper = new ObjectMapper(); diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/controller/FileController.java b/feign/src/main/java/com/baeldung/core/fileupload/controller/FileController.java similarity index 88% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/controller/FileController.java rename to feign/src/main/java/com/baeldung/core/fileupload/controller/FileController.java index 1ddbfcea81..7ba4746979 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/controller/FileController.java +++ b/feign/src/main/java/com/baeldung/core/fileupload/controller/FileController.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.fileupload.controller; +package com.baeldung.core.fileupload.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; @@ -6,7 +6,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; -import com.baeldung.cloud.openfeign.fileupload.service.UploadService; +import com.baeldung.core.fileupload.service.UploadService; @RestController public class FileController { diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadClient.java b/feign/src/main/java/com/baeldung/core/fileupload/service/UploadClient.java similarity index 85% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadClient.java rename to feign/src/main/java/com/baeldung/core/fileupload/service/UploadClient.java index 8f3ef7e421..37b059d642 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadClient.java +++ b/feign/src/main/java/com/baeldung/core/fileupload/service/UploadClient.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.fileupload.service; +package com.baeldung.core.fileupload.service; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.http.MediaType; @@ -6,7 +6,7 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; -import com.baeldung.cloud.openfeign.fileupload.config.FeignSupportConfig; +import com.baeldung.core.fileupload.config.FeignSupportConfig; @FeignClient(name = "file", url = "http://localhost:8081", configuration = FeignSupportConfig.class) public interface UploadClient { diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadResource.java b/feign/src/main/java/com/baeldung/core/fileupload/service/UploadResource.java similarity index 75% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadResource.java rename to feign/src/main/java/com/baeldung/core/fileupload/service/UploadResource.java index 2d5090897d..9d3d173cd4 100644 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadResource.java +++ b/feign/src/main/java/com/baeldung/core/fileupload/service/UploadResource.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.fileupload.service; +package com.baeldung.core.fileupload.service; import org.springframework.web.multipart.MultipartFile; @@ -9,7 +9,7 @@ import feign.Response; public interface UploadResource { - @RequestLine("POST /upload-error") + @RequestLine("POST /upload-file") @Headers("Content-Type: multipart/form-data") Response uploadFile(@Param("file") MultipartFile file); diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadService.java b/feign/src/main/java/com/baeldung/core/fileupload/service/UploadService.java similarity index 62% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadService.java rename to feign/src/main/java/com/baeldung/core/fileupload/service/UploadService.java index 244a5a2168..5176ddf0fa 100644 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadService.java +++ b/feign/src/main/java/com/baeldung/core/fileupload/service/UploadService.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.fileupload.service; +package com.baeldung.core.fileupload.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -13,22 +13,20 @@ public class UploadService { private static final String HTTP_FILE_UPLOAD_URL = "http://localhost:8081"; @Autowired - private FileUploadClientWithFallbackFactory fileUploadClient; - @Autowired - private FileUploadClientWithFallBack fileUploadClientWithFallback; - + private UploadClient client; + public boolean uploadFileWithManualClient(MultipartFile file) { UploadResource fileUploadResource = Feign.builder().encoder(new SpringFormEncoder()) .target(UploadResource.class, HTTP_FILE_UPLOAD_URL); Response response = fileUploadResource.uploadFile(file); return response.status() == 200; } - - public String uploadFileWithFallbackFactory(MultipartFile file) { - return fileUploadClient.fileUpload(file); + + public String uploadFile(MultipartFile file) { + return client.fileUpload(file); } - - public String uploadFileWithFallback(MultipartFile file) { - return fileUploadClientWithFallback.fileUpload(file); + + public String uploadFileError(MultipartFile file) { + return client.fileUpload(file); } } \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/model/Employee.java b/feign/src/main/java/com/baeldung/core/model/Employee.java similarity index 81% rename from spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/model/Employee.java rename to feign/src/main/java/com/baeldung/core/model/Employee.java index 7b8ed1232b..7b0c9e1933 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/model/Employee.java +++ b/feign/src/main/java/com/baeldung/core/model/Employee.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign.model; +package com.baeldung.core.model; public class Employee { diff --git a/feign/src/main/resources/application.properties b/feign/src/main/resources/application.properties index a57c6e36a3..e48d5fd65a 100644 --- a/feign/src/main/resources/application.properties +++ b/feign/src/main/resources/application.properties @@ -5,3 +5,5 @@ ws.port.type.name=UsersPort ws.target.namespace=http://www.baeldung.com/springbootsoap/feignclient ws.location.uri=http://localhost:${server.port}/ws/users/ debug=false + +logging.level.com.baeldung.core=DEBUG \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/resources/fileupload.txt b/feign/src/main/resources/fileupload.txt similarity index 100% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/resources/fileupload.txt rename to feign/src/main/resources/fileupload.txt diff --git a/feign/src/main/resources/logback.xml b/feign/src/main/resources/logback.xml deleted file mode 100644 index e5e962c8e0..0000000000 --- a/feign/src/main/resources/logback.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - \ No newline at end of file diff --git a/feign/src/main/resources/logback_spring.xml b/feign/src/main/resources/logback_spring.xml new file mode 100644 index 0000000000..2a307a5b27 --- /dev/null +++ b/feign/src/main/resources/logback_spring.xml @@ -0,0 +1,45 @@ + + + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + ${LOGS}/spring-boot-logger.log + + %d %p %C{1.} [%t] %m%n + + + + + ${LOGS}/archived/spring-boot-logger-%d{yyyy-MM-dd}.%i.log + + + 10MB + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/test/java/com/baeldung/cloud/openfeign/OpenFeignFileUploadLiveTest.java b/feign/src/test/java/com/baeldung/core/OpenFeignFileUploadLiveTest.java similarity index 55% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/test/java/com/baeldung/cloud/openfeign/OpenFeignFileUploadLiveTest.java rename to feign/src/test/java/com/baeldung/core/OpenFeignFileUploadLiveTest.java index 6396be2453..f9dc8b13ed 100644 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/test/java/com/baeldung/cloud/openfeign/OpenFeignFileUploadLiveTest.java +++ b/feign/src/test/java/com/baeldung/core/OpenFeignFileUploadLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.cloud.openfeign; +package com.baeldung.core; import java.io.File; import java.io.FileInputStream; @@ -14,11 +14,10 @@ import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.multipart.MultipartFile; -import com.baeldung.cloud.openfeign.exception.NotFoundException; -import com.baeldung.cloud.openfeign.fileupload.service.UploadService; +import com.baeldung.core.fileupload.service.UploadService; @RunWith(SpringRunner.class) -@SpringBootTest +@SpringBootTest(classes = ExampleApplication.class) public class OpenFeignFileUploadLiveTest { @Autowired @@ -26,36 +25,26 @@ public class OpenFeignFileUploadLiveTest { private static String FILE_NAME = "fileupload.txt"; - @Test(expected = NotFoundException.class) - public void whenFileUploadClientFallbackFactory_thenFileUploadError() throws IOException { + @Test + public void whenFeignBuilder_thenFileUploadSuccess() throws IOException { ClassLoader classloader = Thread.currentThread().getContextClassLoader(); File file = new File(classloader.getResource(FILE_NAME).getFile()); Assert.assertTrue(file.exists()); FileInputStream input = new FileInputStream(file); MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input)); - uploadService.uploadFileWithFallbackFactory(multipartFile); - } - - @Test(expected = NotFoundException.class) - public void whenFileUploadClientFallback_thenFileUploadError() throws IOException { - ClassLoader classloader = Thread.currentThread().getContextClassLoader(); - File file = new File(classloader.getResource(FILE_NAME).getFile()); - Assert.assertTrue(file.exists()); - FileInputStream input = new FileInputStream(file); - MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", - IOUtils.toByteArray(input)); - uploadService.uploadFileWithFallback(multipartFile); + Assert.assertTrue(uploadService.uploadFileWithManualClient(multipartFile)); } - @Test(expected = NotFoundException.class) - public void whenFileUploadWithMannualClient_thenFileUploadError() throws IOException { + @Test + public void whenAnnotatedFeignClient_thenFileUploadSuccess() throws IOException { ClassLoader classloader = Thread.currentThread().getContextClassLoader(); File file = new File(classloader.getResource(FILE_NAME).getFile()); Assert.assertTrue(file.exists()); FileInputStream input = new FileInputStream(file); MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input)); - uploadService.uploadFileWithManualClient(multipartFile); + String uploadFile = uploadService.uploadFile(multipartFile); + Assert.assertNotNull(uploadFile); } } diff --git a/feign/src/test/java/com/baeldung/core/client/FormClientUnitTest.java b/feign/src/test/java/com/baeldung/core/client/FormClientUnitTest.java new file mode 100644 index 0000000000..b9c263b60b --- /dev/null +++ b/feign/src/test/java/com/baeldung/core/client/FormClientUnitTest.java @@ -0,0 +1,78 @@ +package com.baeldung.core.client; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; +import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.core.defaulterrorhandling.model.FormData; +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.client.WireMock; + +import lombok.extern.slf4j.Slf4j; + +@ExtendWith(SpringExtension.class) +@SpringBootTest +@Slf4j +class FormClientUnitTest { + + private static WireMockServer wireMockServer; + + @Autowired + FormClient formClient; + + @BeforeAll + public static void startWireMockServer() { + wireMockServer = new WireMockServer(8085); + configureFor("localhost", 8085); + wireMockServer.start(); + + } + + @AfterAll + public static void stopWireMockServer() { + wireMockServer.stop(); + } + + @Test + public void givenFormData_whenPostFormDataCalled_thenReturnSuccess() { + FormData formData = new FormData(1, "baeldung"); + stubFor(WireMock.post(urlEqualTo("/api/form")) + .willReturn(aResponse().withStatus(HttpStatus.OK.value()))); + + formClient.postFormData(formData); + wireMockServer.verify(postRequestedFor(urlPathEqualTo("/api/form")) + .withHeader("Content-Type", equalTo("application/x-www-form-urlencoded; charset=UTF-8")) + .withRequestBody(equalTo("name=baeldung&id=1"))); + } + + @Test + public void givenFormMap_whenPostFormMapDataCalled_thenReturnSuccess() { + Map mapData = new HashMap<>(); + mapData.put("name", "baeldung"); + mapData.put("id", "1"); + stubFor(WireMock.post(urlEqualTo("/api/form/map")) + .willReturn(aResponse().withStatus(HttpStatus.OK.value()))); + + formClient.postFormMapData(mapData); + wireMockServer.verify(postRequestedFor(urlPathEqualTo("/api/form/map")) + .withHeader("Content-Type", equalTo("application/x-www-form-urlencoded; charset=UTF-8")) + .withRequestBody(equalTo("name=baeldung&id=1"))); + } + +} \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClientUnitTest.java b/feign/src/test/java/com/baeldung/core/customizederrorhandling/client/ProductClientUnitTest.java similarity index 69% rename from spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClientUnitTest.java rename to feign/src/test/java/com/baeldung/core/customizederrorhandling/client/ProductClientUnitTest.java index 7cf2a12692..ed5f18eb3f 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/client/ProductClientUnitTest.java +++ b/feign/src/test/java/com/baeldung/core/customizederrorhandling/client/ProductClientUnitTest.java @@ -1,8 +1,12 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.client; +package com.baeldung.core.customizederrorhandling.client; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static org.junit.Assert.assertThrows; -import com.baeldung.cloud.openfeign.customizederrorhandling.exception.ProductNotFoundException; -import com.baeldung.cloud.openfeign.customizederrorhandling.exception.ProductServiceNotAvailableException; -import com.github.tomakehurst.wiremock.WireMockServer; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -11,11 +15,13 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.junit.Assert.assertThrows; +import com.baeldung.core.ExampleApplication; +import com.baeldung.core.customizederrorhandling.exception.ProductNotFoundException; +import com.baeldung.core.customizederrorhandling.exception.ProductServiceNotAvailableException; +import com.github.tomakehurst.wiremock.WireMockServer; @RunWith(SpringRunner.class) -@SpringBootTest +@SpringBootTest(classes = ExampleApplication.class) public class ProductClientUnitTest { @Autowired diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductControllerUnitTest.java b/feign/src/test/java/com/baeldung/core/customizederrorhandling/controller/ProductControllerUnitTest.java similarity index 88% rename from spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductControllerUnitTest.java rename to feign/src/test/java/com/baeldung/core/customizederrorhandling/controller/ProductControllerUnitTest.java index cc9d029e07..04fd68d3e4 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/customizederrorhandling/controller/ProductControllerUnitTest.java +++ b/feign/src/test/java/com/baeldung/core/customizederrorhandling/controller/ProductControllerUnitTest.java @@ -1,10 +1,13 @@ -package com.baeldung.cloud.openfeign.customizederrorhandling.controller; +package com.baeldung.core.customizederrorhandling.controller; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static org.junit.Assert.assertEquals; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import com.baeldung.cloud.openfeign.customizederrorhandling.client.ProductClient; -import com.baeldung.cloud.openfeign.customizederrorhandling.exception.ErrorResponse; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.tomakehurst.wiremock.WireMockServer; -import com.github.tomakehurst.wiremock.client.WireMock; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -18,10 +21,11 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; -import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.junit.Assert.assertEquals; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import com.baeldung.core.customizederrorhandling.client.ProductClient; +import com.baeldung.core.customizederrorhandling.exception.ErrorResponse; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.client.WireMock; @RunWith(SpringRunner.class) diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/client/ProductClientUnitTest.java b/feign/src/test/java/com/baeldung/core/defaulterrorhandling/client/ProductClientUnitTest.java similarity index 81% rename from spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/client/ProductClientUnitTest.java rename to feign/src/test/java/com/baeldung/core/defaulterrorhandling/client/ProductClientUnitTest.java index 4dda2bbe15..8a9fa94074 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/client/ProductClientUnitTest.java +++ b/feign/src/test/java/com/baeldung/core/defaulterrorhandling/client/ProductClientUnitTest.java @@ -1,8 +1,13 @@ -package com.baeldung.cloud.openfeign.defaulterrorhandling.client; +package com.baeldung.core.defaulterrorhandling.client; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; -import com.baeldung.cloud.openfeign.defaulterrorhandling.model.Product; -import com.github.tomakehurst.wiremock.WireMockServer; -import feign.FeignException; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -12,12 +17,14 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit4.SpringRunner; -import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; +import com.baeldung.core.ExampleApplication; +import com.baeldung.core.defaulterrorhandling.model.Product; +import com.github.tomakehurst.wiremock.WireMockServer; + +import feign.FeignException; @RunWith(SpringRunner.class) -@SpringBootTest +@SpringBootTest(classes = ExampleApplication.class) public class ProductClientUnitTest { @Autowired diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/ProductControllerUnitTest.java b/feign/src/test/java/com/baeldung/core/defaulterrorhandling/controller/ProductControllerUnitTest.java similarity index 85% rename from spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/ProductControllerUnitTest.java rename to feign/src/test/java/com/baeldung/core/defaulterrorhandling/controller/ProductControllerUnitTest.java index f6ec7c3310..798ee9035c 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/ProductControllerUnitTest.java +++ b/feign/src/test/java/com/baeldung/core/defaulterrorhandling/controller/ProductControllerUnitTest.java @@ -1,8 +1,13 @@ -package com.baeldung.cloud.openfeign.defaulterrorhandling.controller; +package com.baeldung.core.defaulterrorhandling.controller; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.configureFor; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import com.baeldung.cloud.openfeign.defaulterrorhandling.client.ProductClient; -import com.github.tomakehurst.wiremock.WireMockServer; -import com.github.tomakehurst.wiremock.client.WireMock; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -16,10 +21,9 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; +import com.baeldung.core.defaulterrorhandling.client.ProductClient; +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.client.WireMock; @RunWith(SpringRunner.class) @WebMvcTest(ProductController.class) diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/TestControllerAdvice.java b/feign/src/test/java/com/baeldung/core/defaulterrorhandling/controller/TestControllerAdvice.java similarity index 88% rename from spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/TestControllerAdvice.java rename to feign/src/test/java/com/baeldung/core/defaulterrorhandling/controller/TestControllerAdvice.java index 0c7ed86b7c..dfd82ed07d 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/defaulterrorhandling/controller/TestControllerAdvice.java +++ b/feign/src/test/java/com/baeldung/core/defaulterrorhandling/controller/TestControllerAdvice.java @@ -1,11 +1,12 @@ -package com.baeldung.cloud.openfeign.defaulterrorhandling.controller; +package com.baeldung.core.defaulterrorhandling.controller; -import feign.FeignException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; +import feign.FeignException; + @RestControllerAdvice public class TestControllerAdvice { diff --git a/geotools/pom.xml b/geotools/pom.xml index 6edb344c8c..f17b4cc5da 100644 --- a/geotools/pom.xml +++ b/geotools/pom.xml @@ -39,13 +39,6 @@ gt-swing ${geotools-swing.version} - - org.locationtech.jts - jts-core - 1.19.0 - - - diff --git a/guava-modules/guava-collections/pom.xml b/guava-modules/guava-collections/pom.xml index 9283107023..8dc052db75 100644 --- a/guava-modules/guava-collections/pom.xml +++ b/guava-modules/guava-collections/pom.xml @@ -37,6 +37,7 @@ ${java-hamcrest.version} test + diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/Contact.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/Contact.java new file mode 100644 index 0000000000..6417d60310 --- /dev/null +++ b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/Contact.java @@ -0,0 +1,15 @@ +package com.baeldung.exceptions; + +public class Contact { + + private String email; + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + +} diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/Person.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/Person.java new file mode 100644 index 0000000000..1572d7a71f --- /dev/null +++ b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/Person.java @@ -0,0 +1,33 @@ +package com.baeldung.exceptions; + +public class Person { + + private String firstName; + private String lastName; + private String contact; + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getContact() { + return contact; + } + + public void setContact(String contact) { + this.contact = contact; + } + +} diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/PersonContact.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/PersonContact.java new file mode 100644 index 0000000000..0c75240d94 --- /dev/null +++ b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/PersonContact.java @@ -0,0 +1,33 @@ +package com.baeldung.exceptions; + +public class PersonContact { + + private String firstName; + private String lastName; + private Contact contact; + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public Contact getContact() { + return contact; + } + + public void setContact(Contact contact) { + this.contact = contact; + } + +} diff --git a/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java index 38ef3f9390..127d466436 100644 --- a/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java +++ b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java @@ -3,17 +3,14 @@ package com.baeldung.exceptions; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.List; import org.junit.Test; -import com.baeldung.exceptions.User; -import com.baeldung.exceptions.UserWithPrivateFields; -import com.baeldung.exceptions.UserWithRoot; -import com.baeldung.exceptions.Zoo; -import com.baeldung.exceptions.ZooConfigured; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.core.JsonFactory; @@ -82,6 +79,32 @@ public class JacksonExceptionsUnitTest { .readValue(json); } + @Test + public void givenJsonObject_whenDeserializingIntoString_thenException() throws IOException { + final String json = "{\"firstName\":\"Azhrioun\",\"lastName\":\"Abderrahim\",\"contact\":{\"email\":\"azh@email.com\"}}"; + final ObjectMapper mapper = new ObjectMapper(); + + Exception exception = assertThrows(JsonMappingException.class, () -> mapper.reader() + .forType(Person.class) + .readValue(json)); + + assertTrue(exception.getMessage() + .contains("Cannot deserialize value of type `java.lang.String` from Object value (token `JsonToken.START_OBJECT`)")); + } + + @Test + public void givenJsonObject_whenDeserializingIntoObject_thenDeserialize() throws IOException { + final String json = "{\"firstName\":\"Azhrioun\",\"lastName\":\"Abderrahim\",\"contact\":{\"email\":\"azh@email.com\"}}"; + final ObjectMapper mapper = new ObjectMapper(); + + PersonContact person = mapper.reader() + .forType(PersonContact.class) + .readValue(json); + + assertEquals("azh@email.com", person.getContact() + .getEmail()); + } + @Test public void givenDefaultConstructor_whenDeserializing_thenCorrect() throws IOException { final String json = "{\"id\":1,\"name\":\"John\"}"; diff --git a/jenkins-modules/jenkins-jobs/output-job/pipeline-command-substitution-job b/jenkins-modules/jenkins-jobs/output-job/pipeline-command-substitution-job new file mode 100644 index 0000000000..acaacfa867 --- /dev/null +++ b/jenkins-modules/jenkins-jobs/output-job/pipeline-command-substitution-job @@ -0,0 +1,13 @@ +pipeline { + agent any + stages { + stage('Example') { + steps { + script { + def output = sh(script: "echo \$(ls)", returnStdout: true) + echo "Output: ${output}" + } + } + } + } +} diff --git a/jenkins-modules/jenkins-jobs/output-job/pipeline-returnstatus-job b/jenkins-modules/jenkins-jobs/output-job/pipeline-returnstatus-job new file mode 100644 index 0000000000..1b1dc7d315 --- /dev/null +++ b/jenkins-modules/jenkins-jobs/output-job/pipeline-returnstatus-job @@ -0,0 +1,17 @@ +pipeline { + agent any + stages { + stage('Example') { + steps { + script { + def status = sh(returnStatus: true, script: 'ls /test') + if (status != 0) { + echo "Error: Command exited with status ${status}" + } else { + echo "Command executed successfully" + } + } + } + } + } +} diff --git a/jenkins-modules/jenkins-jobs/output-job/pipeline-returnstdout-job b/jenkins-modules/jenkins-jobs/output-job/pipeline-returnstdout-job new file mode 100644 index 0000000000..ad00b30d92 --- /dev/null +++ b/jenkins-modules/jenkins-jobs/output-job/pipeline-returnstdout-job @@ -0,0 +1,13 @@ +pipeline { + agent any + stages { + stage('Example') { + steps { + script { + def output = sh(returnStdout: true, script: 'pwd') + echo "Output: ${output}" + } + } + } + } +} diff --git a/jenkins-modules/jenkins-jobs/output-job/pipeline-returnstdouttrim-job b/jenkins-modules/jenkins-jobs/output-job/pipeline-returnstdouttrim-job new file mode 100644 index 0000000000..d253173934 --- /dev/null +++ b/jenkins-modules/jenkins-jobs/output-job/pipeline-returnstdouttrim-job @@ -0,0 +1,13 @@ +pipeline { + agent any + stages { + stage('Example') { + steps { + script { + def output = sh(returnStdout: true, returnStdoutTrim: true, script: 'echo " hello "') + echo "Output: '${output}'" + } + } + } + } +} diff --git a/json-modules/gson/src/test/java/com/baeldung/gson/serialization/GsonSerializeUnitTest.java b/json-modules/gson/src/test/java/com/baeldung/gson/serialization/GsonSerializeUnitTest.java index d5051060c4..21d2bedd24 100644 --- a/json-modules/gson/src/test/java/com/baeldung/gson/serialization/GsonSerializeUnitTest.java +++ b/json-modules/gson/src/test/java/com/baeldung/gson/serialization/GsonSerializeUnitTest.java @@ -23,8 +23,8 @@ public class GsonSerializeUnitTest { ActorGson rudyYoungblood = new ActorGson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers")); Movie movie = new Movie("tt0472043", "Mel Gibson", Arrays.asList(rudyYoungblood)); - String expectedOutput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"Sep 21, 1982 12:00:00 AM\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; - Assert.assertEquals(new Gson().toJson(movie), expectedOutput); + String expectedOutput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"Sep 21, 1982, 12:00:00 AM\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; + Assert.assertEquals(expectedOutput, new Gson().toJson(movie)); } @Test diff --git a/json-modules/gson/src/test/java/com/baeldung/gson/serialization/test/GsonSerializationUnitTest.java b/json-modules/gson/src/test/java/com/baeldung/gson/serialization/test/GsonSerializationUnitTest.java index 3b8912d259..13fea27b24 100644 --- a/json-modules/gson/src/test/java/com/baeldung/gson/serialization/test/GsonSerializationUnitTest.java +++ b/json-modules/gson/src/test/java/com/baeldung/gson/serialization/test/GsonSerializationUnitTest.java @@ -1,7 +1,7 @@ package com.baeldung.gson.serialization.test; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; + import java.lang.reflect.Type; import java.util.Collection; @@ -88,7 +88,7 @@ public class GsonSerializationUnitTest { String jsonDate = gson.toJson(sourceDate, sourceDateType); System.out.println("jsonDate:\n" + jsonDate); - String expectedResult = "\"Jan 1, 2000 12:00:00 AM\""; + String expectedResult = "\"Jan 1, 2000, 12:00:00 AM\""; assertEquals(expectedResult, jsonDate); } diff --git a/json-modules/json-2/pom.xml b/json-modules/json-2/pom.xml index ee58ab8b25..82fe689ebf 100644 --- a/json-modules/json-2/pom.xml +++ b/json-modules/json-2/pom.xml @@ -3,7 +3,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung json-2 0.0.1-SNAPSHOT @@ -119,6 +118,11 @@ RELEASE test + + javax.annotation + javax.annotation-api + 1.3.2 + diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index ea1b2ca8b6..1d5cde75a2 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -12,22 +12,6 @@ 1.0.0-SNAPSHOT - - - jboss-public-repository-group - JBoss Public Repository Group - http://repository.jboss.org/nexus/content/groups/public/ - - true - never - - - true - daily - - - - org.mapdb @@ -82,6 +66,12 @@ edu.uci.ics crawler4j ${crawler4j.version} + + + com.sleepycat + je + + com.github.jknack @@ -119,22 +109,40 @@ spring-jdbc ${spring.version} + + com.sleepycat + je + 18.3.12 + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + --add-exports=java.base/jdk.internal.ref=ALL-UNNAMED --add-exports=java.base/sun.nio.ch=ALL-UNNAMED --add-exports=jdk.unsupported/sun.misc=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED + + + + + - 3.0.7 - 4.8.28 - 6.0.0.Final - 3.9.6 - 3.17.2 + 3.0.8 + 4.8.153 + 7.1.0.Final + 4.7.0 + 3.24ea1 4.4.0 - 2.1.4.RELEASE - 0.28.3 + 2.7.8 + 1.11.0 1.1.0 - 4.1.2 - 6.17.0 - 5.1.9.RELEASE - 2.5.0 + 4.3.1 + 6.20.0 + 5.3.25 + 2.7.1 \ No newline at end of file diff --git a/libraries-2/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java b/libraries-2/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java index adc753a8ad..e1ad2f7537 100644 --- a/libraries-2/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java @@ -40,7 +40,7 @@ public class ParallelCollectorsUnitTest { List ids = Arrays.asList(1, 2, 3); CompletableFuture> results = ids.stream() - .collect(parallelToList(i -> fetchById(i), executor, 4)); + .collect(parallelToList(ParallelCollectorsUnitTest::fetchById, executor, 4)); System.out.println(results.join()); } @@ -52,7 +52,7 @@ public class ParallelCollectorsUnitTest { List ids = Arrays.asList(1, 2, 3); List results = ids.stream() - .collect(parallelToList(i -> fetchById(i), executor, 4)) + .collect(parallelToList(ParallelCollectorsUnitTest::fetchById, executor, 4)) .join(); System.out.println(results); // [user-1, user-2, user-3] @@ -92,7 +92,7 @@ public class ParallelCollectorsUnitTest { List ids = Arrays.asList(1, 2, 3); ids.stream() - .collect(parallel(i -> fetchByIdWithRandomDelay(i), executor, 4)) + .collect(parallel(ParallelCollectorsUnitTest::fetchByIdWithRandomDelay, executor, 4)) .forEach(System.out::println); } @@ -103,7 +103,7 @@ public class ParallelCollectorsUnitTest { List ids = Arrays.asList(1, 2, 3); ids.stream() - .collect(parallelOrdered(i -> fetchByIdWithRandomDelay(i), executor, 4)) + .collect(parallelOrdered(ParallelCollectorsUnitTest::fetchByIdWithRandomDelay, executor, 4)) .forEach(System.out::println); } @@ -114,7 +114,7 @@ public class ParallelCollectorsUnitTest { List ids = Arrays.asList(1, 2, 3); Map results = ids.stream() - .collect(parallelToMap(i -> i, i -> fetchById(i), executor, 4)) + .collect(parallelToMap(i -> i, ParallelCollectorsUnitTest::fetchById, executor, 4)) .join(); System.out.println(results); // {1=user-1, 2=user-2, 3=user-3} @@ -127,7 +127,7 @@ public class ParallelCollectorsUnitTest { List ids = Arrays.asList(1, 2, 3); Map results = ids.stream() - .collect(parallelToMap(i -> i, i -> fetchById(i), TreeMap::new, executor, 4)) + .collect(parallelToMap(i -> i, ParallelCollectorsUnitTest::fetchById, TreeMap::new, executor, 4)) .join(); System.out.println(results); // {1=user-1, 2=user-2, 3=user-3} @@ -140,7 +140,7 @@ public class ParallelCollectorsUnitTest { List ids = Arrays.asList(1, 2, 3); Map results = ids.stream() - .collect(parallelToMap(i -> i, i -> fetchById(i), TreeMap::new, (s1, s2) -> s1, executor, 4)) + .collect(parallelToMap(i -> i, ParallelCollectorsUnitTest::fetchById, TreeMap::new, (s1, s2) -> s1, executor, 4)) .join(); System.out.println(results); // {1=user-1, 2=user-2, 3=user-3} diff --git a/libraries-apache-commons-io/pom.xml b/libraries-apache-commons-io/pom.xml index b45572ddad..7cac50a8e2 100644 --- a/libraries-apache-commons-io/pom.xml +++ b/libraries-apache-commons-io/pom.xml @@ -26,7 +26,7 @@ - 1.9.0 + 1.10.0 \ No newline at end of file diff --git a/libraries-apache-commons-io/src/test/java/com/baeldung/commons/io/csv/CSVReaderWriterUnitTest.java b/libraries-apache-commons-io/src/test/java/com/baeldung/commons/io/csv/CSVReaderWriterUnitTest.java index b99f4e8bc3..b37613e962 100644 --- a/libraries-apache-commons-io/src/test/java/com/baeldung/commons/io/csv/CSVReaderWriterUnitTest.java +++ b/libraries-apache-commons-io/src/test/java/com/baeldung/commons/io/csv/CSVReaderWriterUnitTest.java @@ -1,9 +1,11 @@ package com.baeldung.commons.io.csv; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.CSVRecord; -import org.junit.Test; import java.io.FileReader; import java.io.IOException; @@ -13,9 +15,7 @@ import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; - -public class CSVReaderWriterUnitTest { +class CSVReaderWriterUnitTest { public static final Map AUTHOR_BOOK_MAP = Collections.unmodifiableMap(new LinkedHashMap() { { @@ -24,12 +24,24 @@ public class CSVReaderWriterUnitTest { } }); public static final String[] HEADERS = { "author", "title" }; + + enum BookHeaders{ + author, title + } + public static final String EXPECTED_FILESTREAM = "author,title\r\n" + "Dan Simmons,Hyperion\r\n" + "Douglas Adams,The Hitchhiker's Guide to the Galaxy"; @Test - public void givenCSVFile_whenRead_thenContentsAsExpected() throws IOException { + void givenCSVFile_whenReadWithArrayHeader_thenContentsAsExpected() throws IOException { Reader in = new FileReader("src/test/resources/book.csv"); - Iterable records = CSVFormat.DEFAULT.withHeader(HEADERS).withFirstRecordAsHeader().parse(in); + + CSVFormat csvFormat = CSVFormat.DEFAULT.builder() + .setHeader(HEADERS) + .setSkipHeaderRecord(true) + .build(); + + Iterable records = csvFormat.parse(in); + for (CSVRecord record : records) { String author = record.get("author"); String title = record.get("title"); @@ -38,9 +50,32 @@ public class CSVReaderWriterUnitTest { } @Test - public void givenAuthorBookMap_whenWrittenToStream_thenOutputStreamAsExpected() throws IOException { + void givenCSVFile_whenReadWithEnumHeader_thenContentsAsExpected() throws IOException { + Reader in = new FileReader("src/test/resources/book.csv"); + + CSVFormat csvFormat = CSVFormat.DEFAULT.builder() + .setHeader(BookHeaders.class) + .setSkipHeaderRecord(true) + .build(); + + Iterable records = csvFormat.parse(in); + + for (CSVRecord record : records) { + String author = record.get(BookHeaders.author); + String title = record.get(BookHeaders.title); + assertEquals(AUTHOR_BOOK_MAP.get(author), title); + } + } + + @Test + void givenAuthorBookMap_whenWrittenToStream_thenOutputStreamAsExpected() throws IOException { StringWriter sw = new StringWriter(); - try (final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withHeader(HEADERS))) { + + CSVFormat csvFormat = CSVFormat.DEFAULT.builder() + .setHeader(BookHeaders.class) + .build(); + + try (final CSVPrinter printer = new CSVPrinter(sw, csvFormat)) { AUTHOR_BOOK_MAP.forEach((author, title) -> { try { printer.printRecord(author, title); @@ -49,7 +84,8 @@ public class CSVReaderWriterUnitTest { } }); } - assertEquals(EXPECTED_FILESTREAM, sw.toString().trim()); + assertEquals(EXPECTED_FILESTREAM, sw.toString() + .trim()); } } diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 85edf8b69a..a3e3f4f539 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -58,6 +58,11 @@ crunch-core ${org.apache.crunch.crunch-core.version} + + org.javassist + javassist + ${javassist.version} + org.apache.hadoop hadoop-client @@ -138,6 +143,15 @@ + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + org.apache.maven.plugins maven-assembly-plugin @@ -166,6 +180,8 @@ + 11 + 11 2.3 3.1 1.2.2 @@ -178,6 +194,7 @@ 1.0.0 2.2.0 1.6.0.1 + 3.29.2-GA \ No newline at end of file diff --git a/libraries-data/src/test/java/com/baeldung/crunch/StopWordFilterUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/StopWordFilterUnitTest.java index fffefc2bfb..0bb03016d8 100644 --- a/libraries-data/src/test/java/com/baeldung/crunch/StopWordFilterUnitTest.java +++ b/libraries-data/src/test/java/com/baeldung/crunch/StopWordFilterUnitTest.java @@ -7,6 +7,7 @@ import static org.junit.Assert.assertTrue; import org.apache.crunch.FilterFn; import org.apache.crunch.PCollection; import org.apache.crunch.impl.mem.MemPipeline; +import org.junit.Ignore; import org.junit.Test; import com.google.common.collect.ImmutableList; diff --git a/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseWithCounterFnUnitTest.java b/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseWithCounterFnUnitTest.java index 76294d273d..00c508e605 100644 --- a/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseWithCounterFnUnitTest.java +++ b/libraries-data/src/test/java/com/baeldung/crunch/ToUpperCaseWithCounterFnUnitTest.java @@ -6,6 +6,7 @@ import org.apache.crunch.PCollection; import org.apache.crunch.impl.mem.MemPipeline; import org.apache.crunch.types.writable.Writables; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import com.google.common.collect.ImmutableList; diff --git a/libraries-testing/pom.xml b/libraries-testing/pom.xml index 2aaad59e09..9274c292ba 100644 --- a/libraries-testing/pom.xml +++ b/libraries-testing/pom.xml @@ -179,17 +179,16 @@ 1.9.9 1.9.0 1.9.0 - 1.9.27 + 3.6.12 1.5.0 3.0.0 0.8.1 4.3.8.RELEASE - 4.1.1 + 5.3.0 2.0.0.0 2.7.0 0.14.1 1.0.0 - 2.1.214 \ No newline at end of file diff --git a/messaging-modules/pom.xml b/messaging-modules/pom.xml index f843b0fe11..8bda46f5cd 100644 --- a/messaging-modules/pom.xml +++ b/messaging-modules/pom.xml @@ -18,7 +18,6 @@ jgroups rabbitmq spring-amqp - spring-apache-camel spring-jms diff --git a/messaging-modules/spring-apache-camel/.gitignore b/messaging-modules/spring-apache-camel/.gitignore index eac473ac50..f137d908d6 100644 --- a/messaging-modules/spring-apache-camel/.gitignore +++ b/messaging-modules/spring-apache-camel/.gitignore @@ -1 +1,2 @@ -/src/test/destination-folder/* \ No newline at end of file +/src/test/destination-folder/* +/output/ \ No newline at end of file diff --git a/messaging-modules/spring-apache-camel/README.md b/messaging-modules/spring-apache-camel/README.md index 6a16e1da05..535c61cbef 100644 --- a/messaging-modules/spring-apache-camel/README.md +++ b/messaging-modules/spring-apache-camel/README.md @@ -4,17 +4,19 @@ This module contains articles about Spring with Apache Camel ### Relevant Articles -- [Apache Camel](http://camel.apache.org/) -- [Enterprise Integration Patterns](http://www.enterpriseintegrationpatterns.com/patterns/messaging/toc.html) - [Introduction To Apache Camel](http://www.baeldung.com/apache-camel-intro) - [Integration Patterns With Apache Camel](http://www.baeldung.com/camel-integration-patterns) - [Using Apache Camel with Spring](http://www.baeldung.com/spring-apache-camel-tutorial) - [Unmarshalling a JSON Array Using camel-jackson](https://www.baeldung.com/java-camel-jackson-json-array) +- [Apache Camel with Spring Boot](https://www.baeldung.com/apache-camel-spring-boot) +- [Apache Camel Routes Testing in Spring Boot](https://www.baeldung.com/spring-boot-apache-camel-routes-testing) +- [Apache Camel Conditional Routing](https://www.baeldung.com/spring-apache-camel-conditional-routing) +- [Apache Camel Exception Handling](https://www.baeldung.com/java-apache-camel-exception-handling) ### Framework Versions: -- Spring 4.2.4 -- Apache Camel 2.16.1 +- Spring 5.3.25 +- Apache Camel 3.14.7 ### Build and Run Application diff --git a/messaging-modules/spring-apache-camel/pom.xml b/messaging-modules/spring-apache-camel/pom.xml index 9f2e74dc36..ec7557666c 100644 --- a/messaging-modules/spring-apache-camel/pom.xml +++ b/messaging-modules/spring-apache-camel/pom.xml @@ -58,11 +58,67 @@ ${env.camel.version} test + + org.apache.camel.springboot + camel-servlet-starter + ${camel.version} + + + org.apache.camel.springboot + camel-jackson-starter + ${camel.version} + + + org.apache.camel.springboot + camel-swagger-java-starter + ${camel.version} + + + org.apache.camel.springboot + camel-spring-boot-starter + ${camel.version} + + + org.springframework.boot + spring-boot-starter-web + + + org.apache.camel + camel-test-spring-junit5 + ${camel.version} + test + - 2.18.1 - 4.3.4.RELEASE + 3.14.7 + 5.3.25 + 3.15.0 + + + spring-boot + + spring-boot:run + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + com.baeldung.camel.boot.boot.testing.GreetingsFileSpringApplication + + + + + + + + + \ No newline at end of file diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/ContentBasedFileRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/ContentBasedFileRouter.java similarity index 94% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/ContentBasedFileRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/ContentBasedFileRouter.java index 9106e996c3..2a3f7e5c7b 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/ContentBasedFileRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/ContentBasedFileRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.file; +package com.baeldung.camel.apache.file; import org.apache.camel.builder.RouteBuilder; diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/DeadLetterChannelFileRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/DeadLetterChannelFileRouter.java similarity index 94% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/DeadLetterChannelFileRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/DeadLetterChannelFileRouter.java index fdcad99f02..37a81af458 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/DeadLetterChannelFileRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/DeadLetterChannelFileRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.file; +package com.baeldung.camel.apache.file; import org.apache.camel.LoggingLevel; import org.apache.camel.builder.RouteBuilder; diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/FileProcessor.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/FileProcessor.java similarity index 93% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/FileProcessor.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/FileProcessor.java index 1ea2cad188..ce4d92e8ab 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/FileProcessor.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/FileProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.file; +package com.baeldung.camel.apache.file; import java.text.SimpleDateFormat; import java.util.Date; diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/FileRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/FileRouter.java similarity index 91% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/FileRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/FileRouter.java index 5216c9a595..760f37677b 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/FileRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/FileRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.file; +package com.baeldung.camel.apache.file; import org.apache.camel.builder.RouteBuilder; diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/MessageTranslatorFileRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/MessageTranslatorFileRouter.java similarity index 92% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/MessageTranslatorFileRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/MessageTranslatorFileRouter.java index b99de99dac..5e65c24c40 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/MessageTranslatorFileRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/MessageTranslatorFileRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.file; +package com.baeldung.camel.apache.file; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/MulticastFileRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/MulticastFileRouter.java similarity index 95% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/MulticastFileRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/MulticastFileRouter.java index 75a6e81d45..6f6aad177d 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/MulticastFileRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/MulticastFileRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.file; +package com.baeldung.camel.apache.file; import org.apache.camel.builder.RouteBuilder; diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/SplitterFileRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/SplitterFileRouter.java similarity index 93% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/SplitterFileRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/SplitterFileRouter.java index 551f9c9685..471dfa7a46 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/SplitterFileRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/SplitterFileRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.file; +package com.baeldung.camel.apache.file; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/cfg/ContentBasedFileRouterConfig.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/cfg/ContentBasedFileRouterConfig.java similarity index 84% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/cfg/ContentBasedFileRouterConfig.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/cfg/ContentBasedFileRouterConfig.java index ceb68dfa3b..2b24cf2a51 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/file/cfg/ContentBasedFileRouterConfig.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/cfg/ContentBasedFileRouterConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.file.cfg; +package com.baeldung.camel.apache.file.cfg; import java.util.Arrays; import java.util.List; @@ -8,7 +8,7 @@ import org.apache.camel.spring.javaconfig.CamelConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.baeldung.camel.file.ContentBasedFileRouter; +import com.baeldung.camel.apache.file.ContentBasedFileRouter; @Configuration public class ContentBasedFileRouterConfig extends CamelConfiguration { diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/jackson/Fruit.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/jackson/Fruit.java similarity index 87% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/jackson/Fruit.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/jackson/Fruit.java index 1932131ddd..d46eb0afd5 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/jackson/Fruit.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/jackson/Fruit.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.jackson; +package com.baeldung.camel.apache.jackson; public class Fruit { diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/jackson/FruitList.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/jackson/FruitList.java similarity index 84% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/jackson/FruitList.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/jackson/FruitList.java index 02f2b6feb0..f8678c6a1e 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/jackson/FruitList.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/jackson/FruitList.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.jackson; +package com.baeldung.camel.apache.jackson; import java.util.List; diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/main/App.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/main/App.java similarity index 91% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/main/App.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/main/App.java index ac0605a215..6071db0580 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/main/App.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/main/App.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.main; +package com.baeldung.camel.apache.main; import org.springframework.context.support.ClassPathXmlApplicationContext; diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/processor/FileProcessor.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/processor/FileProcessor.java similarity index 89% rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/processor/FileProcessor.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/processor/FileProcessor.java index 971dd206cd..5ca61a382a 100644 --- a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/processor/FileProcessor.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/processor/FileProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.processor; +package com.baeldung.camel.apache.processor; import org.apache.camel.Exchange; import org.apache.camel.Processor; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/Application.java similarity index 97% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/Application.java index 48294e9c56..797ad57202 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/Application.java @@ -1,4 +1,4 @@ -package com.baeldung.camel; +package com.baeldung.camel.boot; import javax.ws.rs.core.MediaType; @@ -22,7 +22,7 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Component; @SpringBootApplication(exclude = { WebSocketServletAutoConfiguration.class, AopAutoConfiguration.class, OAuth2ResourceServerAutoConfiguration.class, EmbeddedWebServerFactoryCustomizerAutoConfiguration.class }) -@ComponentScan(basePackages = "com.baeldung.camel") +@ComponentScan(basePackages = "com.baeldung.camel.boot") public class Application { @Value("${server.port}") diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/ExampleServices.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/ExampleServices.java similarity index 90% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/ExampleServices.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/ExampleServices.java index ec8f368e68..6fe5a1ed32 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/ExampleServices.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/ExampleServices.java @@ -1,4 +1,4 @@ -package com.baeldung.camel; +package com.baeldung.camel.boot; /** * a Mock class to show how some other layer diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/MyBean.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/MyBean.java similarity index 90% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/MyBean.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/MyBean.java index 5368e40c93..759fb06459 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/MyBean.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/MyBean.java @@ -1,4 +1,4 @@ -package com.baeldung.camel; +package com.baeldung.camel.boot; public class MyBean { private Integer id; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/boot/testing/GreetingsFileRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/boot/testing/GreetingsFileRouter.java similarity index 89% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/boot/testing/GreetingsFileRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/boot/testing/GreetingsFileRouter.java index 670af5e08c..381a0a61a5 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/boot/testing/GreetingsFileRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/boot/testing/GreetingsFileRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.boot.testing; +package com.baeldung.camel.boot.boot.testing; import org.apache.camel.builder.RouteBuilder; import org.springframework.stereotype.Component; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/boot/testing/GreetingsFileSpringApplication.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/boot/testing/GreetingsFileSpringApplication.java similarity index 87% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/boot/testing/GreetingsFileSpringApplication.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/boot/testing/GreetingsFileSpringApplication.java index a4e862e65d..1d20d1977a 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/boot/testing/GreetingsFileSpringApplication.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/boot/testing/GreetingsFileSpringApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.boot.testing; +package com.baeldung.camel.boot.boot.testing; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalBeanRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalBeanRouter.java similarity index 93% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalBeanRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalBeanRouter.java index 8a03f6ef18..a747ba1f66 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalBeanRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalBeanRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.conditional; +package com.baeldung.camel.boot.conditional; import org.apache.camel.builder.RouteBuilder; import org.springframework.stereotype.Component; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalBodyRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalBodyRouter.java similarity index 93% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalBodyRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalBodyRouter.java index 99d23c747b..ea4f77cb9a 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalBodyRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalBodyRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.conditional; +package com.baeldung.camel.boot.conditional; import org.apache.camel.builder.RouteBuilder; import org.springframework.stereotype.Component; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalHeaderRouter.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalHeaderRouter.java similarity index 93% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalHeaderRouter.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalHeaderRouter.java index e723f97ef1..93371b06b6 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalHeaderRouter.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalHeaderRouter.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.conditional; +package com.baeldung.camel.boot.conditional; import org.apache.camel.builder.RouteBuilder; import org.springframework.stereotype.Component; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalRoutingSpringApplication.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalRoutingSpringApplication.java similarity index 88% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalRoutingSpringApplication.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalRoutingSpringApplication.java index f20d23068a..f11b4302c7 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/ConditionalRoutingSpringApplication.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/ConditionalRoutingSpringApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.conditional; +package com.baeldung.camel.boot.conditional; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/FruitBean.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/FruitBean.java similarity index 84% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/FruitBean.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/FruitBean.java index 080e3393b6..a3481361bd 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/conditional/FruitBean.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/conditional/FruitBean.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.conditional; +package com.baeldung.camel.boot.conditional; import org.apache.camel.Exchange; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionHandlingSpringApplication.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionHandlingSpringApplication.java similarity index 88% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionHandlingSpringApplication.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionHandlingSpringApplication.java index df4550d9d5..bfa08a5c7a 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionHandlingSpringApplication.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionHandlingSpringApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.exception; +package com.baeldung.camel.boot.exception; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionHandlingWithDoTryRoute.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionHandlingWithDoTryRoute.java similarity index 94% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionHandlingWithDoTryRoute.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionHandlingWithDoTryRoute.java index ce3cfc129b..d4c365d25c 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionHandlingWithDoTryRoute.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionHandlingWithDoTryRoute.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.exception; +package com.baeldung.camel.boot.exception; import java.io.IOException; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionHandlingWithExceptionClauseRoute.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionHandlingWithExceptionClauseRoute.java similarity index 94% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionHandlingWithExceptionClauseRoute.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionHandlingWithExceptionClauseRoute.java index 3a438e2402..e2ee3252de 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionHandlingWithExceptionClauseRoute.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionHandlingWithExceptionClauseRoute.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.exception; +package com.baeldung.camel.boot.exception; import org.apache.camel.builder.RouteBuilder; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionLoggingProcessor.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionLoggingProcessor.java similarity index 94% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionLoggingProcessor.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionLoggingProcessor.java index 84e4072888..66add64441 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionLoggingProcessor.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionLoggingProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.exception; +package com.baeldung.camel.boot.exception; import java.util.Map; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionThrowingRoute.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionThrowingRoute.java similarity index 95% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionThrowingRoute.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionThrowingRoute.java index 752aabaf1a..bf4d464c23 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/ExceptionThrowingRoute.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/ExceptionThrowingRoute.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.exception; +package com.baeldung.camel.boot.exception; import org.apache.camel.Exchange; import org.apache.camel.Processor; diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/IllegalArgumentExceptionThrowingProcessor.java b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/IllegalArgumentExceptionThrowingProcessor.java similarity index 93% rename from spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/IllegalArgumentExceptionThrowingProcessor.java rename to messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/IllegalArgumentExceptionThrowingProcessor.java index 461a4e6553..db229418d2 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/exception/IllegalArgumentExceptionThrowingProcessor.java +++ b/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/boot/exception/IllegalArgumentExceptionThrowingProcessor.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.exception; +package com.baeldung.camel.boot.exception; import org.apache.camel.Exchange; import org.apache.camel.Processor; diff --git a/spring-boot-modules/spring-boot-camel/src/main/resources/application.properties b/messaging-modules/spring-apache-camel/src/main/resources/application.properties similarity index 100% rename from spring-boot-modules/spring-boot-camel/src/main/resources/application.properties rename to messaging-modules/spring-apache-camel/src/main/resources/application.properties diff --git a/spring-boot-modules/spring-boot-camel/src/main/resources/application.yml b/messaging-modules/spring-apache-camel/src/main/resources/application.yml similarity index 100% rename from spring-boot-modules/spring-boot-camel/src/main/resources/application.yml rename to messaging-modules/spring-apache-camel/src/main/resources/application.yml diff --git a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-ContentBasedFileRouterTest.xml b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-ContentBasedFileRouterTest.xml index d6d3e62f1c..e93b9fb144 100644 --- a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-ContentBasedFileRouterTest.xml +++ b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-ContentBasedFileRouterTest.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> - + diff --git a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-DeadLetterChannelFileRouter.xml b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-DeadLetterChannelFileRouter.xml index ef61174b32..b9db0a189f 100644 --- a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-DeadLetterChannelFileRouter.xml +++ b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-DeadLetterChannelFileRouter.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> - + diff --git a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-MessageTranslatorFileRouterTest.xml b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-MessageTranslatorFileRouterTest.xml index 7ab988ca8a..fcb9e2b8be 100644 --- a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-MessageTranslatorFileRouterTest.xml +++ b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-MessageTranslatorFileRouterTest.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> - + diff --git a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-MulticastFileRouterTest.xml b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-MulticastFileRouterTest.xml index 6f7e7cbb60..73adecbc98 100644 --- a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-MulticastFileRouterTest.xml +++ b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-MulticastFileRouterTest.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> - + diff --git a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-SplitterFileRouter.xml b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-SplitterFileRouter.xml index 9d4a890cc6..a2ebe76e63 100644 --- a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-SplitterFileRouter.xml +++ b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-SplitterFileRouter.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> - + diff --git a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-test.xml b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-test.xml index e6435db9e5..f306574868 100644 --- a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-test.xml +++ b/messaging-modules/spring-apache-camel/src/main/resources/camel-context-test.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> - - + + diff --git a/messaging-modules/spring-apache-camel/src/main/resources/camel-context.xml b/messaging-modules/spring-apache-camel/src/main/resources/camel-context.xml index 63ef406fdf..721ccab95c 100644 --- a/messaging-modules/spring-apache-camel/src/main/resources/camel-context.xml +++ b/messaging-modules/spring-apache-camel/src/main/resources/camel-context.xml @@ -35,5 +35,5 @@ - + \ No newline at end of file diff --git a/messaging-modules/spring-apache-camel/src/test/java/com/baeldung/SpringContextTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/SpringContextTest.java similarity index 67% rename from messaging-modules/spring-apache-camel/src/test/java/com/baeldung/SpringContextTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/SpringContextTest.java index 14e7de2095..56969da1d7 100644 --- a/messaging-modules/spring-apache-camel/src/test/java/com/baeldung/SpringContextTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/SpringContextTest.java @@ -1,8 +1,8 @@ -package com.baeldung; +package com.apache.baeldung; import org.junit.Test; -import com.baeldung.camel.main.App; +import com.baeldung.camel.apache.main.App; public class SpringContextTest { diff --git a/messaging-modules/spring-apache-camel/src/test/java/com/baeldung/camel/jackson/FruitArrayJacksonUnmarshalUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitArrayJacksonUnmarshalUnitTest.java similarity index 95% rename from messaging-modules/spring-apache-camel/src/test/java/com/baeldung/camel/jackson/FruitArrayJacksonUnmarshalUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitArrayJacksonUnmarshalUnitTest.java index 4810d7370e..bc0025b263 100644 --- a/messaging-modules/spring-apache-camel/src/test/java/com/baeldung/camel/jackson/FruitArrayJacksonUnmarshalUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitArrayJacksonUnmarshalUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.jackson; +package com.apache.baeldung.camel.jackson; import java.io.IOException; import java.net.URISyntaxException; @@ -13,6 +13,8 @@ import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; +import com.baeldung.camel.apache.jackson.Fruit; + public class FruitArrayJacksonUnmarshalUnitTest extends CamelTestSupport { @Test diff --git a/messaging-modules/spring-apache-camel/src/test/java/com/baeldung/camel/jackson/FruitListJacksonUnmarshalUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitListJacksonUnmarshalUnitTest.java similarity index 93% rename from messaging-modules/spring-apache-camel/src/test/java/com/baeldung/camel/jackson/FruitListJacksonUnmarshalUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitListJacksonUnmarshalUnitTest.java index b5647f02f9..2d15ebf46b 100644 --- a/messaging-modules/spring-apache-camel/src/test/java/com/baeldung/camel/jackson/FruitListJacksonUnmarshalUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitListJacksonUnmarshalUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.camel.jackson; +package com.apache.baeldung.camel.jackson; import java.io.IOException; import java.net.URISyntaxException; @@ -13,6 +13,9 @@ import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; +import com.baeldung.camel.apache.jackson.Fruit; +import com.baeldung.camel.apache.jackson.FruitList; + public class FruitListJacksonUnmarshalUnitTest extends CamelTestSupport { @Test diff --git a/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/file/processor/ContentBasedFileRouterIntegrationTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/file/processor/ContentBasedFileRouterIntegrationTest.java index 23f5787e4e..1fc3ee7515 100644 --- a/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/file/processor/ContentBasedFileRouterIntegrationTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/file/processor/ContentBasedFileRouterIntegrationTest.java @@ -11,7 +11,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -import com.baeldung.camel.file.cfg.ContentBasedFileRouterConfig; +import com.baeldung.camel.apache.file.cfg.ContentBasedFileRouterConfig; @RunWith(JUnit4.class) public class ContentBasedFileRouterIntegrationTest { diff --git a/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/file/processor/FileProcessorIntegrationTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/file/processor/FileProcessorIntegrationTest.java index 1d88e8aeb4..bc5de17537 100644 --- a/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/file/processor/FileProcessorIntegrationTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/file/processor/FileProcessorIntegrationTest.java @@ -9,7 +9,7 @@ import org.junit.Before; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; -import com.baeldung.camel.file.FileProcessor; +import com.baeldung.camel.apache.file.FileProcessor; public class FileProcessorIntegrationTest { diff --git a/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/main/AppIntegrationTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/main/AppIntegrationTest.java index b33e6a3b29..cef387dc14 100644 --- a/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/main/AppIntegrationTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/main/AppIntegrationTest.java @@ -1,6 +1,6 @@ package com.apache.camel.main; -import com.baeldung.camel.main.App; +import com.baeldung.camel.apache.main.App; import junit.framework.TestCase; import org.apache.camel.util.FileUtil; import org.junit.After; diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/SpringContextTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/boot/SpringContextTest.java similarity index 85% rename from spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/SpringContextTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/boot/SpringContextTest.java index ce743e0f77..527877f47e 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/SpringContextTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/boot/SpringContextTest.java @@ -1,11 +1,11 @@ -package com.baeldung; +package com.boot; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.camel.Application; +import com.baeldung.camel.boot.Application; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/boot/testing/GreetingsFileRouterUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/boot/testing/GreetingsFileRouterUnitTest.java similarity index 71% rename from spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/boot/testing/GreetingsFileRouterUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/boot/testing/GreetingsFileRouterUnitTest.java index baeb1fd39c..0f4d71f23b 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/boot/testing/GreetingsFileRouterUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/boot/testing/GreetingsFileRouterUnitTest.java @@ -1,4 +1,6 @@ -package com.baeldung.camel.boot.testing; +package com.boot.camel.boot.testing; + +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; @@ -8,10 +10,14 @@ import org.apache.camel.test.spring.junit5.MockEndpoints; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; -@SpringBootTest +import com.baeldung.camel.boot.Application; + +@SpringBootTest(classes = Application.class) @CamelSpringBootTest @MockEndpoints("file:output") +@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class GreetingsFileRouterUnitTest { @Autowired @@ -21,6 +27,7 @@ class GreetingsFileRouterUnitTest { private MockEndpoint mock; @Test + @DirtiesContext void whenSendBody_thenGreetingReceivedSuccessfully() throws InterruptedException { mock.expectedBodiesReceived("Hello Baeldung Readers!"); diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/conditional/ConditionalBeanRouterUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/conditional/ConditionalBeanRouterUnitTest.java similarity index 70% rename from spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/conditional/ConditionalBeanRouterUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/conditional/ConditionalBeanRouterUnitTest.java index bba1f21392..46a5bb5eb9 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/conditional/ConditionalBeanRouterUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/conditional/ConditionalBeanRouterUnitTest.java @@ -1,4 +1,6 @@ -package com.baeldung.camel.conditional; +package com.boot.camel.conditional; + +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; @@ -7,9 +9,13 @@ import org.apache.camel.test.spring.junit5.CamelSpringBootTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; -@SpringBootTest +import com.baeldung.camel.boot.Application; + +@SpringBootTest(classes = Application.class) @CamelSpringBootTest +@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class ConditionalBeanRouterUnitTest { @Autowired @@ -19,6 +25,7 @@ class ConditionalBeanRouterUnitTest { private MockEndpoint mock; @Test + @DirtiesContext void whenSendBodyWithFruit_thenFavouriteHeaderReceivedSuccessfully() throws InterruptedException { mock.expectedHeaderReceived("favourite", "Apples"); diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/conditional/ConditionalBodyRouterUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/conditional/ConditionalBodyRouterUnitTest.java similarity index 70% rename from spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/conditional/ConditionalBodyRouterUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/conditional/ConditionalBodyRouterUnitTest.java index 22c12a741f..745b9993ee 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/conditional/ConditionalBodyRouterUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/conditional/ConditionalBodyRouterUnitTest.java @@ -1,4 +1,6 @@ -package com.baeldung.camel.conditional; +package com.boot.camel.conditional; + +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; @@ -7,9 +9,13 @@ import org.apache.camel.test.spring.junit5.CamelSpringBootTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; -@SpringBootTest +import com.baeldung.camel.boot.Application; + +@SpringBootTest(classes = Application.class) @CamelSpringBootTest +@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class ConditionalBodyRouterUnitTest { @Autowired @@ -19,6 +25,7 @@ class ConditionalBodyRouterUnitTest { private MockEndpoint mock; @Test + @DirtiesContext void whenSendBodyWithBaeldung_thenGoodbyeMessageReceivedSuccessfully() throws InterruptedException { mock.expectedBodiesReceived("Goodbye, Baeldung!"); diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/conditional/ConditionalHeaderRouterUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/conditional/ConditionalHeaderRouterUnitTest.java similarity index 70% rename from spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/conditional/ConditionalHeaderRouterUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/conditional/ConditionalHeaderRouterUnitTest.java index 63fbf6682a..b2803f5682 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/conditional/ConditionalHeaderRouterUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/conditional/ConditionalHeaderRouterUnitTest.java @@ -1,4 +1,6 @@ -package com.baeldung.camel.conditional; +package com.boot.camel.conditional; + +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; @@ -7,9 +9,13 @@ import org.apache.camel.test.spring.junit5.CamelSpringBootTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; -@SpringBootTest +import com.baeldung.camel.boot.Application; + +@SpringBootTest(classes = Application.class) @CamelSpringBootTest +@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class ConditionalHeaderRouterUnitTest { @Autowired @@ -19,6 +25,7 @@ class ConditionalHeaderRouterUnitTest { private MockEndpoint mock; @Test + @DirtiesContext void whenSendBodyWithFruit_thenFavouriteHeaderReceivedSuccessfully() throws InterruptedException { mock.expectedHeaderReceived("favourite", "Banana"); diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/ExceptionHandlingWithDoTryRouteUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/ExceptionHandlingWithDoTryRouteUnitTest.java similarity index 70% rename from spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/ExceptionHandlingWithDoTryRouteUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/ExceptionHandlingWithDoTryRouteUnitTest.java index 23d3b1a392..68deb46883 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/ExceptionHandlingWithDoTryRouteUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/ExceptionHandlingWithDoTryRouteUnitTest.java @@ -1,4 +1,6 @@ -package com.baeldung.camel.exception; +package com.boot.camel.exception; + +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; @@ -7,9 +9,13 @@ import org.apache.camel.test.spring.junit5.CamelSpringBootTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; -@SpringBootTest +import com.baeldung.camel.boot.Application; + +@SpringBootTest(classes = Application.class) @CamelSpringBootTest +@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class ExceptionHandlingWithDoTryRouteUnitTest { @Autowired @@ -19,6 +25,7 @@ class ExceptionHandlingWithDoTryRouteUnitTest { private MockEndpoint mock; @Test + @DirtiesContext void whenSendHeaders_thenExceptionRaisedAndHandledSuccessfully() throws Exception { mock.expectedMessageCount(1); diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/ExceptionHandlingWithExceptionClauseRouteUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/ExceptionHandlingWithExceptionClauseRouteUnitTest.java similarity index 70% rename from spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/ExceptionHandlingWithExceptionClauseRouteUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/ExceptionHandlingWithExceptionClauseRouteUnitTest.java index 28d672bd64..25052f2c10 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/ExceptionHandlingWithExceptionClauseRouteUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/ExceptionHandlingWithExceptionClauseRouteUnitTest.java @@ -1,4 +1,6 @@ -package com.baeldung.camel.exception; +package com.boot.camel.exception; + +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; @@ -7,9 +9,13 @@ import org.apache.camel.test.spring.junit5.CamelSpringBootTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; -@SpringBootTest +import com.baeldung.camel.boot.Application; + +@SpringBootTest(classes = Application.class) @CamelSpringBootTest +@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class ExceptionHandlingWithExceptionClauseRouteUnitTest { @Autowired @@ -19,6 +25,7 @@ class ExceptionHandlingWithExceptionClauseRouteUnitTest { private MockEndpoint mock; @Test + @DirtiesContext void whenSendHeaders_thenExceptionRaisedAndHandledSuccessfully() throws Exception { mock.expectedMessageCount(1); diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/ExceptionThrowingRouteUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/ExceptionThrowingRouteUnitTest.java similarity index 78% rename from spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/ExceptionThrowingRouteUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/ExceptionThrowingRouteUnitTest.java index 6e6944fce8..a547e84a0b 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/ExceptionThrowingRouteUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/ExceptionThrowingRouteUnitTest.java @@ -1,7 +1,8 @@ -package com.baeldung.camel.exception; +package com.boot.camel.exception; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; @@ -11,15 +12,20 @@ import org.apache.camel.test.spring.junit5.CamelSpringBootTest; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; -@SpringBootTest +import com.baeldung.camel.boot.Application; + +@SpringBootTest(classes = Application.class) @CamelSpringBootTest +@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class ExceptionThrowingRouteUnitTest { @Autowired private ProducerTemplate template; @Test + @DirtiesContext void whenSendBody_thenExceptionRaisedSuccessfully() { CamelContext context = template.getCamelContext(); Exchange exchange = context.getEndpoint("direct:start-exception") diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/IllegalArgumentExceptionThrowingProcessorUnitTest.java b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/IllegalArgumentExceptionThrowingProcessorUnitTest.java similarity index 76% rename from spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/IllegalArgumentExceptionThrowingProcessorUnitTest.java rename to messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/IllegalArgumentExceptionThrowingProcessorUnitTest.java index a95abdfd27..9d15f70547 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/camel/exception/IllegalArgumentExceptionThrowingProcessorUnitTest.java +++ b/messaging-modules/spring-apache-camel/src/test/java/com/boot/camel/exception/IllegalArgumentExceptionThrowingProcessorUnitTest.java @@ -1,9 +1,11 @@ -package com.baeldung.camel.exception; +package com.boot.camel.exception; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; +import com.baeldung.camel.boot.exception.IllegalArgumentExceptionThrowingProcessor; + class IllegalArgumentExceptionThrowingProcessorUnitTest { @Test diff --git a/patterns-modules/design-patterns-singleton/src/test/java/com/baeldung/serializable_singleton/EnumSingletonUnitTest.java b/patterns-modules/design-patterns-singleton/src/test/java/com/baeldung/serializable_singleton/EnumSingletonUnitTest.java index e0a098056a..7fdcb20850 100644 --- a/patterns-modules/design-patterns-singleton/src/test/java/com/baeldung/serializable_singleton/EnumSingletonUnitTest.java +++ b/patterns-modules/design-patterns-singleton/src/test/java/com/baeldung/serializable_singleton/EnumSingletonUnitTest.java @@ -1,8 +1,10 @@ package com.baeldung.serializable_singleton; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; @@ -10,8 +12,10 @@ import java.io.ObjectOutputStream; // Unit test for the EnumSingleton class. public class EnumSingletonUnitTest { - - // Checks that when an EnumSingleton instance is serialized + + private static final String ENUM_SINGLETON_TEST_TXT = "enum_singleton_test.txt"; + + // Checks that when an EnumSingleton instance is serialized // and then deserialized, its state is preserved. @Test public void givenEnumSingleton_whenSerializedAndDeserialized_thenStatePreserved() { @@ -19,11 +23,10 @@ public class EnumSingletonUnitTest { es1.setState("State One"); - try ( - FileOutputStream fos = new FileOutputStream("enum_singleton_test.txt"); - ObjectOutputStream oos = new ObjectOutputStream(fos); - FileInputStream fis = new FileInputStream("enum_singleton_test.txt"); - ObjectInputStream ois = new ObjectInputStream(fis)) { + try (FileOutputStream fos = new FileOutputStream(ENUM_SINGLETON_TEST_TXT); + ObjectOutputStream oos = new ObjectOutputStream(fos); + FileInputStream fis = new FileInputStream(ENUM_SINGLETON_TEST_TXT); + ObjectInputStream ois = new ObjectInputStream(fis)) { // Serializing. oos.writeObject(es1); @@ -46,11 +49,10 @@ public class EnumSingletonUnitTest { public void givenEnumSingleton_whenSerializedAndDeserialized_thenOneInstance() { EnumSingleton es1 = EnumSingleton.getInstance(); - try ( - FileOutputStream fos = new FileOutputStream("enum_singleton_test.txt"); - ObjectOutputStream oos = new ObjectOutputStream(fos); - FileInputStream fis = new FileInputStream("enum_singleton_test.txt"); - ObjectInputStream ois = new ObjectInputStream(fis)) { + try (FileOutputStream fos = new FileOutputStream(ENUM_SINGLETON_TEST_TXT); + ObjectOutputStream oos = new ObjectOutputStream(fos); + FileInputStream fis = new FileInputStream(ENUM_SINGLETON_TEST_TXT); + ObjectInputStream ois = new ObjectInputStream(fis)) { // Serializing. oos.writeObject(es1); @@ -66,4 +68,12 @@ public class EnumSingletonUnitTest { System.out.println(e); } } + + @AfterAll + public static void cleanUp() { + final File removeFile = new File(ENUM_SINGLETON_TEST_TXT); + if (removeFile.exists()) { + removeFile.deleteOnExit(); + } + } } diff --git a/patterns-modules/design-patterns-singleton/src/test/java/com/baeldung/serializable_singleton/SingletonUnitTest.java b/patterns-modules/design-patterns-singleton/src/test/java/com/baeldung/serializable_singleton/SingletonUnitTest.java index cc26eb6995..a46288cc8f 100644 --- a/patterns-modules/design-patterns-singleton/src/test/java/com/baeldung/serializable_singleton/SingletonUnitTest.java +++ b/patterns-modules/design-patterns-singleton/src/test/java/com/baeldung/serializable_singleton/SingletonUnitTest.java @@ -1,8 +1,10 @@ package com.baeldung.serializable_singleton; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; @@ -10,8 +12,10 @@ import java.io.ObjectOutputStream; // Unit test for the Singleton class. public class SingletonUnitTest { - - // Checks that when a Singleton instance is serialized + + private static final String SINGLETON_TEST_TXT = "singleton_test.txt"; + + // Checks that when a Singleton instance is serialized // and then deserialized, its state is preserved. @Test public void givenSingleton_whenSerializedAndDeserialized_thenStatePreserved() { @@ -19,11 +23,10 @@ public class SingletonUnitTest { s1.setState("State One"); - try ( - FileOutputStream fos = new FileOutputStream("singleton_test.txt"); - ObjectOutputStream oos = new ObjectOutputStream(fos); - FileInputStream fis = new FileInputStream("singleton_test.txt"); - ObjectInputStream ois = new ObjectInputStream(fis)) { + try (FileOutputStream fos = new FileOutputStream(SINGLETON_TEST_TXT); + ObjectOutputStream oos = new ObjectOutputStream(fos); + FileInputStream fis = new FileInputStream(SINGLETON_TEST_TXT); + ObjectInputStream ois = new ObjectInputStream(fis)) { // Serializing. oos.writeObject(s1); @@ -46,11 +49,10 @@ public class SingletonUnitTest { public void givenSingleton_whenSerializedAndDeserialized_thenTwoInstances() { Singleton s1 = Singleton.getInstance(); - try ( - FileOutputStream fos = new FileOutputStream("singleton_test.txt"); - ObjectOutputStream oos = new ObjectOutputStream(fos); - FileInputStream fis = new FileInputStream("singleton_test.txt"); - ObjectInputStream ois = new ObjectInputStream(fis)) { + try (FileOutputStream fos = new FileOutputStream(SINGLETON_TEST_TXT); + ObjectOutputStream oos = new ObjectOutputStream(fos); + FileInputStream fis = new FileInputStream(SINGLETON_TEST_TXT); + ObjectInputStream ois = new ObjectInputStream(fis)) { // Serializing. oos.writeObject(s1); @@ -65,4 +67,12 @@ public class SingletonUnitTest { System.out.println(e); } } + + @AfterAll + public static void cleanUp() { + final File removeFile = new File(SINGLETON_TEST_TXT); + if (removeFile.exists()) { + removeFile.deleteOnExit(); + } + } } diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/functional/BiFunctionExample.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/functional/BiFunctionExample.java new file mode 100644 index 0000000000..8fedce3943 --- /dev/null +++ b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/functional/BiFunctionExample.java @@ -0,0 +1,17 @@ +package com.baeldung.pipeline.functional; + +import java.util.function.BiFunction; +import java.util.function.Function; + +public class BiFunctionExample { + + public static void main(String[] args) { + BiFunction add = Integer::sum; + BiFunction mul = (a, b) -> a * b; + Function toString = Object::toString; + BiFunction pipeline + = add.andThen(a -> mul.apply(a, 2)).andThen(toString); + String result = pipeline.apply(1, 2); + System.out.println(result); + } +} diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/functional/FunctionExample.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/functional/FunctionExample.java new file mode 100644 index 0000000000..eb393af0ac --- /dev/null +++ b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/functional/FunctionExample.java @@ -0,0 +1,17 @@ +package com.baeldung.pipeline.functional; + +import java.util.function.Function; + +public class FunctionExample { + + public static void main(String[] args) { + Function square = s -> s * s; + Function half = s -> s / 2; + Function toString = Object::toString; + Function pipeline = square.andThen(half) + .andThen(toString); + String result = pipeline.apply(5); + System.out.println(result); + } + +} diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/immutable/Pipe.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/immutable/Pipe.java new file mode 100644 index 0000000000..6fdb4c71c3 --- /dev/null +++ b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/immutable/Pipe.java @@ -0,0 +1,5 @@ +package com.baeldung.pipeline.immutable; + +public interface Pipe { + OUT process(IN input); +} diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/immutable/Pipeline.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/immutable/Pipeline.java new file mode 100644 index 0000000000..db46a26d7e --- /dev/null +++ b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/immutable/Pipeline.java @@ -0,0 +1,37 @@ +package com.baeldung.pipeline.immutable; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; + +public class Pipeline { + + private Collection> pipes; + + private Pipeline(Pipe pipe) { + pipes = Collections.singletonList(pipe); + } + + private Pipeline(Collection> pipes) { + this.pipes = new ArrayList<>(pipes); + } + + public static Pipeline of(Pipe pipe) { + return new Pipeline<>(pipe); + } + + + public Pipeline withNextPipe(Pipe pipe) { + final ArrayList> newPipes = new ArrayList<>(pipes); + newPipes.add(pipe); + return new Pipeline<>(newPipes); + } + + public OUT process(IN input) { + Object output = input; + for (final Pipe pipe : pipes) { + output = pipe.process(output); + } + return (OUT) output; + } +} diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/pipes/Pipe.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/pipes/Pipe.java new file mode 100644 index 0000000000..93f005fdd2 --- /dev/null +++ b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/pipes/Pipe.java @@ -0,0 +1,9 @@ +package com.baeldung.pipeline.pipes; + +public interface Pipe { + OUT process(IN input); + + default Pipe add(Pipe pipe) { + return input -> pipe.process(process(input)); + } +} diff --git a/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/pipeline/PipeUnitTest.java b/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/pipeline/PipeUnitTest.java new file mode 100644 index 0000000000..0e17d87fe2 --- /dev/null +++ b/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/pipeline/PipeUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.pipeline; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.baeldung.pipeline.pipes.Pipe; +import org.junit.jupiter.api.Test; + +class PipeUnitTest { + + @Test + void simplePipeTest() { + Pipe square = s -> s * s; + Pipe half = s -> s / 2; + Pipe toString = Object::toString; + Pipe pipeline = square.add(half).add(toString); + String result = pipeline.process(5); + String expected = "12"; + assertThat(result).isEqualTo(expected); + } +} \ No newline at end of file diff --git a/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/pipeline/PipelineUnitTest.java b/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/pipeline/PipelineUnitTest.java new file mode 100644 index 0000000000..e6ce47f0e8 --- /dev/null +++ b/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/pipeline/PipelineUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.pipeline; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.baeldung.pipeline.immutable.Pipe; +import com.baeldung.pipeline.immutable.Pipeline; +import org.junit.jupiter.api.Test; + +class PipelineUnitTest { + + @Test + void simplePipelineTest() { + Pipe square = s -> s * s; + Pipe half = s -> s / 2; + Pipe toString = Object::toString; + Pipeline squarePipeline = Pipeline.of(square); + Pipeline squareAndHalfPipeline = squarePipeline.withNextPipe(half); + Pipeline squareHalfAndStringPipeline = squareAndHalfPipeline.withNextPipe(toString); + + String result = squareHalfAndStringPipeline.process(5); + String expected = "12"; + assertThat(result).isEqualTo(expected); + } +} \ No newline at end of file diff --git a/patterns-modules/enterprise-patterns/pom.xml b/patterns-modules/enterprise-patterns/pom.xml index 2c59ae2536..0e9edbff67 100644 --- a/patterns-modules/enterprise-patterns/pom.xml +++ b/patterns-modules/enterprise-patterns/pom.xml @@ -65,7 +65,7 @@ 3.7.4 - 2.2.2.RELEASE + 2.7.8 2.17.1 diff --git a/patterns-modules/front-controller/pom.xml b/patterns-modules/front-controller/pom.xml index 84de94cee3..c30a7a666c 100644 --- a/patterns-modules/front-controller/pom.xml +++ b/patterns-modules/front-controller/pom.xml @@ -25,10 +25,12 @@ org.apache.maven.plugins maven-war-plugin + ${maven-war-plugin.version} org.eclipse.jetty jetty-maven-plugin + ${jetty-maven-plugin.version} /front-controller @@ -38,4 +40,9 @@ + + 3.3.2 + 11.0.13 + + \ No newline at end of file diff --git a/patterns-modules/intercepting-filter/pom.xml b/patterns-modules/intercepting-filter/pom.xml index 8028454ee2..cbce56cd6c 100644 --- a/patterns-modules/intercepting-filter/pom.xml +++ b/patterns-modules/intercepting-filter/pom.xml @@ -30,6 +30,7 @@ org.apache.maven.plugins maven-war-plugin + ${maven-war-plugin.version} false @@ -46,4 +47,8 @@ + + 3.3.2 + + \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/README.md b/persistence-modules/hibernate-queries/README.md index f5cba1aa6f..9e6c52d6dc 100644 --- a/persistence-modules/hibernate-queries/README.md +++ b/persistence-modules/hibernate-queries/README.md @@ -12,3 +12,4 @@ This module contains articles about use of Queries in Hibernate. - [Hibernate’s addScalar() Method](https://www.baeldung.com/hibernate-addscalar) - [Distinct Queries in HQL](https://www.baeldung.com/java-hql-distinct) - [JPA and Hibernate – Criteria vs. JPQL vs. HQL Query](https://www.baeldung.com/jpql-hql-criteria-query) +- [Database Keywords as Columns in Hibernate Entities](https://www.baeldung.com/java-hibernate-db-keywords-as-columns) diff --git a/persistence-modules/hibernate-queries/pom.xml b/persistence-modules/hibernate-queries/pom.xml index e530ea2555..68a46b82b1 100644 --- a/persistence-modules/hibernate-queries/pom.xml +++ b/persistence-modules/hibernate-queries/pom.xml @@ -79,6 +79,12 @@ jmh-generator-annprocess ${jmh-generator.version} + + org.testcontainers + mysql + ${testcontainers.mysql.version} + test + @@ -88,6 +94,7 @@ 6.0.6 2.2.3 2.1.214 + 1.17.6 \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/BrokenPhoneOrder.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/BrokenPhoneOrder.java new file mode 100644 index 0000000000..e045005f28 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/BrokenPhoneOrder.java @@ -0,0 +1,39 @@ +package com.baeldung.hibernate.keywords; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "broken_phone_order") +public class BrokenPhoneOrder implements Serializable { + @Id + @Column(name = "order") + String order; + @Column(name = "where") + String where; + + public BrokenPhoneOrder(String order, String where) { + this.order = order; + this.where = where; + } + + public String getOrder() { + return order; + } + + public void setOrder(String order) { + this.order = order; + } + + public String getWhere() { + return where; + } + + public void setWhere(String where) { + this.where = where; + } +} diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/PhoneOrder.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/PhoneOrder.java new file mode 100644 index 0000000000..daee57d553 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/keywords/PhoneOrder.java @@ -0,0 +1,39 @@ +package com.baeldung.hibernate.keywords; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "phone_order") +public class PhoneOrder implements Serializable { + @Id + @Column(name = "`order`") + String order; + @Column(name = "`where`") + String where; + + public PhoneOrder(String order, String where) { + this.order = order; + this.where = where; + } + + public String getOrder() { + return order; + } + + public void setOrder(String order) { + this.order = order; + } + + public String getWhere() { + return where; + } + + public void setWhere(String where) { + this.where = where; + } +} diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/keywords/HibernateKeywordsApplicationIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/keywords/HibernateKeywordsApplicationIntegrationTest.java new file mode 100644 index 0000000000..4282da3de4 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/keywords/HibernateKeywordsApplicationIntegrationTest.java @@ -0,0 +1,58 @@ +package com.baeldung.hibernate.keywords; + +import static java.util.UUID.randomUUID; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +import javax.persistence.PersistenceException; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class HibernateKeywordsApplicationIntegrationTest { + + private static SessionFactory sessionFactory; + private Session session; + + @BeforeAll + static void createSession() { + sessionFactory = new Configuration().addAnnotatedClass(BrokenPhoneOrder.class) + .addAnnotatedClass(PhoneOrder.class) + .configure("keywords/hibernate.keywords.cfg.xml") + .buildSessionFactory(); + } + + @BeforeEach + void before() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @AfterEach + void after() { + session.close(); + } + + @Test + void givenBrokenPhoneOrderWithReservedKeywords_whenNewObjectIsPersisted_thenItFails() { + BrokenPhoneOrder order = new BrokenPhoneOrder(randomUUID().toString(), "My House"); + + assertThatExceptionOfType(PersistenceException.class).isThrownBy(() -> { + session.persist(order); + session.flush(); + }); + } + + @Test + void givenPhoneOrderWithEscapedKeywords_whenNewObjectIsPersisted_thenItSucceeds() { + PhoneOrder order = new PhoneOrder(randomUUID().toString(), "here"); + + session.persist(order); + session.flush(); + } + +} diff --git a/persistence-modules/hibernate-queries/src/test/resources/keywords/hibernate.keywords.cfg.xml b/persistence-modules/hibernate-queries/src/test/resources/keywords/hibernate.keywords.cfg.xml new file mode 100644 index 0000000000..9a1b6bb775 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/resources/keywords/hibernate.keywords.cfg.xml @@ -0,0 +1,14 @@ + + + + + + org.hibernate.dialect.MySQLDialect + jdbc:tc:mysql:5.7.41:///restaurant?TC_INITSCRIPT=keywords/init.sql + org.testcontainers.jdbc.ContainerDatabaseDriver + validate + true + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/test/resources/keywords/init.sql b/persistence-modules/hibernate-queries/src/test/resources/keywords/init.sql new file mode 100644 index 0000000000..4d42a45f5b --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/resources/keywords/init.sql @@ -0,0 +1,9 @@ +CREATE TABLE IF NOT EXISTS phone_order ( + `order` varchar(255) PRIMARY KEY, + `where` varchar(255) +); + +CREATE TABLE IF NOT EXISTS broken_phone_order ( + `order` varchar(255) PRIMARY KEY, + `where` varchar(255) +); \ No newline at end of file diff --git a/persistence-modules/java-mongodb/pom.xml b/persistence-modules/java-mongodb/pom.xml index 2e366d8368..844b9e5bcd 100644 --- a/persistence-modules/java-mongodb/pom.xml +++ b/persistence-modules/java-mongodb/pom.xml @@ -14,20 +14,14 @@ - - de.flapdoodle.embedmongo - de.flapdoodle.embedmongo - ${flapdoodle.version} - test - org.mongodb - mongo-java-driver + mongodb-driver-sync ${mongo.version} dev.morphia.morphia - core + morphia-core ${morphia.version} @@ -42,12 +36,18 @@ ${testcontainers.version} test + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + ${flapdoodle.version} + test + - 3.12.1 - 1.11 - 1.5.3 + 4.8.2 + 4.4.1 + 2.0.0 \ No newline at end of file diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/MongoExample.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/MongoExample.java index 9af1e1f6a4..ef4003fa82 100644 --- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/MongoExample.java +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/MongoExample.java @@ -1,53 +1,64 @@ package com.baeldung; -import com.mongodb.BasicDBObject; -import com.mongodb.DB; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import com.mongodb.MongoClient; +import java.util.ArrayList; + +import org.bson.Document; + +import com.mongodb.client.FindIterable; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoCursor; +import com.mongodb.client.MongoDatabase; public class MongoExample { public static void main(String[] args) { + try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) { - MongoClient mongoClient = new MongoClient("localhost", 27017); + MongoDatabase database = mongoClient.getDatabase("myMongoDb"); - DB database = mongoClient.getDB("myMongoDb"); + // print existing databases + mongoClient.listDatabaseNames().forEach(System.out::println); - // print existing databases - mongoClient.getDatabaseNames().forEach(System.out::println); + boolean collectionExists = mongoClient.getDatabase("myMongoDb").listCollectionNames() + .into(new ArrayList<>()).contains("customers"); + if (!collectionExists) { + database.createCollection("customers"); + } - database.createCollection("customers", null); + // print all collections in customers database + database.listCollectionNames().forEach(System.out::println); - // print all collections in customers database - database.getCollectionNames().forEach(System.out::println); + // create data + MongoCollection collection = database.getCollection("customers"); + Document document = new Document(); + document.put("name", "Shubham"); + document.put("company", "Baeldung"); + collection.insertOne(document); - // create data - DBCollection collection = database.getCollection("customers"); - BasicDBObject document = new BasicDBObject(); - document.put("name", "Shubham"); - document.put("company", "Baeldung"); - collection.insert(document); + // update data + Document query = new Document(); + query.put("name", "Shubham"); + Document newDocument = new Document(); + newDocument.put("name", "John"); + Document updateObject = new Document(); + updateObject.put("$set", newDocument); + collection.updateOne(query, updateObject); - // update data - BasicDBObject query = new BasicDBObject(); - query.put("name", "Shubham"); - BasicDBObject newDocument = new BasicDBObject(); - newDocument.put("name", "John"); - BasicDBObject updateObject = new BasicDBObject(); - updateObject.put("$set", newDocument); - collection.update(query, updateObject); + // read data + Document searchQuery = new Document(); + searchQuery.put("name", "John"); + FindIterable cursor = collection.find(searchQuery); + try (final MongoCursor cursorIterator = cursor.cursor()) { + while (cursorIterator.hasNext()) { + System.out.println(cursorIterator.next()); + } + } - // read data - BasicDBObject searchQuery = new BasicDBObject(); - searchQuery.put("name", "John"); - DBCursor cursor = collection.find(searchQuery); - while (cursor.hasNext()) { - System.out.println(cursor.next()); + // delete data + Document deleteQuery = new Document(); + deleteQuery.put("name", "John"); + collection.deleteOne(deleteQuery); } - - // delete data - BasicDBObject deleteQuery = new BasicDBObject(); - deleteQuery.put("name", "John"); - collection.remove(deleteQuery); } } diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Book.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Book.java index 44e4ecb539..c57f759a95 100644 --- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Book.java +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Book.java @@ -1,11 +1,9 @@ package com.baeldung.bsontojson; -import java.time.LocalDate; import java.time.LocalDateTime; import java.util.HashSet; import java.util.Set; -import dev.morphia.annotations.Embedded; import dev.morphia.annotations.Entity; import dev.morphia.annotations.Field; import dev.morphia.annotations.Id; @@ -25,7 +23,7 @@ public class Book { @Property private String title; private String author; - @Embedded + private Publisher publisher; @Property("price") private double cost; diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/CollectionExistence.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/CollectionExistence.java index 074913af4e..c94a7c042a 100644 --- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/CollectionExistence.java +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/CollectionExistence.java @@ -4,8 +4,8 @@ import java.util.ArrayList; import org.bson.Document; -import com.mongodb.DB; -import com.mongodb.MongoClient; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; @@ -18,7 +18,7 @@ public class CollectionExistence { public static void setUp() { if (mongoClient == null) { - mongoClient = new MongoClient("localhost", 27017); + mongoClient = MongoClients.create("mongodb://localhost:27017"); } databaseName = "baeldung"; testCollectionName = "student"; @@ -26,9 +26,9 @@ public class CollectionExistence { public static void collectionExistsSolution() { - DB db = mongoClient.getDB(databaseName); + MongoDatabase db = mongoClient.getDatabase(databaseName); - System.out.println("collectionName " + testCollectionName + db.collectionExists(testCollectionName)); + System.out.println("collectionName " + testCollectionName + db.listCollectionNames().into(new ArrayList<>()).contains(testCollectionName)); } @@ -62,7 +62,7 @@ public class CollectionExistence { MongoCollection collection = database.getCollection(testCollectionName); - System.out.println(collection.count()); + System.out.println(collection.countDocuments()); } diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/objectid/RetrieveIdExample.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/objectid/RetrieveIdExample.java index 74279bbfcd..5ccabc9326 100644 --- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/objectid/RetrieveIdExample.java +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/objectid/RetrieveIdExample.java @@ -5,7 +5,8 @@ import java.util.Date; import org.bson.Document; import org.bson.types.ObjectId; -import com.mongodb.MongoClient; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; @@ -13,7 +14,7 @@ public class RetrieveIdExample { public static void main(String[] args) { - try ( MongoClient mongoClient = new MongoClient("localhost", 27017) ) { + try ( MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017") ) { MongoDatabase database = mongoClient.getDatabase("myMongoDb"); MongoCollection collection = database.getCollection("example"); diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/MultipleFieldsExample.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/MultipleFieldsExample.java index ebc56cbfd0..9ad62bc1c7 100644 --- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/MultipleFieldsExample.java +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/MultipleFieldsExample.java @@ -3,7 +3,8 @@ package com.baeldung.mongo.update; import org.bson.Document; import com.mongodb.BasicDBObject; -import com.mongodb.MongoClient; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.result.UpdateResult; @@ -16,7 +17,7 @@ public class MultipleFieldsExample { // Connect to cluster (default is localhost:27017) // - MongoClient mongoClient = new MongoClient("localhost", 27017); + MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); MongoDatabase database = mongoClient.getDatabase("baeldung"); MongoCollection collection = database.getCollection("employee"); diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateFields.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateFields.java index a1b051e74c..594d535245 100644 --- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateFields.java +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateFields.java @@ -2,7 +2,8 @@ package com.baeldung.mongo.update; import org.bson.Document; -import com.mongodb.MongoClient; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; @@ -83,10 +84,9 @@ public class UpdateFields { public static void setup() { if (mongoClient == null) { - mongoClient = new MongoClient("localhost", 27017); + mongoClient = MongoClients.create("mongodb://localhost:27017"); database = mongoClient.getDatabase("baeldung"); collection = database.getCollection("student"); - } } diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateMultipleFields.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateMultipleFields.java index 96dd086ed7..08fdce68d6 100644 --- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateMultipleFields.java +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateMultipleFields.java @@ -2,7 +2,8 @@ package com.baeldung.mongo.update; import org.bson.Document; -import com.mongodb.MongoClient; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; @@ -16,19 +17,19 @@ public class UpdateMultipleFields { // // Connect to cluster // + try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27007");) { + MongoDatabase database = mongoClient.getDatabase("baeldung"); + MongoCollection collection = database.getCollection("employee"); - MongoClient mongoClient = new MongoClient("localhost", 27007); - MongoDatabase database = mongoClient.getDatabase("baeldung"); - MongoCollection collection = database.getCollection("employee"); + // + // Update query + // - // - // Update query - // + UpdateResult updateResult = collection.updateMany(Filters.eq("employee_id", 794875), Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager"))); - UpdateResult updateResult = collection.updateMany(Filters.eq("employee_id", 794875), Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager"))); - - System.out.println("updateResult:- " + updateResult); - System.out.println("updateResult:- " + updateResult.getModifiedCount()); + System.out.println("updateResult:- " + updateResult); + System.out.println("updateResult:- " + updateResult.getModifiedCount()); + } } diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java index 4ed2ab8580..b79550dcd1 100644 --- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java @@ -1,6 +1,5 @@ package com.baeldung.morphia.domain; -import java.time.LocalDate; import java.time.LocalDateTime; import java.util.HashSet; import java.util.Set; @@ -25,7 +24,7 @@ public class Book { @Property private String title; private String author; - @Embedded + private Publisher publisher; @Property("price") private double cost; diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/tagging/TagRepository.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/tagging/TagRepository.java index d27d48c743..44b5d461bc 100644 --- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/tagging/TagRepository.java +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/tagging/TagRepository.java @@ -10,8 +10,9 @@ import org.bson.Document; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; -import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; @@ -45,7 +46,7 @@ public class TagRepository implements Closeable { * Instantiates a new TagRepository by opening the DB connection. */ public TagRepository() { - mongoClient = new MongoClient("localhost", 27018); + mongoClient = MongoClients.create("mongodb://localhost:27018"); MongoDatabase database = mongoClient.getDatabase("blog"); collection = database.getCollection("posts"); } diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/AppLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/AppLiveTest.java index 7692a37d03..2abecdbd48 100644 --- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/AppLiveTest.java +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/AppLiveTest.java @@ -2,71 +2,50 @@ package com.baeldung; import static org.junit.Assert.assertEquals; -import org.junit.After; -import org.junit.Before; +import org.bson.Document; import org.junit.Test; -import com.mongodb.BasicDBObject; -import com.mongodb.DB; -import com.mongodb.DBCollection; -import com.mongodb.DBCursor; -import com.mongodb.Mongo; +import com.mongodb.client.FindIterable; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoCursor; +import com.mongodb.client.MongoDatabase; -import de.flapdoodle.embedmongo.MongoDBRuntime; -import de.flapdoodle.embedmongo.MongodExecutable; -import de.flapdoodle.embedmongo.MongodProcess; -import de.flapdoodle.embedmongo.config.MongodConfig; -import de.flapdoodle.embedmongo.distribution.Version; -import de.flapdoodle.embedmongo.runtime.Network; +import de.flapdoodle.embed.mongo.distribution.Version; +import de.flapdoodle.embed.mongo.transitions.Mongod; +import de.flapdoodle.embed.mongo.transitions.RunningMongodProcess; +import de.flapdoodle.reverse.TransitionWalker; public class AppLiveTest { private static final String DB_NAME = "myMongoDb"; - private MongodExecutable mongodExe; - private MongodProcess mongod; - private Mongo mongo; - private DB db; - private DBCollection collection; - - @Before - public void setup() throws Exception { - // Creating Mongodbruntime instance - MongoDBRuntime runtime = MongoDBRuntime.getDefaultInstance(); - - // Creating MongodbExecutable - mongodExe = runtime.prepare(new MongodConfig(Version.V2_0_1, 12345, Network.localhostIsIPv6())); - - // Starting Mongodb - mongod = mongodExe.start(); - mongo = new Mongo("localhost", 12345); - - // Creating DB - db = mongo.getDB(DB_NAME); - - // Creating collection Object and adding values - collection = db.getCollection("customers"); - } - - @After - public void teardown() throws Exception { - mongod.stop(); - mongodExe.cleanup(); - } @Test public void testAddressPersistance() { - BasicDBObject contact = new BasicDBObject(); - contact.put("name", "John"); - contact.put("company", "Baeldung"); + try (TransitionWalker.ReachedState running = Mongod.instance().start(Version.V6_0_3)) { + try (MongoClient mongo = MongoClients.create("mongodb://" + running.current().getServerAddress().getHost() + ":" + running.current().getServerAddress().getPort())) { + // Creating DB + MongoDatabase db = mongo.getDatabase(DB_NAME); - // Inserting document - collection.insert(contact); - DBCursor cursorDoc = collection.find(); - BasicDBObject contact1 = new BasicDBObject(); - while (cursorDoc.hasNext()) { - contact1 = (BasicDBObject) cursorDoc.next(); - System.out.println(contact1); + // Creating collection Object and adding values + MongoCollection collection = db.getCollection("customers"); + + Document contact = new Document(); + contact.put("name", "John"); + contact.put("company", "Baeldung"); + + // Inserting document + collection.insertOne(contact); + FindIterable cursorDoc = collection.find(); + Document contact1 = new Document(); + final MongoCursor cursor = cursorDoc.cursor(); + while (cursor.hasNext()) { + contact1 = cursor.next(); + System.out.println(contact1); + } + assertEquals(contact1.get("name"), "John"); + } } - assertEquals(contact1.get("name"), "John"); } } \ No newline at end of file diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java index 0548119d7a..e2b53436b3 100644 --- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java @@ -1,5 +1,6 @@ package com.baeldung.bsontojson; +import static dev.morphia.query.experimental.filters.Filters.eq; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -14,10 +15,12 @@ import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -import com.mongodb.MongoClient; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; import com.mongodb.client.MongoDatabase; import dev.morphia.Datastore; +import dev.morphia.DeleteOptions; import dev.morphia.Morphia; public class BsonToJsonLiveTest { @@ -27,9 +30,8 @@ public class BsonToJsonLiveTest { @BeforeClass public static void setUp() { - Morphia morphia = new Morphia(); - morphia.mapPackage("com.baeldung.bsontojson"); - datastore = morphia.createDatastore(new MongoClient(), DB_NAME); + datastore = Morphia.createDatastore(MongoClients.create(), DB_NAME); + datastore.getMapper().mapPackage("com.baeldung.bsontojson"); datastore.ensureIndexes(); datastore.save(new Book() @@ -44,25 +46,33 @@ public class BsonToJsonLiveTest { @AfterClass public static void tearDown() { - datastore.delete(datastore.createQuery(Book.class)); + datastore.find(Book.class) + .filter(eq("isbn", "isbn")) + .filter(eq("title", "title")) + .filter(eq("author", "author")) + .filter(eq("cost", "3.95")) + .delete(new DeleteOptions().multi(true)); } @Test public void givenBsonDocument_whenUsingStandardJsonTransformation_thenJsonDateIsObjectEpochTime() { String json; - try (MongoClient mongoClient = new MongoClient()) { + try (MongoClient mongoClient = MongoClients.create()) { MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); Document bson = mongoDatabase.getCollection("Books").find().first(); - json = bson.toJson(); + json = bson.toJson(JsonWriterSettings + .builder() + .dateTimeConverter(new JSONDateFormatEpochTimeConverter()) + .build()); } String expectedJson = "{\"_id\": \"isbn\", " + - "\"className\": \"com.baeldung.bsontojson.Book\", " + + "\"_t\": \"Book\", " + "\"title\": \"title\", " + "\"author\": \"author\", " + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + - "\"name\": \"publisher\"}, " + + "\"_t\": \"Publisher\", \"name\": \"publisher\"}, " + "\"price\": 3.95, " + "\"publishDate\": {\"$date\": 1577898812000}}"; @@ -71,12 +81,11 @@ public class BsonToJsonLiveTest { assertEquals(expectedJson, json); } - @Test public void givenBsonDocument_whenUsingRelaxedJsonTransformation_thenJsonDateIsObjectIsoDate() { String json; - try (MongoClient mongoClient = new MongoClient()) { + try (MongoClient mongoClient = MongoClients.create()) { MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); Document bson = mongoDatabase.getCollection("Books").find().first(); json = bson.toJson(JsonWriterSettings @@ -86,11 +95,11 @@ public class BsonToJsonLiveTest { } String expectedJson = "{\"_id\": \"isbn\", " + - "\"className\": \"com.baeldung.bsontojson.Book\", " + + "\"_t\": \"Book\", " + "\"title\": \"title\", " + "\"author\": \"author\", " + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + - "\"name\": \"publisher\"}, " + + "\"_t\": \"Publisher\", \"name\": \"publisher\"}, " + "\"price\": 3.95, " + "\"publishDate\": {\"$date\": \"2020-01-01T17:13:32Z\"}}"; @@ -103,7 +112,7 @@ public class BsonToJsonLiveTest { public void givenBsonDocument_whenUsingCustomJsonTransformation_thenJsonDateIsStringField() { String json; - try (MongoClient mongoClient = new MongoClient()) { + try (MongoClient mongoClient = MongoClients.create()) { MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); Document bson = mongoDatabase.getCollection("Books").find().first(); json = bson.toJson(JsonWriterSettings @@ -113,11 +122,11 @@ public class BsonToJsonLiveTest { } String expectedJson = "{\"_id\": \"isbn\", " + - "\"className\": \"com.baeldung.bsontojson.Book\", " + + "\"_t\": \"Book\", " + "\"title\": \"title\", " + "\"author\": \"author\", " + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + - "\"name\": \"publisher\"}, " + + "\"_t\": \"Publisher\", \"name\": \"publisher\"}, " + "\"price\": 3.95, " + "\"publishDate\": \"2020-01-01T17:13:32Z\"}"; diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JSONDateFormatEpochTimeConverter.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JSONDateFormatEpochTimeConverter.java new file mode 100644 index 0000000000..7f3a4f936f --- /dev/null +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JSONDateFormatEpochTimeConverter.java @@ -0,0 +1,18 @@ +package com.baeldung.bsontojson; + +import org.bson.json.Converter; +import org.bson.json.StrictJsonWriter; + +/** + * Convertor to epoch time + */ +public class JSONDateFormatEpochTimeConverter implements Converter { + + @Override + public void convert(Long value, StrictJsonWriter writer) { + writer.writeStartObject(); + writer.writeName("$date"); + writer.writeNumber(String.valueOf(value)); + writer.writeEndObject(); + } +} diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/mongo/CollectionExistenceLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/mongo/CollectionExistenceLiveTest.java index ad839d1219..5be97bcb25 100644 --- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/mongo/CollectionExistenceLiveTest.java +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/mongo/CollectionExistenceLiveTest.java @@ -8,8 +8,8 @@ import org.bson.Document; import org.junit.Before; import org.junit.Test; -import com.mongodb.DB; -import com.mongodb.MongoClient; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; @@ -22,7 +22,7 @@ public class CollectionExistenceLiveTest { @Before public void setup() { if (mongoClient == null) { - mongoClient = new MongoClient("localhost", 27017); + mongoClient = MongoClients.create("mongodb://localhost:27017"); databaseName = "baeldung"; testCollectionName = "student"; @@ -58,28 +58,16 @@ public class CollectionExistenceLiveTest { } - @Test - public void givenCollectionExists_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() { - - DB db = mongoClient.getDB(databaseName); - Boolean collectionStatus = db.collectionExists(testCollectionName); - - Boolean expectedStatus = true; - assertEquals(expectedStatus, collectionStatus); - - } - @Test public void givenListCollectionNames_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() { MongoDatabase database = mongoClient.getDatabase(databaseName); boolean collectionExists = database.listCollectionNames() - .into(new ArrayList()) + .into(new ArrayList<>()) .contains(testCollectionName); Boolean expectedStatus = true; assertEquals(expectedStatus, collectionExists); - } @Test @@ -88,7 +76,7 @@ public class CollectionExistenceLiveTest { MongoDatabase database = mongoClient.getDatabase(databaseName); MongoCollection collection = database.getCollection(testCollectionName); - Boolean collectionExists = collection.count() > 0 ? true : false; + Boolean collectionExists = collection.countDocuments() > 0 ? true : false; Boolean expectedStatus = false; assertEquals(expectedStatus, collectionExists); diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java index f508c5f525..d702c691d6 100644 --- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java @@ -2,39 +2,44 @@ package com.baeldung.morphia; import static dev.morphia.aggregation.Group.grouping; import static dev.morphia.aggregation.Group.push; +import static dev.morphia.query.experimental.filters.Filters.eq; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Iterator; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; import org.bson.types.ObjectId; import org.junit.BeforeClass; -import org.junit.Ignore; import org.junit.Test; import com.baeldung.morphia.domain.Author; import com.baeldung.morphia.domain.Book; import com.baeldung.morphia.domain.Publisher; -import com.mongodb.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.model.ReturnDocument; import dev.morphia.Datastore; +import dev.morphia.DeleteOptions; +import dev.morphia.ModifyOptions; import dev.morphia.Morphia; +import dev.morphia.query.FindOptions; import dev.morphia.query.Query; -import dev.morphia.query.UpdateOperations; +import dev.morphia.query.experimental.updates.UpdateOperators; -@Ignore public class MorphiaIntegrationTest { private static Datastore datastore; private static ObjectId id = new ObjectId(); - @BeforeClass + @BeforeClass public static void setUp() { - Morphia morphia = new Morphia(); - morphia.mapPackage("com.baeldung.morphia"); - datastore = morphia.createDatastore(new MongoClient(), "library"); + datastore = Morphia.createDatastore(MongoClients.create(), "library"); + datastore.getMapper().mapPackage("com.baeldung.morphia"); datastore.ensureIndexes(); } @@ -47,11 +52,11 @@ public class MorphiaIntegrationTest { datastore.save(companionBook); datastore.save(book); - List books = datastore.createQuery(Book.class) - .field("title") - .contains("Learning Java") - .find() - .toList(); + Query booksQuery = datastore.find(Book.class) + .filter(eq("title", "Learning Java")); + List books = StreamSupport + .stream(booksQuery.spliterator(), true) + .collect(Collectors.toList()); assertEquals(1, books.size()); assertEquals(book, books.get(0)); } @@ -61,19 +66,13 @@ public class MorphiaIntegrationTest { Publisher publisher = new Publisher(id, "Awsome Publisher"); Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher); datastore.save(book); - Query query = datastore.createQuery(Book.class) - .field("title") - .contains("Learning Java"); - UpdateOperations updates = datastore.createUpdateOperations(Book.class) - .inc("price", 1); - datastore.update(query, updates); - List books = datastore.createQuery(Book.class) - .field("title") - .contains("Learning Java") - .find() - .toList(); - assertEquals(4.95, books.get(0) - .getCost()); + + final Book execute = datastore.find(Book.class) + .filter(eq("title", "Learning Java")) + .modify(UpdateOperators.set("price", 4.95)) + .execute(new ModifyOptions().returnDocument(ReturnDocument.AFTER)); + + assertEquals(4.95, execute.getCost()); } @Test @@ -81,16 +80,12 @@ public class MorphiaIntegrationTest { Publisher publisher = new Publisher(id, "Awsome Publisher"); Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher); datastore.save(book); - Query query = datastore.createQuery(Book.class) - .field("title") - .contains("Learning Java"); - datastore.delete(query); - List books = datastore.createQuery(Book.class) - .field("title") - .contains("Learning Java") - .find() - .toList(); - assertEquals(0, books.size()); + datastore.find(Book.class) + .filter(eq("title", "Learning Java")) + .delete(new DeleteOptions().multi(true)); + Query books = datastore.find(Book.class) + .filter(eq("title", "Learning Java")); + assertFalse(books.iterator().hasNext()); } @Test @@ -107,7 +102,6 @@ public class MorphiaIntegrationTest { .out(Author.class); assertTrue(authors.hasNext()); - } @Test @@ -115,17 +109,12 @@ public class MorphiaIntegrationTest { Publisher publisher = new Publisher(id, "Awsome Publisher"); Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher); datastore.save(book); - List books = datastore.createQuery(Book.class) - .field("title") - .contains("Learning Java") - .project("title", true) - .find() - .toList(); - assertEquals(books.size(), 1); - assertEquals("Learning Java", books.get(0) - .getTitle()); - assertNull(books.get(0) - .getAuthor()); + List books = datastore.find(Book.class) + .filter(eq("title", "Learning Java")) + .iterator(new FindOptions().projection().include("title")).toList(); + assertEquals( 1, books.size()); + assertEquals("Learning Java", books.get(0).getTitle()); + assertNull(books.get(0).getAuthor()); } } diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/tagging/TaggingLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/tagging/TaggingLiveTest.java index edd8e22775..2a7afbd753 100644 --- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/tagging/TaggingLiveTest.java +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/tagging/TaggingLiveTest.java @@ -100,9 +100,7 @@ public class TaggingLiveTest { results.forEach(System.out::println); Assert.assertEquals(1, results.size()); - results.forEach(post -> { - Assert.assertFalse(post.getTags().contains("MongoDB")); - }); + results.forEach(post -> Assert.assertFalse(post.getTags().contains("MongoDB"))); } /** diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateFieldLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateFieldLiveTest.java index 47114e1f1a..ef725a9435 100644 --- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateFieldLiveTest.java +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateFieldLiveTest.java @@ -8,7 +8,8 @@ import org.bson.Document; import org.junit.BeforeClass; import org.junit.Test; -import com.mongodb.MongoClient; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; @@ -27,7 +28,7 @@ public class UpdateFieldLiveTest { @BeforeClass public static void setup() { if (mongoClient == null) { - mongoClient = new MongoClient("localhost", 27017); + mongoClient = MongoClients.create("mongodb://localhost:27017"); db = mongoClient.getDatabase("baeldung"); collection = db.getCollection("student"); diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateMultipleFieldsLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateMultipleFieldsLiveTest.java index d06de23423..19edda5870 100644 --- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateMultipleFieldsLiveTest.java +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateMultipleFieldsLiveTest.java @@ -8,7 +8,8 @@ import org.junit.Before; import org.junit.Test; import com.mongodb.BasicDBObject; -import com.mongodb.MongoClient; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; @@ -23,7 +24,7 @@ public class UpdateMultipleFieldsLiveTest { @Before public void setup() { if (mongoClient == null) { - mongoClient = new MongoClient("localhost", 27017); + mongoClient = MongoClients.create("mongodb://localhost:27017"); db = mongoClient.getDatabase("baeldung"); collection = db.getCollection("employee"); diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 8c191b0abd..9606da4594 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -43,7 +43,8 @@ java-jpa java-jpa-2 java-jpa-3 - java-mongodb + + java-mongodb-2 java-mongodb-3 java-mongodb-queries diff --git a/persistence-modules/rethinkdb/README.md b/persistence-modules/rethinkdb/README.md new file mode 100644 index 0000000000..e8cf1415e7 --- /dev/null +++ b/persistence-modules/rethinkdb/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Getting Started With RethinkDB](https://www.baeldung.com/rethinkdb) diff --git a/persistence-modules/spring-data-cassandra-2/README.md b/persistence-modules/spring-data-cassandra-2/README.md index f5cf20b8a9..3f49d6ae93 100644 --- a/persistence-modules/spring-data-cassandra-2/README.md +++ b/persistence-modules/spring-data-cassandra-2/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Using Test Containers With Spring Data Cassandra](https://www.baeldung.com/spring-data-cassandra-test-containers) +- [Cassandra – Object Mapping with DataStax Java Driver](https://www.baeldung.com/cassandra-object-mapping-datastax-java-driver) diff --git a/persistence-modules/spring-data-cassandra-2/pom.xml b/persistence-modules/spring-data-cassandra-2/pom.xml index 1e6412dc17..740c04d2a0 100644 --- a/persistence-modules/spring-data-cassandra-2/pom.xml +++ b/persistence-modules/spring-data-cassandra-2/pom.xml @@ -60,8 +60,32 @@ ${system.stubs.version} test + + com.datastax.oss + java-driver-mapper-runtime + 4.15.0 + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + + + com.datastax.oss + java-driver-mapper-processor + 4.15.0 + + + + + + + 11 3.1.11 diff --git a/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/CassandraMapperApplication.java b/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/CassandraMapperApplication.java new file mode 100644 index 0000000000..da66ee1401 --- /dev/null +++ b/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/CassandraMapperApplication.java @@ -0,0 +1,12 @@ +package org.baeldung.objectmapper; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CassandraMapperApplication { + + public static void main(String[] args) { + SpringApplication.run(CassandraMapperApplication.class, args); + } +} diff --git a/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/DaoMapper.java b/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/DaoMapper.java new file mode 100644 index 0000000000..f7e937702d --- /dev/null +++ b/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/DaoMapper.java @@ -0,0 +1,18 @@ +package org.baeldung.objectmapper; + +import com.datastax.oss.driver.api.core.CqlIdentifier; +import com.datastax.oss.driver.api.mapper.annotations.DaoFactory; +import com.datastax.oss.driver.api.mapper.annotations.DaoKeyspace; +import com.datastax.oss.driver.api.mapper.annotations.Mapper; +import org.baeldung.objectmapper.dao.CounterDao; +import org.baeldung.objectmapper.dao.UserDao; + +@Mapper +public interface DaoMapper { + + @DaoFactory + UserDao getUserDao(@DaoKeyspace CqlIdentifier keyspace); + + @DaoFactory + CounterDao getUserCounterDao(@DaoKeyspace CqlIdentifier keyspace); +} \ No newline at end of file diff --git a/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/dao/CounterDao.java b/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/dao/CounterDao.java new file mode 100644 index 0000000000..71978ce116 --- /dev/null +++ b/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/dao/CounterDao.java @@ -0,0 +1,16 @@ +package org.baeldung.objectmapper.dao; + +import com.datastax.oss.driver.api.mapper.annotations.Dao; +import com.datastax.oss.driver.api.mapper.annotations.Increment; +import com.datastax.oss.driver.api.mapper.annotations.Select; +import org.baeldung.objectmapper.entity.Counter; + +@Dao +public interface CounterDao { + + @Increment(entityClass = Counter.class) + void incrementCounter(String id, long count); + + @Select + Counter getCounterById(String id); +} diff --git a/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/dao/UserDao.java b/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/dao/UserDao.java new file mode 100644 index 0000000000..9e06066c1e --- /dev/null +++ b/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/dao/UserDao.java @@ -0,0 +1,38 @@ +package org.baeldung.objectmapper.dao; + +import com.datastax.oss.driver.api.core.PagingIterable; +import com.datastax.oss.driver.api.core.cql.BoundStatement; +import com.datastax.oss.driver.api.core.cql.Row; +import com.datastax.oss.driver.api.mapper.annotations.*; +import org.baeldung.objectmapper.entity.User; + +@Dao +public interface UserDao { + + @Insert + void insertUser(User user); + + @Select + User getUserById(int id); + + @Select + PagingIterable getAllUsers(); + + @Update + void updateUser(User user); + + @Delete + void deleteUser(User user); + + @GetEntity + User getUser(Row row); + + @SetEntity + BoundStatement setUser(BoundStatement udtValue, User user); + + @Query(value = "select * from user_profile where user_age > :userAge ALLOW FILTERING") + PagingIterable getUsersOlderThanAge(int userAge); + + @QueryProvider(providerClass = UserQueryProvider.class, entityHelpers = User.class, providerMethod = "getUsersOlderThanAge") + PagingIterable getUsersOlderThan(String age); +} diff --git a/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/dao/UserQueryProvider.java b/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/dao/UserQueryProvider.java new file mode 100644 index 0000000000..10c56a9310 --- /dev/null +++ b/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/dao/UserQueryProvider.java @@ -0,0 +1,34 @@ +package org.baeldung.objectmapper.dao; + +import com.datastax.oss.driver.api.core.CqlSession; +import com.datastax.oss.driver.api.core.PagingIterable; +import com.datastax.oss.driver.api.core.cql.PreparedStatement; +import com.datastax.oss.driver.api.core.cql.SimpleStatement; +import com.datastax.oss.driver.api.mapper.MapperContext; +import com.datastax.oss.driver.api.mapper.entity.EntityHelper; +import com.datastax.oss.driver.api.querybuilder.QueryBuilder; +import org.baeldung.objectmapper.entity.User; + +public class UserQueryProvider { + + private final CqlSession session; + private final EntityHelper userHelper; + + public UserQueryProvider(MapperContext context, EntityHelper userHelper) { + this.session = context.getSession(); + this.userHelper = userHelper; + } + + public PagingIterable getUsersOlderThanAge(String age) { + SimpleStatement statement = QueryBuilder.selectFrom("user_profile") + .all() + .whereColumn("user_age") + .isGreaterThan(QueryBuilder + .bindMarker(age)) + .build(); + PreparedStatement preparedSelectUser = session.prepare(statement); + return session + .execute(preparedSelectUser.getQuery()) + .map(result -> userHelper.get(result, true)); + } +} diff --git a/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/entity/Admin.java b/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/entity/Admin.java new file mode 100644 index 0000000000..afd6b74490 --- /dev/null +++ b/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/entity/Admin.java @@ -0,0 +1,31 @@ +package org.baeldung.objectmapper.entity; + +import com.datastax.oss.driver.api.mapper.annotations.CqlName; +import com.datastax.oss.driver.api.mapper.annotations.Entity; +import com.datastax.oss.driver.api.mapper.annotations.HierarchyScanStrategy; + +@Entity +@CqlName("admin_profile") +@HierarchyScanStrategy(highestAncestor = User.class, includeHighestAncestor = true) +public class Admin extends User { + private String role; + private String department; + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public String getDepartment() { + return department; + } + + public void setDepartment(String department) { + this.department = department; + } + +} + diff --git a/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/entity/Counter.java b/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/entity/Counter.java new file mode 100644 index 0000000000..88b49b561e --- /dev/null +++ b/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/entity/Counter.java @@ -0,0 +1,29 @@ +package org.baeldung.objectmapper.entity; + +import com.datastax.oss.driver.api.mapper.annotations.Entity; +import com.datastax.oss.driver.api.mapper.annotations.PartitionKey; + +@Entity +public class Counter { + + @PartitionKey + private String id; + private long count; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public long getCount() { + return count; + } + + public void setCount(long count) { + this.count = count; + } + +} diff --git a/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/entity/User.java b/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/entity/User.java new file mode 100644 index 0000000000..31612ffe73 --- /dev/null +++ b/persistence-modules/spring-data-cassandra-2/src/main/java/org/baeldung/objectmapper/entity/User.java @@ -0,0 +1,58 @@ +package org.baeldung.objectmapper.entity; + +import com.datastax.oss.driver.api.mapper.annotations.*; + +@Entity +@CqlName("user_profile") +public class User { + @PartitionKey + private int id; + @CqlName("username") + private String userName; + @ClusteringColumn + private int userAge; + + @Computed("writetime(userName)") + private long writetime; + + public User() { + } + + public User(int id, String userName, int userAge) { + this.id = id; + this.userName = userName; + this.userAge = userAge; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public int getUserAge() { + return userAge; + } + + public void setUserAge(int userAge) { + this.userAge = userAge; + } + + public long getWritetime() { + return writetime; + } + + public void setWritetime(long writetime) { + this.writetime = writetime; + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/objectmapper/MapperLiveTest.java b/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/objectmapper/MapperLiveTest.java new file mode 100644 index 0000000000..b61663d622 --- /dev/null +++ b/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/objectmapper/MapperLiveTest.java @@ -0,0 +1,96 @@ +package org.baeldung.objectmapper; + +import com.datastax.oss.driver.api.core.CqlIdentifier; +import com.datastax.oss.driver.api.core.CqlSession; +import org.baeldung.objectmapper.dao.CounterDao; +import org.baeldung.objectmapper.dao.UserDao; +import org.baeldung.objectmapper.entity.Counter; +import org.baeldung.objectmapper.entity.User; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.testcontainers.containers.CassandraContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +import java.util.List; + +@Testcontainers +@SpringBootTest +public class MapperLiveTest { + + private static final String KEYSPACE_NAME = "baeldung"; + + @Container + private static final CassandraContainer cassandra = (CassandraContainer) new CassandraContainer("cassandra:3.11.2") + .withExposedPorts(9042); + + static void setupCassandraConnectionProperties() { + System.setProperty("spring.data.cassandra.keyspace-name", KEYSPACE_NAME); + System.setProperty("spring.data.cassandra.contact-points", cassandra.getContainerIpAddress()); + System.setProperty("spring.data.cassandra.port", String.valueOf(cassandra.getMappedPort(9042))); + } + + static UserDao userDao; + static CounterDao counterDao; + + @BeforeAll + static void setup() { + setupCassandraConnectionProperties(); + CqlSession session = CqlSession.builder().build(); + + String createKeyspace = "CREATE KEYSPACE IF NOT EXISTS baeldung " + + "WITH replication = {'class':'SimpleStrategy', 'replication_factor':1};"; + String useKeyspace = "USE baeldung;"; + String createUserTable = "CREATE TABLE IF NOT EXISTS user_profile " + + "(id int, username text, user_age int, writetime bigint, PRIMARY KEY (id, user_age)) " + + "WITH CLUSTERING ORDER BY (user_age DESC);"; + String createAdminTable = "CREATE TABLE IF NOT EXISTS admin_profile " + + "(id int, username text, user_age int, role text, writetime bigint, department text, " + + "PRIMARY KEY (id, user_age)) " + + "WITH CLUSTERING ORDER BY (user_age DESC);"; + String createCounter = "CREATE TABLE IF NOT EXISTS counter " + + "(id text, count counter, PRIMARY KEY (id));"; + + session.execute(createKeyspace); + session.execute(useKeyspace); + session.execute(createUserTable); + session.execute(createAdminTable); + session.execute(createCounter); + + DaoMapper mapper = new DaoMapperBuilder(session).build(); + userDao = mapper.getUserDao(CqlIdentifier.fromCql("baeldung")); + counterDao = mapper.getUserCounterDao(CqlIdentifier.fromCql("baeldung")); + } + + @Test + void givenUser_whenInsert_thenRetrievedDuringGet() { + User user = new User(1, "JohnDoe", 31); + userDao.insertUser(user); + User retrievedUser = userDao.getUserById(1); + Assertions.assertEquals(retrievedUser.getUserName(), user.getUserName()); + } + + @Test + void givenCounter_whenIncrement_thenIncremented() { + Counter users = counterDao.getCounterById("users"); + long initialCount = users != null ? users.getCount(): 0; + + counterDao.incrementCounter("users", 1); + + users = counterDao.getCounterById("users"); + long finalCount = users != null ? users.getCount(): 0; + + Assertions.assertEquals(finalCount - initialCount, 1); + } + + @Test + void givenUser_whenGetUsersOlderThan_thenRetrieved() { + User user = new User(2, "JaneDoe", 20); + userDao.insertUser(user); + List retrievedUsers = userDao.getUsersOlderThanAge(30).all(); + Assertions.assertEquals(retrievedUsers.size(), 1); + } + +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index 8b395d44f1..651ed36d1a 100644 --- a/pom.xml +++ b/pom.xml @@ -330,29 +330,24 @@ parent-spring-5 parent-java - apache-cxf-modules - apache-libraries azure checker-plugin - core-groovy-modules core-java-modules - couchbase - custom-pmd - drools + couchbase + gradle-modules/gradle/maven-to-gradle - guava-modules apache-httpclient - httpclient4 + apache-httpclient4 jackson-modules @@ -364,25 +359,20 @@ jaxb jersey jhipster-5 - jmeter + jmh jsf - json-modules kubernetes-modules language-interop - libraries-2 libraries-3 - libraries-data - libraries-data-db libraries-security libraries-server-2 - libraries-testing logging-modules lombok-modules @@ -399,18 +389,10 @@ osgi orika - patterns-modules performance-tests persistence-modules - - quarkus-modules - - rule-engines-modules - rxjava-modules - - reactive-systems security-modules vavr-modules @@ -459,17 +441,13 @@ parent-spring-5 parent-java - saas-modules - server-modules spf4j spring-4 spring-aop - spring-aop-2 spring-batch spring-bom spring-boot-modules spring-boot-rest - spring-caching spring-cloud-modules spring-core @@ -599,28 +577,21 @@ parent-spring-5 parent-java - apache-cxf-modules - apache-libraries azure checker-plugin - core-groovy-modules core-java-modules couchbase - custom-pmd - drools gradle-modules/gradle/maven-to-gradle - - guava-modules apache-httpclient - httpclient4 + apache-httpclient4 jackson-modules @@ -632,25 +603,21 @@ jaxb jersey jhipster-5 - jmeter jmh jsf - json-modules kubernetes-modules language-interop - libraries-2 libraries-3 - libraries-data + libraries-data-db libraries-security libraries-server-2 - libraries-testing logging-modules lombok-modules @@ -661,24 +628,15 @@ microservices-modules muleesb - netflix-modules osgi orika - patterns-modules performance-tests persistence-modules - - quarkus-modules - - rule-engines-modules - rxjava-modules - - reactive-systems security-modules vavr-modules @@ -719,17 +677,13 @@ parent-spring-5 parent-java - saas-modules - server-modules + spf4j spring-4 - spring-aop - spring-aop-2 spring-batch spring-bom spring-boot-modules spring-boot-rest - spring-caching spring-cloud-modules spring-core @@ -879,12 +833,28 @@ + patterns-modules + json-modules + libraries-data + saas-modules + server-modules + apache-cxf-modules + + spring-aop + jmeter + spring-aop-2 + algorithms-modules + apache-libraries apache-poi apache-velocity di-modules asciidoctor aws-modules + + couchbase + core-groovy-modules + core-java-modules/core-java-9 core-java-modules/core-java-9-improvements core-java-modules/core-java-9-jigsaw @@ -922,24 +892,26 @@ core-java-modules/core-java-networking-3 core-java-modules/core-java-strings core-java-modules/core-java-httpclient + custom-pmd spring-core-6 data-structures ddd-contexts deeplearning4j docker-modules + drools + guava-modules apache-httpclient-2 kubernetes-modules/kubernetes-spring libraries-concurrency + libraries-testing maven-modules/compiler-plugin-java-9 maven-modules/maven-generate-war maven-modules/multimodulemavenproject optaplanner persistence-modules/sirix persistence-modules/spring-data-cassandra-2 - quarkus-modules/quarkus-vs-springboot - quarkus-modules/quarkus-jandex + quarkus-modules spring-boot-modules/spring-boot-cassandre - spring-boot-modules/spring-boot-camel spring-boot-modules/spring-boot-3 spring-boot-modules/spring-boot-3-native spring-boot-modules/spring-boot-3-observation @@ -948,6 +920,12 @@ spring-swagger-codegen/custom-validations-opeanpi-codegen testing-modules/testing-assertions persistence-modules/fauna + + rule-engines-modules + + reactive-systems + rxjava-modules + lightrun tablesaw geotools @@ -971,7 +949,7 @@ asm atomikos atomix - axon + bazel code-generation @@ -1001,6 +979,7 @@ java-native jsoup ksqldb + libraries-2 libraries-7 libraries-apache-commons libraries-apache-commons-collections @@ -1035,7 +1014,7 @@ spring-5-webflux-2 spring-activiti spring-batch-2 - spring-caching-2 + spring-boot-modules/spring-caching-2 spring-core-2 spring-core-3 spring-core-5 @@ -1055,12 +1034,15 @@ tensorflow-java xstream webrtc + persistence-modules/java-mongodb + messaging-modules/spring-apache-camel UTF-8 11 - 11 + 11 + 11 @@ -1087,13 +1069,23 @@ + patterns-modules + json-modules + libraries-data + saas-modules + server-modules + apache-cxf-modules algorithms-modules + apache-libraries apache-poi apache-velocity di-modules asciidoctor aws-modules + couchbase + + core-groovy-modules core-java-modules/core-java-9 core-java-modules/core-java-9-improvements core-java-modules/core-java-9-jigsaw @@ -1131,24 +1123,29 @@ core-java-modules/core-java-networking-3 core-java-modules/core-java-strings core-java-modules/core-java-httpclient + spring-aop + spring-aop-2 + custom-pmd spring-core-6 data-structures ddd-contexts deeplearning4j + jmeter docker-modules + drools + guava-modules apache-httpclient-2 kubernetes-modules/kubernetes-spring libraries-concurrency + libraries-testing maven-modules/compiler-plugin-java-9 maven-modules/maven-generate-war maven-modules/multimodulemavenproject optaplanner persistence-modules/sirix persistence-modules/spring-data-cassandra-2 - quarkus-modules/quarkus-vs-springboot - quarkus-modules/quarkus-jandex + quarkus-modules spring-boot-modules/spring-boot-cassandre - spring-boot-modules/spring-boot-camel spring-boot-modules/spring-boot-3 spring-boot-modules/spring-boot-3-native spring-boot-modules/spring-boot-3-observation @@ -1157,6 +1154,12 @@ spring-swagger-codegen/custom-validations-opeanpi-codegen testing-modules/testing-assertions persistence-modules/fauna + + rule-engines-modules + + reactive-systems + rxjava-modules + lightrun tablesaw geotools @@ -1179,7 +1182,7 @@ asm atomikos atomix - axon + bazel code-generation @@ -1247,7 +1250,7 @@ spring-5-webflux-2 spring-activiti spring-batch-2 - spring-caching-2 + spring-boot-modules/spring-caching-2 spring-core-2 spring-core-3 spring-core-5 @@ -1267,12 +1270,16 @@ tensorflow-java xstream webrtc + persistence-modules/java-mongodb + libraries-2 + messaging-modules/spring-apache-camel UTF-8 11 - 11 + 11 + 11 @@ -1343,8 +1350,8 @@ 1.2 2.13.3 1.4 - 1.8.1 - 5.8.1 + 1.9.2 + 5.9.2 1.3.2 0.3.1 2.5.2 diff --git a/quarkus-modules/pom.xml b/quarkus-modules/pom.xml index 94fe1ae10f..ab9f7c3906 100644 --- a/quarkus-modules/pom.xml +++ b/quarkus-modules/pom.xml @@ -16,7 +16,8 @@ quarkus quarkus-extension - + quarkus-jandex + quarkus-vs-springboot \ No newline at end of file diff --git a/quarkus-modules/quarkus/pom.xml b/quarkus-modules/quarkus/pom.xml index 3e1cbff01c..99d18579c3 100644 --- a/quarkus-modules/quarkus/pom.xml +++ b/quarkus-modules/quarkus/pom.xml @@ -182,7 +182,7 @@ - 1.7.0.Final + 2.16.3.Final 3.3.0 diff --git a/rule-engines-modules/easy-rules/pom.xml b/rule-engines-modules/easy-rules/pom.xml index c8e875944c..6f43307e89 100644 --- a/rule-engines-modules/easy-rules/pom.xml +++ b/rule-engines-modules/easy-rules/pom.xml @@ -23,7 +23,7 @@ - 3.0.0 + 4.1.0 \ No newline at end of file diff --git a/rule-engines-modules/evrete/pom.xml b/rule-engines-modules/evrete/pom.xml index d94da2853f..5b7f195722 100644 --- a/rule-engines-modules/evrete/pom.xml +++ b/rule-engines-modules/evrete/pom.xml @@ -30,7 +30,7 @@ - 2.1.04 + 3.0.01 \ No newline at end of file diff --git a/rule-engines-modules/openl-tablets/pom.xml b/rule-engines-modules/openl-tablets/pom.xml index 204efce6c5..a24e06c44d 100644 --- a/rule-engines-modules/openl-tablets/pom.xml +++ b/rule-engines-modules/openl-tablets/pom.xml @@ -28,7 +28,7 @@ - 5.19.4 + 5.26.5 \ No newline at end of file diff --git a/rule-engines-modules/rulebook/pom.xml b/rule-engines-modules/rulebook/pom.xml index 55e312289e..88feb148e2 100644 --- a/rule-engines-modules/rulebook/pom.xml +++ b/rule-engines-modules/rulebook/pom.xml @@ -23,7 +23,7 @@ - 0.6.2 + 0.12 \ No newline at end of file diff --git a/rxjava-modules/pom.xml b/rxjava-modules/pom.xml index cd46270d92..2f2597b644 100644 --- a/rxjava-modules/pom.xml +++ b/rxjava-modules/pom.xml @@ -17,6 +17,7 @@ rxjava-core + rxjava-core-2 rxjava-libraries rxjava-observables rxjava-operators diff --git a/rxjava-modules/rxjava-core-2/src/test/java/com/baeldung/rxjava/justvscallable/SingleJustVsFromCallableTest.java b/rxjava-modules/rxjava-core-2/src/test/java/com/baeldung/rxjava/justvscallable/SingleJustVsFromCallableTest.java index d0de86fed8..a693432343 100644 --- a/rxjava-modules/rxjava-core-2/src/test/java/com/baeldung/rxjava/justvscallable/SingleJustVsFromCallableTest.java +++ b/rxjava-modules/rxjava-core-2/src/test/java/com/baeldung/rxjava/justvscallable/SingleJustVsFromCallableTest.java @@ -12,7 +12,7 @@ import org.mockito.Mockito; import rx.Single; import rx.observers.TestSubscriber; -class SingleJustVsFromCallableTest { +class SingleJustVsFromCallableUnitTest { public EmployeeRepository repository = mock(EmployeeRepository.class); diff --git a/saas-modules/sentry-servlet/pom.xml b/saas-modules/sentry-servlet/pom.xml index c86fcbce03..2e4f95b5fb 100644 --- a/saas-modules/sentry-servlet/pom.xml +++ b/saas-modules/sentry-servlet/pom.xml @@ -15,6 +15,7 @@ 6.11.0 1.10.4 + 3.3.2 diff --git a/saas-modules/sentry-servlet/src/main/java/com/baeldung/sentry/support/SentryFilter.java b/saas-modules/sentry-servlet/src/main/java/com/baeldung/sentry/support/SentryFilter.java index e853368ad9..51055f321d 100644 --- a/saas-modules/sentry-servlet/src/main/java/com/baeldung/sentry/support/SentryFilter.java +++ b/saas-modules/sentry-servlet/src/main/java/com/baeldung/sentry/support/SentryFilter.java @@ -21,7 +21,7 @@ public class SentryFilter implements Filter { try { chain.doFilter(request, response); int rc = ((HttpServletResponse) response).getStatus(); - if (rc/100 == 5) { + if (rc / 100 == 5) { Sentry.captureMessage("Application error: code=" + rc, SentryLevel.ERROR); } } catch (Throwable t) { diff --git a/saas-modules/sentry-servlet/src/main/resources/sentry.properties b/saas-modules/sentry-servlet/src/main/resources/sentry.properties index c937874420..cd8b3005dd 100644 --- a/saas-modules/sentry-servlet/src/main/resources/sentry.properties +++ b/saas-modules/sentry-servlet/src/main/resources/sentry.properties @@ -1,3 +1,3 @@ # Sentry configuration file -# put your DSN here -dsn=https://xxxxxxxxxxxxxxxx@zzzzzzz.ingest.sentry.io/wwww \ No newline at end of file +# put your own DSN here. This one is NOT valid !!! +dsn=https://c295098aadd04f719f1c9f50d801f93e@o75061.ingest.sentry.io/4504455033978880 \ No newline at end of file diff --git a/server-modules/wildfly/pom.xml b/server-modules/wildfly/pom.xml index eaec4d176c..af742c7bd3 100644 --- a/server-modules/wildfly/pom.xml +++ b/server-modules/wildfly/pom.xml @@ -13,7 +13,7 @@ com.baeldung parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2 + ../../parent-boot-2 @@ -63,6 +63,7 @@ org.apache.maven.plugins maven-war-plugin + ${maven-war-plugin.version} @@ -74,4 +75,8 @@ + + 3.3.2 + + \ No newline at end of file diff --git a/spring-aop-2/pom.xml b/spring-aop-2/pom.xml index 76e4780e72..cb84ed4ca2 100644 --- a/spring-aop-2/pom.xml +++ b/spring-aop-2/pom.xml @@ -39,8 +39,22 @@ + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + + + + - 1.11 + 1.14.0 + 3.3.2 \ No newline at end of file diff --git a/spring-aop/pom.xml b/spring-aop/pom.xml index 0d48c479ca..ae5ab5fce1 100644 --- a/spring-aop/pom.xml +++ b/spring-aop/pom.xml @@ -69,11 +69,20 @@ + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + false + + - 1.11 + 1.14.0 + 3.3.2 \ No newline at end of file diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 3ed9eea431..7fdfac4b93 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -84,6 +84,7 @@ spring-boot-data-2 spring-boot-validation spring-boot-data-3 + spring-caching diff --git a/spring-boot-modules/spring-boot-camel/.gitignore b/spring-boot-modules/spring-boot-camel/.gitignore deleted file mode 100644 index 16be8f2193..0000000000 --- a/spring-boot-modules/spring-boot-camel/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/output/ diff --git a/spring-boot-modules/spring-boot-camel/README.md b/spring-boot-modules/spring-boot-camel/README.md deleted file mode 100644 index d797f1a0b5..0000000000 --- a/spring-boot-modules/spring-boot-camel/README.md +++ /dev/null @@ -1,30 +0,0 @@ -## Spring Boot Camel - -This module contains articles about Spring Boot with Apache Camel - -### Example for the Article on Camel API with SpringBoot - -To start, run: - -`mvn spring-boot:run` - -Then, make a POST http request to: - -`http://localhost:8080/camel/api/bean` - -Include the HEADER: Content-Type: application/json, - -and a BODY Payload like: - -`{"id": 1,"name": "World"}` - -We will get a return code of 201 and the response: `Hello, World` - if the transform() method from Application class is uncommented and the process() method is commented - -or return code of 201 and the response: `{"id": 10,"name": "Hello, World"}` - if the transform() method from Application class is commented and the process() method is uncommented - -## Relevant articles: - -- [Apache Camel with Spring Boot](https://www.baeldung.com/apache-camel-spring-boot) -- [Apache Camel Routes Testing in Spring Boot](https://www.baeldung.com/spring-boot-apache-camel-routes-testing) -- [Apache Camel Conditional Routing](https://www.baeldung.com/spring-apache-camel-conditional-routing) -- [Apache Camel Exception Handling](https://www.baeldung.com/java-apache-camel-exception-handling) diff --git a/spring-boot-modules/spring-boot-camel/pom.xml b/spring-boot-modules/spring-boot-camel/pom.xml deleted file mode 100644 index ecf7143808..0000000000 --- a/spring-boot-modules/spring-boot-camel/pom.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - 4.0.0 - com.example - spring-boot-camel - 0.0.1-SNAPSHOT - spring-boot-camel - - - com.baeldung.spring-boot-modules - spring-boot-modules - 1.0.0-SNAPSHOT - - - - - org.apache.camel.springboot - camel-servlet-starter - ${camel.version} - - - org.apache.camel.springboot - camel-jackson-starter - ${camel.version} - - - org.apache.camel.springboot - camel-swagger-java-starter - ${camel.version} - - - org.apache.camel.springboot - camel-spring-boot-starter - ${camel.version} - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-test - test - - - org.apache.camel - camel-test-spring-junit5 - ${camel.version} - test - - - - - spring-boot:run - - - org.springframework.boot - spring-boot-maven-plugin - - - - repackage - - - com.baeldung.camel.boot.testing.GreetingsFileSpringApplication - - - - - - - - - 11 - 3.15.0 - - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-camel/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-camel/src/main/resources/logback.xml deleted file mode 100644 index d0b4334f5a..0000000000 --- a/spring-boot-modules/spring-boot-camel/src/main/resources/logback.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - diff --git a/spring-boot-modules/spring-boot-keycloak-2/pom.xml b/spring-boot-modules/spring-boot-keycloak-2/pom.xml index a119a09561..8b1eec2e4e 100644 --- a/spring-boot-modules/spring-boot-keycloak-2/pom.xml +++ b/spring-boot-modules/spring-boot-keycloak-2/pom.xml @@ -17,18 +17,6 @@ ../../parent-boot-2 - - - - org.keycloak.bom - keycloak-adapter-bom - ${keycloak-adapter-bom.version} - pom - import - - - - org.springframework.boot @@ -39,8 +27,12 @@ spring-boot-starter-security - org.keycloak - keycloak-spring-boot-starter + org.springframework.boot + spring-boot-starter-oauth2-resource-server + + + org.springframework.boot + spring-boot-starter-oauth2-client org.springframework.boot @@ -58,8 +50,4 @@ - - 15.0.2 - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-keycloak-2/src/main/java/com/baeldung/disablingkeycloak/KeycloakConfiguration.java b/spring-boot-modules/spring-boot-keycloak-2/src/main/java/com/baeldung/disablingkeycloak/KeycloakConfiguration.java deleted file mode 100644 index a9a2ea6a18..0000000000 --- a/spring-boot-modules/spring-boot-keycloak-2/src/main/java/com/baeldung/disablingkeycloak/KeycloakConfiguration.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.disablingkeycloak; - -import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class KeycloakConfiguration { - - @Bean - public KeycloakSpringBootConfigResolver keycloakConfigResolver() { - return new KeycloakSpringBootConfigResolver(); - } -} diff --git a/spring-boot-modules/spring-boot-keycloak-2/src/main/java/com/baeldung/disablingkeycloak/KeycloakSecurityConfig.java b/spring-boot-modules/spring-boot-keycloak-2/src/main/java/com/baeldung/disablingkeycloak/KeycloakSecurityConfig.java index d48c99d8fd..b41b64077c 100644 --- a/spring-boot-modules/spring-boot-keycloak-2/src/main/java/com/baeldung/disablingkeycloak/KeycloakSecurityConfig.java +++ b/spring-boot-modules/spring-boot-keycloak-2/src/main/java/com/baeldung/disablingkeycloak/KeycloakSecurityConfig.java @@ -1,38 +1,34 @@ package com.baeldung.disablingkeycloak; -import org.keycloak.adapters.springsecurity.KeycloakConfiguration; -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.web.builders.HttpSecurity; -import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy; +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; import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; -@KeycloakConfiguration +@Configuration +@EnableWebSecurity @ConditionalOnProperty(name = "keycloak.enabled", havingValue = "true", matchIfMissing = true) -public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter { +public class KeycloakSecurityConfig { - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) { - auth.authenticationProvider(keycloakAuthenticationProvider()); + @Bean + protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { + return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl()); } @Bean - @Override - protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { - return new NullAuthenticatedSessionStrategy(); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - super.configure(http); - + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.csrf() .disable() - .authorizeRequests() - .anyRequest() - .authenticated(); + .authorizeHttpRequests(auth -> auth.anyRequest() + .authenticated()); + http.oauth2Login(); + http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); + return http.build(); } } diff --git a/spring-boot-modules/spring-boot-keycloak-2/src/main/resources/application-disabling-keycloak.properties b/spring-boot-modules/spring-boot-keycloak-2/src/main/resources/application-disabling-keycloak.properties deleted file mode 100644 index 21263cf725..0000000000 --- a/spring-boot-modules/spring-boot-keycloak-2/src/main/resources/application-disabling-keycloak.properties +++ /dev/null @@ -1,7 +0,0 @@ -# Keycloak authentication is enabled for production. -keycloak.enabled=true -keycloak.realm=SpringBootKeycloak -keycloak.auth-server-url=http://localhost:8180/auth -keycloak.resource=login-app -keycloak.bearer-only=true -keycloak.ssl-required=external diff --git a/spring-boot-modules/spring-boot-keycloak-2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-keycloak-2/src/main/resources/application.properties new file mode 100644 index 0000000000..1f08eac234 --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak-2/src/main/resources/application.properties @@ -0,0 +1,10 @@ +server.port=8081 +keycloak.enabled=true + +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: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-logging-log4j2/pom.xml b/spring-boot-modules/spring-boot-logging-log4j2/pom.xml index b2a6975964..b429339417 100644 --- a/spring-boot-modules/spring-boot-logging-log4j2/pom.xml +++ b/spring-boot-modules/spring-boot-logging-log4j2/pom.xml @@ -8,34 +8,13 @@ jar Demo project for Spring Boot Logging with Log4J2 - - org.springframework.boot - spring-boot-starter-parent - 2.2.2.RELEASE - + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 - - - - - - - junit - junit - ${junit.version} - - - org.junit - junit-bom - ${junit-jupiter.version} - pom - import - - - - org.springframework.boot @@ -62,7 +41,6 @@ org.projectlombok lombok - ${lombok.version} provided @@ -96,10 +74,6 @@ com.baeldung.springbootlogging.SpringBootLoggingApplication 1.3.8.RELEASE 1.1.16 - 1.18.24 - - 4.13.2 - 5.8.1 2.17.1 diff --git a/spring-boot-modules/spring-boot-swagger-2/README.md b/spring-boot-modules/spring-boot-swagger-2/README.md index 242f3d3385..e5ec236801 100644 --- a/spring-boot-modules/spring-boot-swagger-2/README.md +++ b/spring-boot-modules/spring-boot-swagger-2/README.md @@ -2,4 +2,5 @@ - [Swagger: Specify Two Responses with the Same Response Code](https://www.baeldung.com/swagger-two-responses-one-response-code) - [Specify an Array of Strings as Body Parameters in Swagger](https://www.baeldung.com/swagger-body-array-of-strings) -- [Swagger @ApiParam vs @ApiModelProperty](https://www.baeldung.com/swagger-apiparam-vs-apimodelproperty) \ No newline at end of file +- [Swagger @ApiParam vs @ApiModelProperty](https://www.baeldung.com/swagger-apiparam-vs-apimodelproperty) +- [Map Date Types With OpenAPI Generator](https://www.baeldung.com/openapi-map-date-types) diff --git a/spring-caching-2/README.md b/spring-boot-modules/spring-caching-2/README.md similarity index 100% rename from spring-caching-2/README.md rename to spring-boot-modules/spring-caching-2/README.md diff --git a/spring-caching-2/pom.xml b/spring-boot-modules/spring-caching-2/pom.xml similarity index 91% rename from spring-caching-2/pom.xml rename to spring-boot-modules/spring-caching-2/pom.xml index 0a07820fc4..6e33e42d2b 100644 --- a/spring-caching-2/pom.xml +++ b/spring-boot-modules/spring-caching-2/pom.xml @@ -9,10 +9,9 @@ jar - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2/pom.xml + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/redis/CacheConfig.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/CacheConfig.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/redis/CacheConfig.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/CacheConfig.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/redis/Item.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/Item.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/redis/Item.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/Item.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemController.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemController.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemController.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemController.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemRepository.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemRepository.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemRepository.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemRepository.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemService.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemService.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemService.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/ItemService.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/redis/RedisCacheApplication.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/CachingTTLApplication.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/CachingTTLApplication.java old mode 100755 new mode 100644 similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/CachingTTLApplication.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/CachingTTLApplication.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/config/SpringCachingConfig.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/config/SpringCachingConfig.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/config/SpringCachingConfig.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/config/SpringCachingConfig.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java old mode 100755 new mode 100644 similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/controller/HotelController.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ControllerAdvisor.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ControllerAdvisor.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ControllerAdvisor.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ControllerAdvisor.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ElementNotFoundException.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ElementNotFoundException.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ElementNotFoundException.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/exception/ElementNotFoundException.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/City.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/City.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/City.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/City.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/Hotel.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/Hotel.java old mode 100755 new mode 100644 similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/Hotel.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/model/Hotel.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/CityRepository.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/CityRepository.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/CityRepository.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/CityRepository.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java old mode 100755 new mode 100644 similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/repository/HotelRepository.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/HotelService.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/HotelService.java old mode 100755 new mode 100644 similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/HotelService.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/HotelService.java diff --git a/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/SpringCacheCustomizer.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/SpringCacheCustomizer.java similarity index 100% rename from spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/SpringCacheCustomizer.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/ttl/service/SpringCacheCustomizer.java diff --git a/spring-caching-2/src/main/resources/application.properties b/spring-boot-modules/spring-caching-2/src/main/resources/application.properties similarity index 100% rename from spring-caching-2/src/main/resources/application.properties rename to spring-boot-modules/spring-caching-2/src/main/resources/application.properties diff --git a/spring-caching-2/src/main/resources/data.sql b/spring-boot-modules/spring-caching-2/src/main/resources/data.sql similarity index 100% rename from spring-caching-2/src/main/resources/data.sql rename to spring-boot-modules/spring-caching-2/src/main/resources/data.sql diff --git a/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java similarity index 100% rename from spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java rename to spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java diff --git a/spring-caching-2/src/test/java/com/baeldung/caching/ttl/HotelControllerIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/ttl/HotelControllerIntegrationTest.java similarity index 100% rename from spring-caching-2/src/test/java/com/baeldung/caching/ttl/HotelControllerIntegrationTest.java rename to spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/ttl/HotelControllerIntegrationTest.java diff --git a/spring-caching-2/src/test/java/com/baeldung/caching/ttl/SlowTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/ttl/SlowTest.java similarity index 100% rename from spring-caching-2/src/test/java/com/baeldung/caching/ttl/SlowTest.java rename to spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/ttl/SlowTest.java diff --git a/spring-caching-2/src/test/resources/application.properties b/spring-boot-modules/spring-caching-2/src/test/resources/application.properties similarity index 100% rename from spring-caching-2/src/test/resources/application.properties rename to spring-boot-modules/spring-caching-2/src/test/resources/application.properties diff --git a/spring-caching/README.md b/spring-boot-modules/spring-caching/README.md similarity index 100% rename from spring-caching/README.md rename to spring-boot-modules/spring-caching/README.md diff --git a/spring-caching/pom.xml b/spring-boot-modules/spring-caching/pom.xml similarity index 93% rename from spring-caching/pom.xml rename to spring-boot-modules/spring-caching/pom.xml index 34c035a8ec..c0318729af 100644 --- a/spring-caching/pom.xml +++ b/spring-boot-modules/spring-caching/pom.xml @@ -8,11 +8,10 @@ spring-caching war - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 + + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT diff --git a/spring-caching/src/main/java/com/baeldung/cachetest/Application.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/Application.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/cachetest/Application.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/Application.java diff --git a/spring-caching/src/main/java/com/baeldung/cachetest/config/CacheConfig.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/config/CacheConfig.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/cachetest/config/CacheConfig.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/config/CacheConfig.java diff --git a/spring-caching/src/main/java/com/baeldung/cachetest/config/CacheEventLogger.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/config/CacheEventLogger.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/cachetest/config/CacheEventLogger.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/config/CacheEventLogger.java diff --git a/spring-caching/src/main/java/com/baeldung/cachetest/rest/NumberController.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/rest/NumberController.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/cachetest/rest/NumberController.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/rest/NumberController.java diff --git a/spring-caching/src/main/java/com/baeldung/cachetest/service/NumberService.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/service/NumberService.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/cachetest/service/NumberService.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/cachetest/service/NumberService.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/config/ApplicationCacheConfig.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/config/ApplicationCacheConfig.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/config/ApplicationCacheConfig.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/config/ApplicationCacheConfig.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/config/CachingConfig.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/config/CachingConfig.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/config/CachingConfig.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/config/CachingConfig.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/config/CustomKeyGenerator.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/config/CustomKeyGenerator.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/config/CustomKeyGenerator.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/config/CustomKeyGenerator.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/eviction/controllers/CachingController.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/eviction/controllers/CachingController.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/eviction/controllers/CachingController.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/eviction/controllers/CachingController.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/eviction/service/CachingService.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/eviction/service/CachingService.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/eviction/service/CachingService.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/eviction/service/CachingService.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/example/AbstractService.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/AbstractService.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/example/AbstractService.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/AbstractService.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/example/BookService.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/BookService.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/example/BookService.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/BookService.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/example/Customer.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/Customer.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/example/Customer.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/Customer.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/example/CustomerDataService.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/CustomerDataService.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/example/CustomerDataService.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/CustomerDataService.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/example/CustomerServiceWithParent.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/CustomerServiceWithParent.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/example/CustomerServiceWithParent.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/example/CustomerServiceWithParent.java diff --git a/spring-caching/src/main/java/com/baeldung/caching/model/Book.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/model/Book.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/caching/model/Book.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/caching/model/Book.java diff --git a/spring-caching/src/main/java/com/baeldung/ehcache/calculator/SquaredCalculator.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/ehcache/calculator/SquaredCalculator.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/ehcache/calculator/SquaredCalculator.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/ehcache/calculator/SquaredCalculator.java diff --git a/spring-caching/src/main/java/com/baeldung/ehcache/config/CacheHelper.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/ehcache/config/CacheHelper.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/ehcache/config/CacheHelper.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/ehcache/config/CacheHelper.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/CustomerDetailBO.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/CustomerDetailBO.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/CustomerDetailBO.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/CustomerDetailBO.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/OrderDetailBO.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/OrderDetailBO.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/OrderDetailBO.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/bo/OrderDetailBO.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheManagerConfig.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheManagerConfig.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheManagerConfig.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheManagerConfig.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheResolver.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheResolver.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheResolver.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/config/MultipleCacheResolver.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/controller/MultipleCacheManagerController.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/controller/MultipleCacheManagerController.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/controller/MultipleCacheManagerController.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/controller/MultipleCacheManagerController.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Customer.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Customer.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Customer.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Customer.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Item.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Item.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Item.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Item.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Order.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Order.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Order.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/entity/Order.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/CustomerDetailRepository.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/CustomerDetailRepository.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/CustomerDetailRepository.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/CustomerDetailRepository.java diff --git a/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/OrderDetailRepository.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/OrderDetailRepository.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/OrderDetailRepository.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/multiplecachemanager/repository/OrderDetailRepository.java diff --git a/spring-caching/src/main/java/com/baeldung/springdatacaching/model/Book.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/springdatacaching/model/Book.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/springdatacaching/model/Book.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/springdatacaching/model/Book.java diff --git a/spring-caching/src/main/java/com/baeldung/springdatacaching/repositories/BookRepository.java b/spring-boot-modules/spring-caching/src/main/java/com/baeldung/springdatacaching/repositories/BookRepository.java similarity index 100% rename from spring-caching/src/main/java/com/baeldung/springdatacaching/repositories/BookRepository.java rename to spring-boot-modules/spring-caching/src/main/java/com/baeldung/springdatacaching/repositories/BookRepository.java diff --git a/spring-caching/src/main/resources/application.properties b/spring-boot-modules/spring-caching/src/main/resources/application.properties similarity index 100% rename from spring-caching/src/main/resources/application.properties rename to spring-boot-modules/spring-caching/src/main/resources/application.properties diff --git a/spring-caching/src/main/resources/config.xml b/spring-boot-modules/spring-caching/src/main/resources/config.xml similarity index 100% rename from spring-caching/src/main/resources/config.xml rename to spring-boot-modules/spring-caching/src/main/resources/config.xml diff --git a/spring-caching/src/main/resources/data.sql b/spring-boot-modules/spring-caching/src/main/resources/data.sql similarity index 100% rename from spring-caching/src/main/resources/data.sql rename to spring-boot-modules/spring-caching/src/main/resources/data.sql diff --git a/spring-caching/src/main/resources/ehcache.xml b/spring-boot-modules/spring-caching/src/main/resources/ehcache.xml similarity index 100% rename from spring-caching/src/main/resources/ehcache.xml rename to spring-boot-modules/spring-caching/src/main/resources/ehcache.xml diff --git a/spring-caching/src/main/resources/logback.xml b/spring-boot-modules/spring-caching/src/main/resources/logback.xml similarity index 100% rename from spring-caching/src/main/resources/logback.xml rename to spring-boot-modules/spring-caching/src/main/resources/logback.xml diff --git a/spring-caching/src/main/resources/schema.sql b/spring-boot-modules/spring-caching/src/main/resources/schema.sql similarity index 100% rename from spring-caching/src/main/resources/schema.sql rename to spring-boot-modules/spring-caching/src/main/resources/schema.sql diff --git a/spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java b/spring-boot-modules/spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java similarity index 100% rename from spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java rename to spring-boot-modules/spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java diff --git a/spring-caching/src/test/java/com/baeldung/caching/test/CacheEvictAnnotationIntegrationTest.java b/spring-boot-modules/spring-caching/src/test/java/com/baeldung/caching/test/CacheEvictAnnotationIntegrationTest.java similarity index 100% rename from spring-caching/src/test/java/com/baeldung/caching/test/CacheEvictAnnotationIntegrationTest.java rename to spring-boot-modules/spring-caching/src/test/java/com/baeldung/caching/test/CacheEvictAnnotationIntegrationTest.java diff --git a/spring-caching/src/test/java/com/baeldung/caching/test/CacheManagerEvictIntegrationTest.java b/spring-boot-modules/spring-caching/src/test/java/com/baeldung/caching/test/CacheManagerEvictIntegrationTest.java similarity index 100% rename from spring-caching/src/test/java/com/baeldung/caching/test/CacheManagerEvictIntegrationTest.java rename to spring-boot-modules/spring-caching/src/test/java/com/baeldung/caching/test/CacheManagerEvictIntegrationTest.java diff --git a/spring-caching/src/test/java/com/baeldung/caching/test/SpringCachingIntegrationTest.java b/spring-boot-modules/spring-caching/src/test/java/com/baeldung/caching/test/SpringCachingIntegrationTest.java similarity index 100% rename from spring-caching/src/test/java/com/baeldung/caching/test/SpringCachingIntegrationTest.java rename to spring-boot-modules/spring-caching/src/test/java/com/baeldung/caching/test/SpringCachingIntegrationTest.java diff --git a/spring-caching/src/test/java/com/baeldung/ehcache/SquareCalculatorUnitTest.java b/spring-boot-modules/spring-caching/src/test/java/com/baeldung/ehcache/SquareCalculatorUnitTest.java similarity index 100% rename from spring-caching/src/test/java/com/baeldung/ehcache/SquareCalculatorUnitTest.java rename to spring-boot-modules/spring-caching/src/test/java/com/baeldung/ehcache/SquareCalculatorUnitTest.java diff --git a/spring-caching/src/test/java/com/baeldung/multiplecachemanager/MultipleCacheManagerIntegrationTest.java b/spring-boot-modules/spring-caching/src/test/java/com/baeldung/multiplecachemanager/MultipleCacheManagerIntegrationTest.java similarity index 100% rename from spring-caching/src/test/java/com/baeldung/multiplecachemanager/MultipleCacheManagerIntegrationTest.java rename to spring-boot-modules/spring-caching/src/test/java/com/baeldung/multiplecachemanager/MultipleCacheManagerIntegrationTest.java diff --git a/spring-caching/src/test/java/com/baeldung/springdatacaching/repositories/BookRepositoryCachingIntegrationTest.java b/spring-boot-modules/spring-caching/src/test/java/com/baeldung/springdatacaching/repositories/BookRepositoryCachingIntegrationTest.java similarity index 100% rename from spring-caching/src/test/java/com/baeldung/springdatacaching/repositories/BookRepositoryCachingIntegrationTest.java rename to spring-boot-modules/spring-caching/src/test/java/com/baeldung/springdatacaching/repositories/BookRepositoryCachingIntegrationTest.java diff --git a/spring-caching/src/test/java/com/baeldung/springdatacaching/repositories/BookRepositoryIntegrationTest.java b/spring-boot-modules/spring-caching/src/test/java/com/baeldung/springdatacaching/repositories/BookRepositoryIntegrationTest.java similarity index 100% rename from spring-caching/src/test/java/com/baeldung/springdatacaching/repositories/BookRepositoryIntegrationTest.java rename to spring-boot-modules/spring-caching/src/test/java/com/baeldung/springdatacaching/repositories/BookRepositoryIntegrationTest.java diff --git a/spring-cloud-modules/pom.xml b/spring-cloud-modules/pom.xml index 43e2687d74..68c7d45b7c 100644 --- a/spring-cloud-modules/pom.xml +++ b/spring-cloud-modules/pom.xml @@ -54,8 +54,7 @@ spring-cloud-bus spring-cloud-data-flow spring-cloud-sleuth - spring-cloud-openfeign-2 - spring-cloud-open-telemetry + spring-cloud-open-telemetry diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/README.md b/spring-cloud-modules/spring-cloud-openfeign-2/README.md deleted file mode 100644 index bc306e2302..0000000000 --- a/spring-cloud-modules/spring-cloud-openfeign-2/README.md +++ /dev/null @@ -1,4 +0,0 @@ - -### Relevant Articles: - -- [Feign Client Exception Handling](https://www.baeldung.com/java-feign-client-exception-handling) diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/pom.xml b/spring-cloud-modules/spring-cloud-openfeign-2/pom.xml deleted file mode 100644 index 43cc7c6c50..0000000000 --- a/spring-cloud-modules/spring-cloud-openfeign-2/pom.xml +++ /dev/null @@ -1,64 +0,0 @@ - - - 4.0.0 - com.baeldung.cloud - spring-cloud-openfeign-2 - spring-cloud-openfeign-2 - OpenFeign project for Spring Boot - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - - org.springframework.cloud - spring-cloud-dependencies - ${spring-cloud.version} - pom - import - - - - - - - org.springframework.cloud - spring-cloud-starter-openfeign - - - io.github.openfeign - feign-okhttp - - - org.springframework.boot - spring-boot-starter-web - - - io.github.openfeign.form - feign-form - ${feign-form.version} - - - io.github.openfeign.form - feign-form-spring - - - org.springframework.boot - spring-boot-starter-test - test - - - - - 2021.0.3 - 3.8.0 - - - \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/resources/application.properties b/spring-cloud-modules/spring-cloud-openfeign-2/src/main/resources/application.properties deleted file mode 100644 index 7188b74c9b..0000000000 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/resources/application.properties +++ /dev/null @@ -1,10 +0,0 @@ -server.port=8085 -spring.main.allow-bean-definition-overriding=true -spring.application.name= openfeign -logging.level.com.baeldung.cloud.openfeign.client: DEBUG -feign.hystrix.enabled=true - -spring.security.oauth2.client.registration.keycloak.authorization-grant-type=client_credentials -spring.security.oauth2.client.registration.keycloak.client-id=payment-app -spring.security.oauth2.client.registration.keycloak.client-secret=863e9de4-33d4-4471-b35e-f8d2434385bb -spring.security.oauth2.client.provider.keycloak.token-uri=http://localhost:8083/auth/realms/master/protocol/openid-connect/token diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/test/java/com/baeldung/cloud/openfeign/SpringContextTest.java b/spring-cloud-modules/spring-cloud-openfeign-2/src/test/java/com/baeldung/cloud/openfeign/SpringContextTest.java deleted file mode 100644 index 4bf35f74f4..0000000000 --- a/spring-cloud-modules/spring-cloud-openfeign-2/src/test/java/com/baeldung/cloud/openfeign/SpringContextTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.cloud.openfeign; - - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ExampleApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud-modules/spring-cloud-openfeign/README.md b/spring-cloud-modules/spring-cloud-openfeign/README.md index 421fa0284f..62434b35b8 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/README.md +++ b/spring-cloud-modules/spring-cloud-openfeign/README.md @@ -2,9 +2,6 @@ - [Introduction to Spring Cloud OpenFeign](https://www.baeldung.com/spring-cloud-openfeign) - [Differences Between Netflix Feign and OpenFeign](https://www.baeldung.com/netflix-feign-vs-openfeign) -- [File Upload With Open Feign](https://www.baeldung.com/java-feign-file-upload) -- [Feign Logging Configuration](https://www.baeldung.com/java-feign-logging) - [Provide an OAuth2 Token to a Feign Client](https://www.baeldung.com/spring-cloud-feign-oauth-token) -- [Retrieve Original Message From Feign ErrorDecoder](https://www.baeldung.com/feign-retrieve-original-message) -- [RequestLine with Feign Client](https://www.baeldung.com/feign-requestline) - [Propagating Exceptions With OpenFeign and Spring](https://www.baeldung.com/spring-openfeign-propagate-exception) +- [Feign Client Exception Handling](https://www.baeldung.com/java-feign-client-exception-handling) diff --git a/spring-cloud-modules/spring-cloud-openfeign/pom.xml b/spring-cloud-modules/spring-cloud-openfeign/pom.xml index 570cb6a082..88ad38517b 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/pom.xml +++ b/spring-cloud-modules/spring-cloud-openfeign/pom.xml @@ -61,12 +61,6 @@ spring-boot-starter-test test - - com.github.tomakehurst - wiremock-jre8 - 2.33.2 - test - diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/UserClient.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/UserClient.java deleted file mode 100644 index 9416bd30f0..0000000000 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/client/UserClient.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.cloud.openfeign.client; - -import com.baeldung.cloud.openfeign.config.FeignConfig; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -@FeignClient(name = "user-client", url="https://jsonplaceholder.typicode.com", configuration = FeignConfig.class) -public interface UserClient { - - @RequestMapping(value = "/users", method = RequestMethod.GET) - String getUsers(); -} \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/RetreiveMessageErrorDecoder.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/RetreiveMessageErrorDecoder.java index 09bf8bf54b..5ebd7b6887 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/RetreiveMessageErrorDecoder.java +++ b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/config/RetreiveMessageErrorDecoder.java @@ -12,7 +12,6 @@ import feign.codec.ErrorDecoder; public class RetreiveMessageErrorDecoder implements ErrorDecoder { private final ErrorDecoder errorDecoder = new Default(); - @Override public Exception decode(String methodKey, Response response) { ExceptionMessage message = null; diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientFallbackFactory.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientFallbackFactory.java similarity index 100% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientFallbackFactory.java rename to spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientFallbackFactory.java diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallBack.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallBack.java similarity index 100% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallBack.java rename to spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallBack.java diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallbackFactory.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallbackFactory.java similarity index 100% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallbackFactory.java rename to spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallbackFactory.java diff --git a/spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallbackImpl.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallbackImpl.java similarity index 100% rename from spring-cloud-modules/spring-cloud-openfeign-2/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallbackImpl.java rename to spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/FileUploadClientWithFallbackImpl.java diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadResource.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadResource.java index 26e658a7f0..2d5090897d 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadResource.java +++ b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadResource.java @@ -9,7 +9,7 @@ import feign.Response; public interface UploadResource { - @RequestLine("POST /upload-file") + @RequestLine("POST /upload-error") @Headers("Content-Type: multipart/form-data") Response uploadFile(@Param("file") MultipartFile file); diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadService.java b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadService.java index c0d1962a71..244a5a2168 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadService.java +++ b/spring-cloud-modules/spring-cloud-openfeign/src/main/java/com/baeldung/cloud/openfeign/fileupload/service/UploadService.java @@ -13,20 +13,22 @@ public class UploadService { private static final String HTTP_FILE_UPLOAD_URL = "http://localhost:8081"; @Autowired - private UploadClient client; - + private FileUploadClientWithFallbackFactory fileUploadClient; + @Autowired + private FileUploadClientWithFallBack fileUploadClientWithFallback; + public boolean uploadFileWithManualClient(MultipartFile file) { UploadResource fileUploadResource = Feign.builder().encoder(new SpringFormEncoder()) .target(UploadResource.class, HTTP_FILE_UPLOAD_URL); Response response = fileUploadResource.uploadFile(file); return response.status() == 200; } - - public String uploadFile(MultipartFile file) { - return client.fileUpload(file); + + public String uploadFileWithFallbackFactory(MultipartFile file) { + return fileUploadClient.fileUpload(file); } - - public String uploadFileError(MultipartFile file) { - return client.fileUpload(file); + + public String uploadFileWithFallback(MultipartFile file) { + return fileUploadClientWithFallback.fileUpload(file); } } \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignFileUploadLiveTest.java b/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignFileUploadLiveTest.java index f558e07491..6396be2453 100644 --- a/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignFileUploadLiveTest.java +++ b/spring-cloud-modules/spring-cloud-openfeign/src/test/java/com/baeldung/cloud/openfeign/OpenFeignFileUploadLiveTest.java @@ -14,6 +14,7 @@ import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.multipart.MultipartFile; +import com.baeldung.cloud.openfeign.exception.NotFoundException; import com.baeldung.cloud.openfeign.fileupload.service.UploadService; @RunWith(SpringRunner.class) @@ -25,26 +26,36 @@ public class OpenFeignFileUploadLiveTest { private static String FILE_NAME = "fileupload.txt"; - @Test - public void whenFeignBuilder_thenFileUploadSuccess() throws IOException { + @Test(expected = NotFoundException.class) + public void whenFileUploadClientFallbackFactory_thenFileUploadError() throws IOException { ClassLoader classloader = Thread.currentThread().getContextClassLoader(); File file = new File(classloader.getResource(FILE_NAME).getFile()); Assert.assertTrue(file.exists()); FileInputStream input = new FileInputStream(file); MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input)); - Assert.assertTrue(uploadService.uploadFileWithManualClient(multipartFile)); + uploadService.uploadFileWithFallbackFactory(multipartFile); + } + + @Test(expected = NotFoundException.class) + public void whenFileUploadClientFallback_thenFileUploadError() throws IOException { + ClassLoader classloader = Thread.currentThread().getContextClassLoader(); + File file = new File(classloader.getResource(FILE_NAME).getFile()); + Assert.assertTrue(file.exists()); + FileInputStream input = new FileInputStream(file); + MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", + IOUtils.toByteArray(input)); + uploadService.uploadFileWithFallback(multipartFile); } - @Test - public void whenAnnotatedFeignClient_thenFileUploadSuccess() throws IOException { + @Test(expected = NotFoundException.class) + public void whenFileUploadWithMannualClient_thenFileUploadError() throws IOException { ClassLoader classloader = Thread.currentThread().getContextClassLoader(); File file = new File(classloader.getResource(FILE_NAME).getFile()); Assert.assertTrue(file.exists()); FileInputStream input = new FileInputStream(file); MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input)); - String uploadFile = uploadService.uploadFile(multipartFile); - Assert.assertNotNull(uploadFile); + uploadService.uploadFileWithManualClient(multipartFile); } } diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index d51c2e300f..7b0bb0a8b7 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 @@ -61,8 +61,24 @@ awaitility test + + org.apache.commons + commons-lang3 + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.spring.kafka.KafkaApplication + + + + + 1.16.2 diff --git a/spring-kafka/src/main/java/com/baeldung/countingmessages/KafkaCountingMessagesComponent.java b/spring-kafka/src/main/java/com/baeldung/countingmessages/KafkaCountingMessagesComponent.java index 89cd1c8dac..f76be95c1c 100644 --- a/spring-kafka/src/main/java/com/baeldung/countingmessages/KafkaCountingMessagesComponent.java +++ b/spring-kafka/src/main/java/com/baeldung/countingmessages/KafkaCountingMessagesComponent.java @@ -6,7 +6,7 @@ import org.apache.kafka.common.serialization.StringDeserializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import java.util.Collections; import java.util.HashMap; import java.util.List; diff --git a/spring-kafka/src/main/java/com/baeldung/kafka/ssl/KafkaProducer.java b/spring-kafka/src/main/java/com/baeldung/kafka/ssl/KafkaProducer.java index 895d437c6b..38ce366355 100644 --- a/spring-kafka/src/main/java/com/baeldung/kafka/ssl/KafkaProducer.java +++ b/spring-kafka/src/main/java/com/baeldung/kafka/ssl/KafkaProducer.java @@ -15,9 +15,12 @@ public class KafkaProducer { public void sendMessage(String message, String topic) { log.info("Producing message: {}", message); kafkaTemplate.send(topic, "key", message) - .addCallback( - result -> log.info("Message sent to topic: {}", message), - ex -> log.error("Failed to send message", ex) - ); + .whenComplete((result, ex) -> { + if (ex == null) { + log.info("Message sent to topic: {}", message); + } else { + log.error("Failed to send message", ex); + } + }); } } diff --git a/spring-kafka/src/main/java/com/baeldung/kafka/streams/KafkaProducer.java b/spring-kafka/src/main/java/com/baeldung/kafka/streams/KafkaProducer.java index 2b8e9bbfbd..664758a052 100644 --- a/spring-kafka/src/main/java/com/baeldung/kafka/streams/KafkaProducer.java +++ b/spring-kafka/src/main/java/com/baeldung/kafka/streams/KafkaProducer.java @@ -15,9 +15,12 @@ public class KafkaProducer { public void sendMessage(String message) { kafkaTemplate.send("input-topic", message) - .addCallback( - result -> log.info("Message sent to topic: {}", message), - ex -> log.error("Failed to send message", ex) - ); + .whenComplete((result, ex) -> { + if (ex == null) { + log.info("Message sent to topic: {}", message); + } else { + log.error("Failed to send message", ex); + } + }); } } diff --git a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java index 9b79f716e9..ff2d21668f 100644 --- a/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java +++ b/spring-kafka/src/main/java/com/baeldung/spring/kafka/KafkaApplication.java @@ -1,5 +1,6 @@ package com.baeldung.spring.kafka; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -16,8 +17,6 @@ import org.springframework.kafka.support.KafkaHeaders; import org.springframework.kafka.support.SendResult; import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.Payload; -import org.springframework.util.concurrent.ListenableFuture; -import org.springframework.util.concurrent.ListenableFutureCallback; @SpringBootApplication public class KafkaApplication { @@ -102,18 +101,13 @@ public class KafkaApplication { public void sendMessage(String message) { - ListenableFuture> future = kafkaTemplate.send(topicName, message); + CompletableFuture> future = kafkaTemplate.send(topicName, message); + future.whenComplete((result, ex) -> { - future.addCallback(new ListenableFutureCallback>() { - - @Override - public void onSuccess(SendResult result) { + if (ex == null) { System.out.println("Sent message=[" + message + "] with offset=[" + result.getRecordMetadata() .offset() + "]"); - } - - @Override - public void onFailure(Throwable ex) { + } else { System.out.println("Unable to send message=[" + message + "] due to : " + ex.getMessage()); } }); @@ -155,13 +149,13 @@ public class KafkaApplication { } @KafkaListener(topics = "${message.topic.name}", containerFactory = "headersKafkaListenerContainerFactory") - public void listenWithHeaders(@Payload String message, @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition) { + public void listenWithHeaders(@Payload String message, @Header(KafkaHeaders.RECEIVED_PARTITION) int partition) { System.out.println("Received Message: " + message + " from partition: " + partition); latch.countDown(); } @KafkaListener(topicPartitions = @TopicPartition(topic = "${partitioned.topic.name}", partitions = { "0", "3" }), containerFactory = "partitionsKafkaListenerContainerFactory") - public void listenToPartition(@Payload String message, @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition) { + public void listenToPartition(@Payload String message, @Header(KafkaHeaders.RECEIVED_PARTITION) int partition) { System.out.println("Received Message: " + message + " from partition: " + partition); this.partitionLatch.countDown(); } diff --git a/spring-kafka/src/test/java/com/baeldung/kafka/streams/KafkaStreamsApplicationLiveTest.java b/spring-kafka/src/test/java/com/baeldung/kafka/streams/KafkaStreamsApplicationLiveTest.java index 85df8485d2..aee3c2c0dc 100644 --- a/spring-kafka/src/test/java/com/baeldung/kafka/streams/KafkaStreamsApplicationLiveTest.java +++ b/spring-kafka/src/test/java/com/baeldung/kafka/streams/KafkaStreamsApplicationLiveTest.java @@ -20,7 +20,7 @@ import org.junit.jupiter.api.io.TempDir; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; diff --git a/spring-security-modules/pom.xml b/spring-security-modules/pom.xml index d6e30e8ab8..223f0894d5 100644 --- a/spring-security-modules/pom.xml +++ b/spring-security-modules/pom.xml @@ -49,6 +49,7 @@ spring-security-web-x509 spring-security-opa spring-security-pkce + spring-security-azuread \ No newline at end of file diff --git a/spring-security-modules/spring-security-azuread/pom.xml b/spring-security-modules/spring-security-azuread/pom.xml new file mode 100644 index 0000000000..c4dbbd14b9 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/pom.xml @@ -0,0 +1,76 @@ + + + + 4.0.0 + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + spring-security-azuread + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-oauth2-client + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/Application.java b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/Application.java new file mode 100644 index 0000000000..ac36bc1328 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/Application.java @@ -0,0 +1,14 @@ +package com.baeldung.security.azuread; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/config/JwtAuthorizationConfiguration.java b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/config/JwtAuthorizationConfiguration.java new file mode 100644 index 0000000000..4d82e930ae --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/config/JwtAuthorizationConfiguration.java @@ -0,0 +1,72 @@ +package com.baeldung.security.azuread.config; + +import java.util.HashSet; +import java.util.Set; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +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.core.GrantedAuthority; +import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest; +import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService; +import org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails; +import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; +import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; +import org.springframework.security.oauth2.core.oidc.user.OidcUser; +import org.springframework.security.web.SecurityFilterChain; + +import com.baeldung.security.azuread.support.GroupsClaimMapper; +import com.baeldung.security.azuread.support.NamedOidcUser; + +@Configuration +@EnableConfigurationProperties(JwtAuthorizationProperties.class) +public class JwtAuthorizationConfiguration { + + + + @Bean + SecurityFilterChain customJwtSecurityChain(HttpSecurity http, JwtAuthorizationProperties props) throws Exception { + // @formatter:off + return http + .authorizeRequests( r -> r.anyRequest().authenticated()) + .oauth2Login(oauth2 -> { + oauth2.userInfoEndpoint(ep -> + ep.oidcUserService(customOidcUserService(props))); + }) + .build(); + // @formatter:on + } + + private OAuth2UserService customOidcUserService(JwtAuthorizationProperties props) { + final OidcUserService delegate = new OidcUserService(); + final GroupsClaimMapper mapper = new GroupsClaimMapper( + props.getAuthoritiesPrefix(), + props.getGroupsClaim(), + props.getGroupToAuthorities()); + + return (userRequest) -> { + OidcUser oidcUser = delegate.loadUser(userRequest); + // Enrich standard authorities with groups + Set mappedAuthorities = new HashSet<>(); + mappedAuthorities.addAll(oidcUser.getAuthorities()); + mappedAuthorities.addAll(mapper.mapAuthorities(oidcUser)); + + oidcUser = new NamedOidcUser(mappedAuthorities, oidcUser.getIdToken(), oidcUser.getUserInfo(),oidcUser.getName()); + + return oidcUser; + }; + } + + + +// @Bean +// GrantedAuthoritiesMapper jwtAuthoritiesMapper(JwtAuthorizationProperties props) { +// return new MappingJwtGrantedAuthoritiesMapper( +// props.getAuthoritiesPrefix(), +// props.getGroupsClaim(), +// props.getGroupToAuthorities()); +// } + + +} diff --git a/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/config/JwtAuthorizationProperties.java b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/config/JwtAuthorizationProperties.java new file mode 100644 index 0000000000..981be317a3 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/config/JwtAuthorizationProperties.java @@ -0,0 +1,68 @@ +package com.baeldung.security.azuread.config; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * @author Baeldung + * + */ +@ConfigurationProperties(prefix="baeldung.jwt.authorization") +public class JwtAuthorizationProperties { + + // Claim that has the group list + private String groupsClaim = "groups"; + + private String authoritiesPrefix = "ROLE_"; + + // map groupIds to a list of authorities. + private Map> groupToAuthorities = new HashMap<>(); + + /** + * @return the groupsClaim + */ + public String getGroupsClaim() { + return groupsClaim; + } + + /** + * @param groupsClaim the groupsClaim to set + */ + public void setGroupsClaim(String groupsClaim) { + this.groupsClaim = groupsClaim; + } + + /** + * @return the groupToAuthorities + */ + public Map> getGroupToAuthorities() { + return groupToAuthorities; + } + + /** + * @param groupToAuthorities the groupToAuthorities to set + */ + public void setGroupToAuthorities(Map> groupToAuthorities) { + this.groupToAuthorities = groupToAuthorities; + } + + /** + * @return the authoritiesPrefix + */ + public String getAuthoritiesPrefix() { + return authoritiesPrefix; + } + + /** + * @param authoritiesPrefix the authoritiesPrefix to set + */ + public void setAuthoritiesPrefix(String authoritiesPrefix) { + this.authoritiesPrefix = authoritiesPrefix; + } + + + +} diff --git a/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/controllers/IndexController.java b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/controllers/IndexController.java new file mode 100644 index 0000000000..d2cebd0231 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/controllers/IndexController.java @@ -0,0 +1,22 @@ +package com.baeldung.security.azuread.controllers; + +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +import lombok.extern.slf4j.Slf4j; + +@Controller +@RequestMapping("/") +@Slf4j +public class IndexController { + + @GetMapping + public String index(Model model, Authentication user) { + log.info("GET /: user={}", user); + model.addAttribute("user", user); + return "index"; + } +} diff --git a/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/support/GroupsClaimMapper.java b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/support/GroupsClaimMapper.java new file mode 100644 index 0000000000..2487cd9db3 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/support/GroupsClaimMapper.java @@ -0,0 +1,61 @@ +/** + * + */ +package com.baeldung.security.azuread.support; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.core.convert.converter.Converter; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper; +import org.springframework.security.oauth2.core.ClaimAccessor; +import org.springframework.security.oauth2.jwt.Jwt; + +/** + * @author Baeldung + * + */ +public class GroupsClaimMapper { + + private final String authoritiesPrefix; + private final String groupsClaim; + private final Map> groupToAuthorities; + + public GroupsClaimMapper(String authoritiesPrefix, String groupsClaim, Map> groupToAuthorities) { + this.authoritiesPrefix = authoritiesPrefix; + this.groupsClaim = groupsClaim; + this.groupToAuthorities = Collections.unmodifiableMap(groupToAuthorities); + } + + public Collection mapAuthorities(ClaimAccessor source) { + + List groups = source.getClaimAsStringList(groupsClaim); + if ( groups == null || groups.isEmpty()) { + return Collections.emptyList(); + } + + List result = new ArrayList<>(); + for( String g : groups) { + List authNames = groupToAuthorities.get(g); + if ( authNames == null ) { + continue; + } + + List mapped = authNames.stream() + .map( s -> authoritiesPrefix + s) + .map( SimpleGrantedAuthority::new) + .collect(Collectors.toList()); + + result.addAll(mapped); + } + + return result; + } + +} diff --git a/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/support/NamedOidcUser.java b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/support/NamedOidcUser.java new file mode 100644 index 0000000000..b29b04fe7b --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/main/java/com/baeldung/security/azuread/support/NamedOidcUser.java @@ -0,0 +1,24 @@ +package com.baeldung.security.azuread.support; + +import java.util.Collection; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.core.oidc.OidcIdToken; +import org.springframework.security.oauth2.core.oidc.OidcUserInfo; +import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; + +public class NamedOidcUser extends DefaultOidcUser { + private static final long serialVersionUID = 1L; + private final String userName; + + public NamedOidcUser(Collection authorities, OidcIdToken idToken, + OidcUserInfo userInfo, String userName) { + super(authorities,idToken,userInfo); + this.userName= userName; + } + + @Override + public String getName() { + return this.userName; + } +} diff --git a/spring-security-modules/spring-security-azuread/src/main/resources/application-azuread.yml b/spring-security-modules/spring-security-azuread/src/main/resources/application-azuread.yml new file mode 100644 index 0000000000..5e65c381c8 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/main/resources/application-azuread.yml @@ -0,0 +1,27 @@ +spring: + security: + oauth2: + client: + provider: + azure: + issuer-uri: https://login.microsoftonline.com/2e9fde3a-38ec-44f9-8bcd-c184dc1e8033/v2.0 + user-name-attribute: name + registration: + azure-dev: + provider: azure + #client-id: "6035bfd4-22f0-437c-b76f-da729a916cbf" + #client-secret: "fo28Q~-aLbmQvonnZtzbgtSiqYstmBWEmGPAodmx" + client-id: your-client-id + client-secret: your-secret-id + scope: + - openid + - email + - profile + +# Group mapping +baeldung: + jwt: + authorization: + group-to-authorities: + "ceef656a-fca9-49b6-821b-f7543b7065cb": BAELDUNG_RW + "eaaecb69-ccbc-4143-b111-7dd1ce1d99f1": BAELDUNG_RO,BAELDUNG_ADMIN \ No newline at end of file diff --git a/spring-security-modules/spring-security-azuread/src/main/resources/application.properties b/spring-security-modules/spring-security-azuread/src/main/resources/application.properties new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/spring-security-modules/spring-security-azuread/src/main/resources/templates/index.html b/spring-security-modules/spring-security-azuread/src/main/resources/templates/index.html new file mode 100644 index 0000000000..ca9a9bdbe8 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/main/resources/templates/index.html @@ -0,0 +1,53 @@ + + + + +Insert title here + + + +

Hello, NOMO_NOMO

+ +

User info:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributeValue
Nameuser.name
Classuser.class
Principal Classuser.principal.class
isAuthenticated?user.authenticated
clientRegistrationIduser.authorizedClientregistrationId
Claim: keyvalue
Granted Authority: authority
+ + \ No newline at end of file diff --git a/spring-security-modules/spring-security-azuread/src/test/java/com/baeldung/security/azuread/ApplicationLiveTest.java b/spring-security-modules/spring-security-azuread/src/test/java/com/baeldung/security/azuread/ApplicationLiveTest.java new file mode 100644 index 0000000000..8c941aa787 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/test/java/com/baeldung/security/azuread/ApplicationLiveTest.java @@ -0,0 +1,62 @@ +package com.baeldung.security.azuread; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +import java.net.URI; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; + +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +@ActiveProfiles("azuread") +class ApplicationLiveTest { + + @Autowired + TestRestTemplate rest; + + @LocalServerPort + int port; + + @Test + void testWhenAccessRootPath_thenRedirectToAzureAD() { + + ResponseEntity response = rest.getForEntity("http://localhost:" + port , String.class); + HttpStatus st = response.getStatusCode(); + assertThat(st) + .isEqualTo(HttpStatus.FOUND); + + URI location1 = response.getHeaders().getLocation(); + assertThat(location1) + .isNotNull(); + assertThat(location1.getPath()) + .isEqualTo("/oauth2/authorization/azure-dev"); + + assertThat(location1.getPort()) + .isEqualTo(port); + + assertThat(location1.getHost()) + .isEqualTo("localhost"); + + // Now let't follow this redirect + response = rest.getForEntity(location1, String.class); + assertThat(st) + .isEqualTo(HttpStatus.FOUND); + URI location2 = response.getHeaders().getLocation(); + assertThat(location2) + .isNotNull(); + + assertThat(location2.getHost()) + .describedAs("Should redirect to AzureAD") + .isEqualTo("login.microsoftonline.com"); + + } + +} diff --git a/spring-security-modules/spring-security-azuread/src/test/java/com/baeldung/security/azuread/support/GroupsClaimMapperUnitTest.java b/spring-security-modules/spring-security-azuread/src/test/java/com/baeldung/security/azuread/support/GroupsClaimMapperUnitTest.java new file mode 100644 index 0000000000..0a8f85d0d1 --- /dev/null +++ b/spring-security-modules/spring-security-azuread/src/test/java/com/baeldung/security/azuread/support/GroupsClaimMapperUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.security.azuread.support; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.oauth2.core.ClaimAccessor; + +class GroupsClaimMapperUnitTest { + + private Map> g2a = new HashMap<>(); + + @Test + void testWhenNoGroupClaimsPresent_thenNoAuthoritiesAdded() { + + ClaimAccessor source = mock(ClaimAccessor.class); + GroupsClaimMapper mapper = new GroupsClaimMapper("ROLE", "group", g2a); + + Collection authorities = mapper.mapAuthorities(source); + assertThat(authorities) + .isNotNull() + .isEmpty(); + } + + @Test + void testWhenEmptyGroupClaimsPresent_thenNoAuthoritiesAdded() { + + ClaimAccessor source = mock(ClaimAccessor.class); + when(source.getClaimAsStringList("group")) + .thenReturn(Collections.emptyList()); + + GroupsClaimMapper mapper = new GroupsClaimMapper("ROLE", "group", g2a); + + Collection authorities = mapper.mapAuthorities(source); + assertThat(authorities) + .isNotNull() + .isEmpty(); + } + +} diff --git a/spring-web-modules/spring-mvc-basics-4/pom.xml b/spring-web-modules/spring-mvc-basics-4/pom.xml index 376e13ed72..455e4e488c 100644 --- a/spring-web-modules/spring-mvc-basics-4/pom.xml +++ b/spring-web-modules/spring-mvc-basics-4/pom.xml @@ -15,26 +15,26 @@ - - com.fasterxml.jackson.core - jackson-databind - - - org.springframework - spring-web - org.springframework.boot spring-boot-starter-validation - javax.servlet - javax.servlet-api - provided + org.springframework.boot + spring-boot-starter-web + 3.0.2 - org.springframework - spring-webmvc + org.apache.tomcat.embed + tomcat-embed-jasper + + + javax.servlet + jstl + + + org.springframework.boot + spring-boot-starter-thymeleaf diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/config/WebConfig.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/config/WebConfig.java new file mode 100644 index 0000000000..e9b59a2b23 --- /dev/null +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/config/WebConfig.java @@ -0,0 +1,44 @@ +package com.baeldung.config; + +import org.springframework.boot.web.server.WebServerFactoryCustomizer; +import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; +import org.thymeleaf.spring5.SpringTemplateEngine; +import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; +import org.thymeleaf.spring5.view.ThymeleafViewResolver; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; +import org.thymeleaf.templateresolver.ITemplateResolver; + +import com.baeldung.contexts.Greeting; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Web Configuration for the entire app + */ +@Configuration +@EnableWebMvc +public class WebConfig { + + @Bean + public WebServerFactoryCustomizer enableDefaultServlet() { + return factory -> factory.setRegisterDefaultServlet(true); + } + + @Bean + public Greeting greeting() { + Greeting greeting = new Greeting(); + greeting.setMessage("Hello World !!"); + return greeting; + } + + @Bean + public ObjectMapper objectMapper() { + return new ObjectMapper(); + } +} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java deleted file mode 100644 index 1dffad637a..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.contexts.config; - -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; - -public class AnnotationsBasedApplicationAndServletInitializer //extends AbstractDispatcherServletInitializer -{ - - //uncomment to run the multiple contexts example - //@Override - protected WebApplicationContext createRootApplicationContext() { - //If this is not the only class declaring a root context, we return null because it would clash - //with other classes, as there can only be a single root context. - - //AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); - //rootContext.register(RootApplicationConfig.class); - //return rootContext; - return null; - } - - //@Override - protected WebApplicationContext createServletApplicationContext() { - AnnotationConfigWebApplicationContext normalWebAppContext = new AnnotationConfigWebApplicationContext(); - normalWebAppContext.register(NormalWebAppConfig.class); - return normalWebAppContext; - } - - //@Override - protected String[] getServletMappings() { - return new String[] { "/api/*" }; - } - - //@Override - protected String getServletName() { - return "normal-dispatcher"; - } -} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java deleted file mode 100644 index ffa80d58bf..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.contexts.config; - -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; - -public class AnnotationsBasedApplicationInitializer //extends AbstractContextLoaderInitializer -{ - //uncomment to run the multiple contexts example - // @Override - protected WebApplicationContext createRootApplicationContext() { - AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); - rootContext.register(RootApplicationConfig.class); - return rootContext; - } - -} \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java deleted file mode 100644 index 15a2631cbb..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.contexts.config; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -import org.springframework.context.annotation.Configuration; -import org.springframework.context.support.ClassPathXmlApplicationContext; -import org.springframework.web.WebApplicationInitializer; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.context.support.XmlWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -public class ApplicationInitializer //implements WebApplicationInitializer -{ - //uncomment to run the multiple contexts example - //@Override - public void onStartup(ServletContext servletContext) throws ServletException { - //Here, we can define a root context and register servlets, among other things. - //However, since we've later defined other classes to do the same and they would clash, - //we leave this commented out. - - //Root XML Context - //XmlWebApplicationContext rootContext = new XmlWebApplicationContext(); - //rootContext.setConfigLocations("/WEB-INF/rootApplicationContext.xml"); - //Annotations Context - //AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); - //rootContext.register(RootApplicationConfig.class); - //Registration - //servletContext.addListener(new ContextLoaderListener(rootContext)); - - //Dispatcher Servlet - //XmlWebApplicationContext normalWebAppContext = new XmlWebApplicationContext(); - //normalWebAppContext.setConfigLocation("/WEB-INF/normal-webapp-servlet.xml"); - //ServletRegistration.Dynamic normal = servletContext.addServlet("normal-webapp", new DispatcherServlet(normalWebAppContext)); - //normal.setLoadOnStartup(1); - //normal.addMapping("/api/*"); - } - -} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java deleted file mode 100644 index 3da3d3beb1..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.contexts.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; - -@Configuration -@EnableWebMvc -@ComponentScan(basePackages = { "com.baeldung.contexts.normal" }) -public class NormalWebAppConfig implements WebMvcConfigurer { - - @Bean - public ViewResolver viewResolver() { - InternalResourceViewResolver resolver = new InternalResourceViewResolver(); - resolver.setPrefix("/WEB-INF/view/"); - resolver.setSuffix(".jsp"); - resolver.setViewClass(JstlView.class); - return resolver; - } -} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/RootApplicationConfig.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/RootApplicationConfig.java deleted file mode 100644 index 59821076d2..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/RootApplicationConfig.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.contexts.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -import com.baeldung.contexts.Greeting; - -@Configuration -@ComponentScan(basePackages = { "com.baeldung.contexts.services" }) -public class RootApplicationConfig { - - @Bean - public Greeting greeting() { - Greeting greeting = new Greeting(); - greeting.setMessage("Hello World !!"); - return greeting; - } -} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java deleted file mode 100644 index 580e86d2b5..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.contexts.config; - -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; - -public class SecureAnnotationsBasedApplicationAndServletInitializer// extends AbstractDispatcherServletInitializer -{ - - //uncomment to run the multiple contexts example - //@Override - protected WebApplicationContext createRootApplicationContext() { - return null; - } - - //@Override - protected WebApplicationContext createServletApplicationContext() { - AnnotationConfigWebApplicationContext secureWebAppContext = new AnnotationConfigWebApplicationContext(); - secureWebAppContext.register(SecureWebAppConfig.class); - return secureWebAppContext; - } - - //@Override - protected String[] getServletMappings() { - return new String[] { "/s/api/*" }; - } - - - //@Override - protected String getServletName() { - return "secure-dispatcher"; - } - -} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java deleted file mode 100644 index acc1e3092b..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.contexts.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; - -@Configuration -@EnableWebMvc -@ComponentScan(basePackages = { "com.baeldung.contexts.secure" }) -public class SecureWebAppConfig implements WebMvcConfigurer { - - @Bean - public ViewResolver viewResolver() { - InternalResourceViewResolver resolver = new InternalResourceViewResolver(); - resolver.setPrefix("/WEB-INF/secure/view/"); - resolver.setSuffix(".jsp"); - resolver.setViewClass(JstlView.class); - return resolver; - } -} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java index 8b58c51eb3..46d1769349 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java @@ -3,9 +3,9 @@ package com.baeldung.contexts.normal; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.context.ContextLoader; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; @@ -19,21 +19,22 @@ public class HelloWorldController { @Autowired private GreeterService greeterService; + + @Autowired + private ApplicationContext applicationContext; private void processContext() { - WebApplicationContext rootContext = ContextLoader.getCurrentWebApplicationContext(); - - System.out.println("root context : " + rootContext); - System.out.println("root context Beans: " + Arrays.asList(rootContext.getBeanDefinitionNames())); + System.out.println("root context : " + applicationContext); + System.out.println("root context Beans: " + Arrays.asList(applicationContext.getBeanDefinitionNames())); System.out.println("context : " + webApplicationContext); System.out.println("context Beans: " + Arrays.asList(webApplicationContext.getBeanDefinitionNames())); } - @RequestMapping(path = "/welcome") + @GetMapping(path = "/welcome") public ModelAndView helloWorld() { processContext(); String message = "
" + "

Normal " + greeterService.greet() + "

"; - return new ModelAndView("welcome", "message", message); + return new ModelAndView("/view/welcome", "message", message); } } diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java index 4ebf2d55e0..84d7808000 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/secure/HelloWorldSecureController.java @@ -6,8 +6,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.context.ContextLoader; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; @@ -31,19 +30,15 @@ public class HelloWorldSecureController { ApplicationContext context = contextUtilService.getApplicationContext(); System.out.println("application context : " + context); System.out.println("application context Beans: " + Arrays.asList(context.getBeanDefinitionNames())); - - WebApplicationContext rootContext = ContextLoader.getCurrentWebApplicationContext(); - System.out.println("context : " + rootContext); - System.out.println("context Beans: " + Arrays.asList(rootContext.getBeanDefinitionNames())); System.out.println("context : " + webApplicationContext); System.out.println("context Beans: " + Arrays.asList(webApplicationContext.getBeanDefinitionNames())); } - @RequestMapping(path = "/welcome") + @GetMapping(path = "/welcome_secure") public ModelAndView helloWorld() { processContext(); String message = "
" + "

Secure " + greeterService.greet() + "

"; - return new ModelAndView("welcome", "message", message); + return new ModelAndView("/secure/view/welcome", "message", message); } } diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/config/StudentControllerConfig.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/config/StudentControllerConfig.java deleted file mode 100644 index b84094132d..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/config/StudentControllerConfig.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.controller.config; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -public class StudentControllerConfig //implements WebApplicationInitializer -{ - - //uncomment to run the student controller example - //@Override - public void onStartup(ServletContext sc) throws ServletException { - AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); - root.register(WebConfig.class); - root.setServletContext(sc); - sc.addListener(new ContextLoaderListener(root)); - - DispatcherServlet dv = new DispatcherServlet(root); - - ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv); - appServlet.setLoadOnStartup(1); - appServlet.addMapping("/test/*"); - } -} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/config/WebConfig.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/config/WebConfig.java deleted file mode 100644 index 364f042ac7..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/config/WebConfig.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.controller.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.view.InternalResourceViewResolver; - -@Configuration -@EnableWebMvc -@ComponentScan(basePackages = { "com.baeldung.controller", "com.baeldung.optionalpathvars" }) -public class WebConfig implements WebMvcConfigurer { - @Override - public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - @Bean - public ViewResolver viewResolver() { - InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setPrefix("/WEB-INF/"); - bean.setSuffix(".jsp"); - return bean; - } -} \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/GreetingsController.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/GreetingsController.java index fbf78b8a0e..1568b94050 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/GreetingsController.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/GreetingsController.java @@ -7,42 +7,26 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; -@Controller +@RestController public class GreetingsController { - @RequestMapping( - value = "/greetings-with-response-body", - method = RequestMethod.GET, - produces="application/json" - ) - @ResponseBody + @GetMapping(value = "/greetings-with-response-body", produces="application/json") public String getGreetingWhileReturnTypeIsString() { - return "{\"test\": \"Hello using @ResponseBody\"}"; + return "{\"test\": \"Hello\"}"; } - @RequestMapping( - value = "/greetings-with-response-entity", - method = RequestMethod.GET, - produces = "application/json" - ) + @GetMapping(value = "/greetings-with-response-entity", produces = "application/json") public ResponseEntity getGreetingWithResponseEntity() { final HttpHeaders httpHeaders= new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); - return new ResponseEntity("{\"test\": \"Hello with ResponseEntity\"}", httpHeaders, HttpStatus.OK); + return new ResponseEntity<>("{\"test\": \"Hello with ResponseEntity\"}", httpHeaders, HttpStatus.OK); } - @RequestMapping( - value = "/greetings-with-map-return-type", - method = RequestMethod.GET, - produces = "application/json" - ) - @ResponseBody + @GetMapping(value = "/greetings-with-map-return-type", produces = "application/json") public Map getGreetingWhileReturnTypeIsMap() { - HashMap map = new HashMap(); + HashMap map = new HashMap<>(); map.put("test", "Hello from map"); return map; } diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/PassParametersController.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/PassParametersController.java index d8330333cb..46b7003f3e 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/PassParametersController.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/PassParametersController.java @@ -18,19 +18,19 @@ public class PassParametersController { @GetMapping("/showViewPage") public String passParametersWithModel(Model model) { model.addAttribute("message", "Baeldung"); - return "viewPage"; + return "view/viewPage"; } @GetMapping("/printViewPage") public String passParametersWithModelMap(ModelMap map) { map.addAttribute("welcomeMessage", "welcome"); map.addAttribute("message", "Baeldung"); - return "viewPage"; + return "view/viewPage"; } @GetMapping("/goToViewPage") public ModelAndView passParametersWithModelAndView() { - ModelAndView modelAndView = new ModelAndView("viewPage"); + ModelAndView modelAndView = new ModelAndView("view/viewPage"); modelAndView.addObject("message", "Baeldung"); return modelAndView; } diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/RestController.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/RestController.java index a529faeed3..eead000621 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/RestController.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/controller/RestController.java @@ -1,17 +1,15 @@ package com.baeldung.controller.controller; -import com.baeldung.controller.student.Student; -import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.ResponseBody; -@Controller +import com.baeldung.controller.student.Student; + +@org.springframework.web.bind.annotation.RestController public class RestController { @GetMapping(value = "/student/{studentId}") - public @ResponseBody - Student getTestData(@PathVariable Integer studentId) { + public Student getTestData(@PathVariable Integer studentId) { Student student = new Student(); student.setName("Peter"); student.setId(studentId); diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/student/Student.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/student/Student.java index 8a82dd5553..5c2b991312 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/student/Student.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/controller/student/Student.java @@ -27,7 +27,14 @@ public class Student { } @Override - public boolean equals(Object obj) { - return this.name.equals(((Student) obj).getName()); + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Student)) { + return false; + } + Student student = (Student) o; + return getName().equals(student.getName()); } } \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/config/JsonParamsConfig.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/config/JsonParamsConfig.java deleted file mode 100644 index f2049554ab..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/config/JsonParamsConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.jsonparams.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.view.InternalResourceViewResolver; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@Configuration -@EnableWebMvc -@ComponentScan(basePackages = { "com.baeldung.jsonparams" }) -public class JsonParamsConfig implements WebMvcConfigurer { - @Override - public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - @Bean - public ViewResolver viewResolver() { - InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setPrefix("/WEB-INF/"); - bean.setSuffix(".jsp"); - return bean; - } - - @Bean - public ObjectMapper objectMapper() { - return new ObjectMapper(); - } - -} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/config/JsonParamsInit.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/config/JsonParamsInit.java deleted file mode 100644 index 6db2a92350..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/config/JsonParamsInit.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.jsonparams.config; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -public class JsonParamsInit // implements WebApplicationInitializer -{ - - //uncomment to run the product controller example - //@Override - public void onStartup(ServletContext sc) throws ServletException { - AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); - root.register(JsonParamsConfig.class); - root.setServletContext(sc); - sc.addListener(new ContextLoaderListener(root)); - - DispatcherServlet dv = new DispatcherServlet(root); - - ServletRegistration.Dynamic appServlet = sc.addServlet("jsonparams-mvc", dv); - appServlet.setLoadOnStartup(1); - appServlet.addMapping("/"); - } - -} diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/controller/ProductController.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/controller/ProductController.java index e4e2ce085d..915731581e 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/controller/ProductController.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/controller/ProductController.java @@ -1,7 +1,6 @@ package com.baeldung.jsonparams.controller; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.InitBinder; @@ -9,7 +8,7 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; import com.baeldung.jsonparams.model.Product; import com.baeldung.jsonparams.propertyeditor.ProductEditor; @@ -17,7 +16,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; -@Controller +@RestController @RequestMapping("/products") public class ProductController { @@ -34,21 +33,18 @@ public class ProductController { } @PostMapping("/create") - @ResponseBody public Product createProduct(@RequestBody Product product) { // custom logic return product; } @GetMapping("/get") - @ResponseBody - public Product getProduct(@RequestParam String product) throws JsonMappingException, JsonProcessingException { + public Product getProduct(@RequestParam String product) throws JsonProcessingException { final Product prod = objectMapper.readValue(product, Product.class); return prod; } @GetMapping("/get2") - @ResponseBody public Product get2Product(@RequestParam Product product) { // custom logic return product; diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/propertyeditor/ProductEditor.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/propertyeditor/ProductEditor.java index 11766118cd..41d97bed84 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/propertyeditor/ProductEditor.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/jsonparams/propertyeditor/ProductEditor.java @@ -18,7 +18,7 @@ public class ProductEditor extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { - if (StringUtils.isEmpty(text)) { + if (!StringUtils.hasText(text)) { setValue(null); } else { Product prod = new Product(); diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerController.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerController.java deleted file mode 100644 index 1876798bd6..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerController.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.optionalpathvars; - -import static com.baeldung.optionalpathvars.Article.DEFAULT_ARTICLE; - -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class ArticleViewerController { - - @RequestMapping(value = {"/article", "/article/{id}"}) - public Article getArticle(@PathVariable(name = "id") Integer articleId) { - - if (articleId != null) { - return new Article(articleId); - } else { - return DEFAULT_ARTICLE; - } - - } - -} \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerWithRequiredAttributeController.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerWithRequiredAttributeController.java index 7548747f05..786a56c130 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerWithRequiredAttributeController.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/optionalpathvars/ArticleViewerWithRequiredAttributeController.java @@ -4,7 +4,7 @@ import static com.baeldung.optionalpathvars.Article.DEFAULT_ARTICLE; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController;; +import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value = "/requiredAttribute") diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java index f16d5f877f..3d518c467c 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java @@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -@ComponentScan(basePackages = "com.baeldung.validation.listvalidation") +@ComponentScan(basePackages = "com.baeldung") @Configuration @SpringBootApplication public class SpringListValidationApplication { diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/secure/view/welcome.html b/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/secure/view/welcome.html new file mode 100644 index 0000000000..fac7234f15 --- /dev/null +++ b/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/secure/view/welcome.html @@ -0,0 +1,11 @@ + + + + Spring Web Contexts + + +
+
Secure Web Application : +
+ + \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/viewPage.html b/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/view/viewPage.html similarity index 58% rename from spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/viewPage.html rename to spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/view/viewPage.html index 71f766407e..b520d0dd51 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/viewPage.html +++ b/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/view/viewPage.html @@ -4,6 +4,6 @@ Title -
Web Application. Passed parameter : th:text="${message}"
+
Web Application. Passed parameter :
diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/welcome.jsp b/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/view/welcome.html similarity index 57% rename from spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/welcome.jsp rename to spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/view/welcome.html index 4eda3c58e2..291f3b8919 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/welcome.jsp +++ b/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/view/welcome.html @@ -1,11 +1,12 @@ - + + Spring Web Contexts
- Normal Web Application : ${message} + Normal Web Application :
\ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/welcome.html b/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/welcome.html new file mode 100644 index 0000000000..c5b88e135e --- /dev/null +++ b/spring-web-modules/spring-mvc-basics-4/src/main/resources/templates/welcome.html @@ -0,0 +1,10 @@ + + + + + Insert title here + + +Data returned is + + \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/resources/test-mvc.xml b/spring-web-modules/spring-mvc-basics-4/src/main/resources/test-mvc.xml deleted file mode 100644 index 44c300dfc6..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/resources/test-mvc.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - /WEB-INF/ - - - .jsp - - - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/greeting.xml b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/greeting.xml deleted file mode 100644 index 1ad5484d80..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/greeting.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/index.jsp b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/index.jsp deleted file mode 100644 index c38169bb95..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/index.jsp +++ /dev/null @@ -1,5 +0,0 @@ - - -

Hello World!

- - diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/normal-webapp-servlet.xml b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/normal-webapp-servlet.xml deleted file mode 100644 index 8addbe3cf3..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/normal-webapp-servlet.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/rootApplicationContext.xml b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/rootApplicationContext.xml deleted file mode 100644 index 12e5d8f161..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/rootApplicationContext.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/secure-webapp-servlet.xml b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/secure-webapp-servlet.xml deleted file mode 100644 index 86797ad081..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/secure-webapp-servlet.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/secure/view/welcome.jsp b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/secure/view/welcome.jsp deleted file mode 100644 index 49ca0f8e87..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/secure/view/welcome.jsp +++ /dev/null @@ -1,11 +0,0 @@ - - - Spring Web Contexts - - -
-
- Secure Web Application : ${message} -
- - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/sample.jsp b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/sample.jsp deleted file mode 100644 index 4c64bf97f2..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/sample.jsp +++ /dev/null @@ -1,7 +0,0 @@ - - - - -

This is the body of the sample view

- - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/scopesExample.jsp b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/scopesExample.jsp deleted file mode 100644 index e9abcf194c..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/view/scopesExample.jsp +++ /dev/null @@ -1,10 +0,0 @@ - - - - -

Bean Scopes Examples

-
Previous Message: ${previousMessage } -
Current Message: ${currentMessage } -
- - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/web-old.xml b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/web-old.xml deleted file mode 100644 index 1344362d19..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/web-old.xml +++ /dev/null @@ -1,88 +0,0 @@ - - - - - - - - - - - - - - - - - - - normal-webapp-annotations - - org.springframework.web.servlet.DispatcherServlet - - - contextClass - org.springframework.web.context.support.AnnotationConfigWebApplicationContext - - - contextConfigLocation - com.baeldung.contexts.config.NormalWebAppConfig - - 1 - - - normal-webapp-annotations - /api-ann/* - - - - /WEB-INF/index.jsp - - diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/welcome.jsp b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/welcome.jsp deleted file mode 100644 index c34223b411..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/WEB-INF/welcome.jsp +++ /dev/null @@ -1,12 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=UTF-8" - pageEncoding="UTF-8" %> - - - - - Insert title here - - -Data returned is ${data} - - \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/index.jsp b/spring-web-modules/spring-mvc-basics-4/src/main/webapp/index.jsp deleted file mode 100644 index c38169bb95..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/main/webapp/index.jsp +++ /dev/null @@ -1,5 +0,0 @@ - - -

Hello World!

- - diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java index f378357548..7fd8f0c97f 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java @@ -1,26 +1,24 @@ package com.baeldung.controller; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.baeldung.controller.config.WebConfig; -import com.baeldung.controller.student.Student; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.AnnotationConfigWebContextLoader; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { WebConfig.class }, loader = AnnotationConfigWebContextLoader.class) +import com.baeldung.controller.student.Student; +import com.baeldung.validation.listvalidation.SpringListValidationApplication; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class ControllerAnnotationIntegrationTest { private MockMvc mockMvc; diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java index 7e5cf1532e..a7e6bd6c4b 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java @@ -5,9 +5,8 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @@ -15,11 +14,11 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; import com.baeldung.controller.student.Student; +import com.baeldung.validation.listvalidation.SpringListValidationApplication; import com.fasterxml.jackson.databind.ObjectMapper; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration({ "classpath:test-mvc.xml" }) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class ControllerIntegrationTest { private MockMvc mockMvc; diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/GreetingsControllerUnitTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/GreetingsControllerUnitTest.java index ee9a8da8d4..4917d68ef4 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/GreetingsControllerUnitTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/GreetingsControllerUnitTest.java @@ -1,24 +1,21 @@ package com.baeldung.controller; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.baeldung.controller.controller.GreetingsController; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.AnnotationConfigWebContextLoader; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { GreetingsController.class }, loader = AnnotationConfigWebContextLoader.class) +import com.baeldung.validation.listvalidation.SpringListValidationApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class GreetingsControllerUnitTest { private MockMvc mockMvc; diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/PassParametersControllerIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/PassParametersControllerIntegrationTest.java index aa8148c1ef..7408ae825d 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/PassParametersControllerIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/PassParametersControllerIntegrationTest.java @@ -5,24 +5,24 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; +import com.baeldung.validation.listvalidation.SpringListValidationApplication; + /** * This is the test class for {@link com.baeldung.controller.controller.PassParametersController} class. * 09/09/2017 * * @author Ahmet Cetin */ -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration({"classpath:test-mvc.xml"}) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class PassParametersControllerIntegrationTest { private MockMvc mockMvc; @@ -39,7 +39,7 @@ public class PassParametersControllerIntegrationTest { ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/showViewPage")).andReturn().getModelAndView(); //Validate view - Assert.assertEquals(mv.getViewName(), "viewPage"); + Assert.assertEquals(mv.getViewName(), "view/viewPage"); //Validate attribute Assert.assertEquals(mv.getModelMap().get("message").toString(), "Baeldung"); @@ -50,7 +50,7 @@ public class PassParametersControllerIntegrationTest { ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/printViewPage")).andReturn().getModelAndView(); //Validate view - Assert.assertEquals(mv.getViewName(), "viewPage"); + Assert.assertEquals(mv.getViewName(), "view/viewPage"); //Validate attribute Assert.assertEquals(mv.getModelMap().get("message").toString(), "Baeldung"); @@ -61,7 +61,7 @@ public class PassParametersControllerIntegrationTest { ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/goToViewPage")).andReturn().getModelAndView(); //Validate view - Assert.assertEquals(mv.getViewName(), "viewPage"); + Assert.assertEquals(mv.getViewName(), "view/viewPage"); //Validate attribute Assert.assertEquals(mv.getModelMap().get("message").toString(), "Baeldung"); diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/jsonparams/JsonParamsIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/jsonparams/JsonParamsIntegrationTest.java index bceadc4896..9d414ed4ca 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/jsonparams/JsonParamsIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/jsonparams/JsonParamsIntegrationTest.java @@ -1,26 +1,25 @@ package com.baeldung.jsonparams; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.AnnotationConfigWebContextLoader; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import com.baeldung.validation.listvalidation.SpringListValidationApplication; -import com.baeldung.jsonparams.config.JsonParamsConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { JsonParamsConfig.class }, loader = AnnotationConfigWebContextLoader.class) +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class JsonParamsIntegrationTest { private MockMvc mockMvc; diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerIntegrationTest.java deleted file mode 100644 index 0e2313c2ac..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerIntegrationTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.optionalpathvars; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; -import com.baeldung.controller.config.WebConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { WebConfig.class }) -public class ArticleViewerControllerIntegrationTest { - - @Autowired - private WebApplicationContext wac; - - private MockMvc mockMvc; - - @Before - public void setup() throws Exception { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); - } - - @Test - public void whenIdPathVariableIsPassed_thenResponseOK() throws Exception { - - int articleId = 5; - - this.mockMvc - .perform(MockMvcRequestBuilders.get("/article/{id}", articleId)) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(articleId)); - - } - - @Test - public void whenIdPathVariableIsNotPassed_thenResponse500() throws Exception { - - this.mockMvc - .perform(MockMvcRequestBuilders.get("/article")) - .andExpect(MockMvcResultMatchers.status().isInternalServerError()); - - } - - -} \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithOptionalParamIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithOptionalParamIntegrationTest.java index 094995ba67..2685946b4c 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithOptionalParamIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithOptionalParamIntegrationTest.java @@ -4,19 +4,18 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.controller.config.WebConfig; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { WebConfig.class }) +import com.baeldung.validation.listvalidation.SpringListValidationApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class ArticleViewerControllerWithOptionalParamIntegrationTest { @Autowired diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithRequiredAttributeIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithRequiredAttributeIntegrationTest.java index a4b12c7163..e7d864d9be 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithRequiredAttributeIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerControllerWithRequiredAttributeIntegrationTest.java @@ -12,42 +12,38 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.controller.config.WebConfig; +import com.baeldung.validation.listvalidation.SpringListValidationApplication; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration -@ContextConfiguration(classes = { WebConfig.class }) +@ContextConfiguration(classes = { SpringListValidationApplication.class }) public class ArticleViewerControllerWithRequiredAttributeIntegrationTest { @Autowired private WebApplicationContext wac; - + private MockMvc mockMvc; @Before - public void setup() throws Exception { + public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test - public void givenRequiredAttributeIsFalse_whenIdPathVariableIsPassed_thenResponseOK() throws Exception { - - int articleId = 154; + public void whenIdPathVariableIsPassed_thenResponseOK() throws Exception { + int articleId = 5; this.mockMvc .perform(MockMvcRequestBuilders.get("/requiredAttribute/article/{id}", articleId)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(articleId)); - } - + @Test - public void givenRequiredAttributeIsFalse_whenIdPathVariableIsNotPassed_thenResponseOK() throws Exception { - + public void whenIdPathVariableIsNotPassed_thenResponseOK() throws Exception { this.mockMvc .perform(MockMvcRequestBuilders.get("/requiredAttribute/article")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(Article.DEFAULT_ARTICLE.getId())); - + .andExpect(MockMvcResultMatchers.status().isOk()); + } } \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithMapParamIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithMapParamIntegrationTest.java index 044a1c8bce..2be6d1e679 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithMapParamIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithMapParamIntegrationTest.java @@ -4,19 +4,18 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.controller.config.WebConfig; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { WebConfig.class }) +import com.baeldung.validation.listvalidation.SpringListValidationApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class ArticleViewerWithMapParamIntegrationTest { @Autowired diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithTwoSeparateMethodsIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithTwoSeparateMethodsIntegrationTest.java index 1ca926277d..e70ac5e5a6 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithTwoSeparateMethodsIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/optionalpathvars/ArticleViewerWithTwoSeparateMethodsIntegrationTest.java @@ -4,19 +4,18 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.controller.config.WebConfig; -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = { WebConfig.class }) +import com.baeldung.validation.listvalidation.SpringListValidationApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) public class ArticleViewerWithTwoSeparateMethodsIntegrationTest { @Autowired diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java index cddc6c6bd9..14ceb651d7 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java @@ -34,7 +34,7 @@ public class MovieControllerIntegrationTest { Movie movie = new Movie("Movie3"); movies.add(movie); mvc.perform(MockMvcRequestBuilders.post("/movies") - .contentType(MediaType.APPLICATION_JSON_UTF8) + .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(movies))) .andExpect(MockMvcResultMatchers.status() .isOk()); @@ -44,7 +44,7 @@ public class MovieControllerIntegrationTest { public void givenEmptyMovieList_whenAddingMovieList_thenThrowBadRequest() throws Exception { List movies = new ArrayList<>(); mvc.perform(MockMvcRequestBuilders.post("/movies") - .contentType(MediaType.APPLICATION_JSON_UTF8) + .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(movies))) .andExpect(MockMvcResultMatchers.status() .isBadRequest()); @@ -54,7 +54,7 @@ public class MovieControllerIntegrationTest { public void givenEmptyMovieName_whenAddingMovieList_thenThrowBadRequest() throws Exception { Movie movie = new Movie(""); mvc.perform(MockMvcRequestBuilders.post("/movies") - .contentType(MediaType.APPLICATION_JSON_UTF8) + .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(Arrays.asList(movie)))) .andExpect(MockMvcResultMatchers.status() .isBadRequest()); @@ -74,7 +74,7 @@ public class MovieControllerIntegrationTest { movies.add(movie4); movies.add(movie5); mvc.perform(MockMvcRequestBuilders.post("/movies") - .contentType(MediaType.APPLICATION_JSON_UTF8) + .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(movies))) .andExpect(MockMvcResultMatchers.status() .isBadRequest()); diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/resources/test-mvc.xml b/spring-web-modules/spring-mvc-basics-4/src/test/resources/test-mvc.xml deleted file mode 100644 index f1aa8e9504..0000000000 --- a/spring-web-modules/spring-mvc-basics-4/src/test/resources/test-mvc.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - /WEB-INF/ - - - .jsp - - - \ No newline at end of file diff --git a/testing-modules/instancio/pom.xml b/testing-modules/instancio/pom.xml index 137da91897..7687ce282d 100644 --- a/testing-modules/instancio/pom.xml +++ b/testing-modules/instancio/pom.xml @@ -51,8 +51,8 @@ - 2.6.0 + 2.9.0 2.14.1 5.9.2 - \ No newline at end of file + diff --git a/testing-modules/junit5-annotations/pom.xml b/testing-modules/junit5-annotations/pom.xml index a4035a23f1..847baa827c 100644 --- a/testing-modules/junit5-annotations/pom.xml +++ b/testing-modules/junit5-annotations/pom.xml @@ -15,6 +15,12 @@ + + org.junit.jupiter + junit-jupiter + ${junit-jupiter.version} + test + org.junit.platform junit-platform-engine @@ -39,7 +45,7 @@ - 2.17.1 + 2.19.0 \ No newline at end of file