From 626c1096358d4561fe20a6930d9d2b3487302121 Mon Sep 17 00:00:00 2001 From: "alex.oreshkevich" Date: Mon, 16 Mar 2020 19:28:42 +0300 Subject: [PATCH 001/150] Add embedded app server --- spring-mvc-webflow/pom.xml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/spring-mvc-webflow/pom.xml b/spring-mvc-webflow/pom.xml index 5a6856385c..22ae3c913d 100644 --- a/spring-mvc-webflow/pom.xml +++ b/spring-mvc-webflow/pom.xml @@ -72,6 +72,24 @@ + + org.apache.tomee.maven + tomee-maven-plugin + 8.0.1 + + 8080 + spring-mvc-webflow + true + plume + + + .class + + + -Xmx2048m -XX:PermSize=256m -Dtomee.serialization.class.blacklist=- -Dtomee.serialization.class.whitelist=* + true + + org.apache.maven.plugins maven-war-plugin From 5f652fb842f247ad7d859921af5e64a93fe32470 Mon Sep 17 00:00:00 2001 From: Lukasz Rys Date: Sun, 22 Mar 2020 19:14:28 +0100 Subject: [PATCH 002/150] [ BAEL-3751 ] : Initialize CI/CD module with application --- pom.xml | 2 + spring-boot-ci-cd/README.md | 1 + spring-boot-ci-cd/pom.xml | 39 +++++++++++++++++++ .../com/baeldung/cicd/CiCdApplication.java | 12 ++++++ .../main/resources/introduction-config.yml | 1 + 5 files changed, 55 insertions(+) create mode 100644 spring-boot-ci-cd/README.md create mode 100644 spring-boot-ci-cd/pom.xml create mode 100644 spring-boot-ci-cd/src/main/java/com/baeldung/cicd/CiCdApplication.java create mode 100644 spring-boot-ci-cd/src/main/resources/introduction-config.yml diff --git a/pom.xml b/pom.xml index 15331d8c95..9cf1aa2e92 100644 --- a/pom.xml +++ b/pom.xml @@ -638,6 +638,7 @@ spring-batch spring-bom + spring-boot-ci-cd spring-boot-modules spring-boot-rest @@ -1141,6 +1142,7 @@ spring-batch spring-bom + spring-boot-ci-cd spring-boot-modules spring-boot-rest diff --git a/spring-boot-ci-cd/README.md b/spring-boot-ci-cd/README.md new file mode 100644 index 0000000000..d207cd0fa0 --- /dev/null +++ b/spring-boot-ci-cd/README.md @@ -0,0 +1 @@ +# Spring Boot CI/CD \ No newline at end of file diff --git a/spring-boot-ci-cd/pom.xml b/spring-boot-ci-cd/pom.xml new file mode 100644 index 0000000000..070294fdce --- /dev/null +++ b/spring-boot-ci-cd/pom.xml @@ -0,0 +1,39 @@ + + + 4.0.0 + spring-boot-ci-cd + 0.0.1-SNAPSHOT + spring-boot-ci-cd + jar + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-actuator + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-boot-ci-cd/src/main/java/com/baeldung/cicd/CiCdApplication.java b/spring-boot-ci-cd/src/main/java/com/baeldung/cicd/CiCdApplication.java new file mode 100644 index 0000000000..8451084148 --- /dev/null +++ b/spring-boot-ci-cd/src/main/java/com/baeldung/cicd/CiCdApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.cicd; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CiCdApplication { + + public static void main(String[] args) { + SpringApplication.run(CiCdApplication.class, args); + } +} diff --git a/spring-boot-ci-cd/src/main/resources/introduction-config.yml b/spring-boot-ci-cd/src/main/resources/introduction-config.yml new file mode 100644 index 0000000000..02ff36de05 --- /dev/null +++ b/spring-boot-ci-cd/src/main/resources/introduction-config.yml @@ -0,0 +1 @@ +defaultSize: 5 \ No newline at end of file From 1cca64cc7095c723b96bcfa3c7050a3fe55f8456 Mon Sep 17 00:00:00 2001 From: Atanas Gegov Date: Sat, 4 Apr 2020 00:57:04 +0300 Subject: [PATCH 003/150] Fix palindrome unit test One of the test cases was not as described in the test method name. Also corrected formatting in another test case. --- .../java/com/baeldung/mutation/PalindromeUnitTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/testing-modules/testing-libraries/src/test/java/com/baeldung/mutation/PalindromeUnitTest.java b/testing-modules/testing-libraries/src/test/java/com/baeldung/mutation/PalindromeUnitTest.java index cb4830a6fb..207077158e 100644 --- a/testing-modules/testing-libraries/src/test/java/com/baeldung/mutation/PalindromeUnitTest.java +++ b/testing-modules/testing-libraries/src/test/java/com/baeldung/mutation/PalindromeUnitTest.java @@ -11,13 +11,13 @@ public class PalindromeUnitTest { @Test public void whenEmptyString_thanAccept() { Palindrome palindromeTester = new Palindrome(); - assertTrue(palindromeTester.isPalindrome("noon")); + assertTrue(palindromeTester.isPalindrome("")); } @Test - public void whenPalindrom_thanAccept() { - Palindrome palindromeTester = new Palindrome(); - assertTrue(palindromeTester.isPalindrome("noon")); + public void whenPalindrom_thanAccept() { + Palindrome palindromeTester = new Palindrome(); + assertTrue(palindromeTester.isPalindrome("noon")); } @Test From ca16e787e93e891df3cbb9dd6af642efc72fad11 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Sat, 4 Apr 2020 11:42:54 +0530 Subject: [PATCH 004/150] JAVA-991 Week 14 | Do we have any Spring Milestone/RC repos defined? - Removed spring milestone/snapshots repositories from modules --- parent-kotlin/pom.xml | 7 +---- spring-boot-modules/spring-boot-mvc-2/pom.xml | 30 +------------------ 2 files changed, 2 insertions(+), 35 deletions(-) diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml index 52a753439c..4a54264510 100644 --- a/parent-kotlin/pom.xml +++ b/parent-kotlin/pom.xml @@ -28,11 +28,6 @@ kotlin-eap http://dl.bintray.com/kotlin/kotlin-eap - - spring-milestone - Spring Milestone Repository - https://repo.spring.io/milestone - @@ -217,7 +212,7 @@ 0.9.5 3.12.0 1.3.2 - 2.2.0.M4 + 2.2.6.RELEASE diff --git a/spring-boot-modules/spring-boot-mvc-2/pom.xml b/spring-boot-modules/spring-boot-mvc-2/pom.xml index 3c503eb23d..45202d1e4c 100644 --- a/spring-boot-modules/spring-boot-mvc-2/pom.xml +++ b/spring-boot-modules/spring-boot-mvc-2/pom.xml @@ -87,19 +87,6 @@ - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - jcenter-snapshots jcenter @@ -107,27 +94,12 @@ - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - 3.0.0-SNAPSHOT com.baeldung.swagger2boot.SpringBootSwaggerApplication - 2.2.0.BUILD-SNAPSHOT + 2.2.6.RELEASE 1.4.11.1 From d4e7a4bc9dc1fe6b838a566618e5ca1404f9218a Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Sat, 4 Apr 2020 17:39:54 +0530 Subject: [PATCH 005/150] JAVA-991 Week 14 | Do we have any Spring Milestone/RC repos defined? - Reverted removal of snapshot repository from parent-kotlin as some of the artifacts are used by child modules --- parent-kotlin/pom.xml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml index 4a54264510..52a753439c 100644 --- a/parent-kotlin/pom.xml +++ b/parent-kotlin/pom.xml @@ -28,6 +28,11 @@ kotlin-eap http://dl.bintray.com/kotlin/kotlin-eap + + spring-milestone + Spring Milestone Repository + https://repo.spring.io/milestone + @@ -212,7 +217,7 @@ 0.9.5 3.12.0 1.3.2 - 2.2.6.RELEASE + 2.2.0.M4 From 3daa258c680d13d57b6ff6603e50f766c5effad3 Mon Sep 17 00:00:00 2001 From: cristianvasiliu Date: Thu, 16 Apr 2020 15:08:40 +0300 Subject: [PATCH 006/150] Updated dependency assertj.version as the old one wasn't found --- libraries-testing/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries-testing/pom.xml b/libraries-testing/pom.xml index ad6c81a3d6..89cb0bd494 100644 --- a/libraries-testing/pom.xml +++ b/libraries-testing/pom.xml @@ -195,7 +195,7 @@ 0.8.1 4.3.8.RELEASE 4.1.1 - 3.6.2 + 3.14.0 2.0.0.0 1.4.200 2.7.0 From 9105107048c85f7799629e723b5a3bb2f01efad9 Mon Sep 17 00:00:00 2001 From: Suresh Jaganathan Date: Fri, 17 Apr 2020 12:47:32 +0100 Subject: [PATCH 007/150] tested the code with latest testng version 7.1.0 --- testing-modules/testng/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/testng/pom.xml b/testing-modules/testng/pom.xml index 601b152144..c4a1284b0e 100644 --- a/testing-modules/testng/pom.xml +++ b/testing-modules/testng/pom.xml @@ -42,7 +42,7 @@ - 6.10 + 7.1.0 \ No newline at end of file From 80f5196ecc41226395c27e8b0ccd73763f426e4d Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sat, 18 Apr 2020 23:28:45 +0530 Subject: [PATCH 008/150] renamed project name --- .../{entitiymodule => entitymodule}/pom.xml | 0 .../src/main/java/com/baeldung/entity/User.java | 0 .../src/main/java/module-info.java | 0 .../{mainppmodule => mainappmodule}/pom.xml | 9 ++++++--- .../src/main/java/com/baeldung/mainapp/Application.java | 0 .../src/main/java/module-info.java | 0 6 files changed, 6 insertions(+), 3 deletions(-) rename maven-java-11/multimodule-maven-project/{entitiymodule => entitymodule}/pom.xml (100%) rename maven-java-11/multimodule-maven-project/{entitiymodule => entitymodule}/src/main/java/com/baeldung/entity/User.java (100%) rename maven-java-11/multimodule-maven-project/{entitiymodule => entitymodule}/src/main/java/module-info.java (100%) rename maven-java-11/multimodule-maven-project/{mainppmodule => mainappmodule}/pom.xml (97%) rename maven-java-11/multimodule-maven-project/{mainppmodule => mainappmodule}/src/main/java/com/baeldung/mainapp/Application.java (100%) rename maven-java-11/multimodule-maven-project/{mainppmodule => mainappmodule}/src/main/java/module-info.java (100%) diff --git a/maven-java-11/multimodule-maven-project/entitiymodule/pom.xml b/maven-java-11/multimodule-maven-project/entitymodule/pom.xml similarity index 100% rename from maven-java-11/multimodule-maven-project/entitiymodule/pom.xml rename to maven-java-11/multimodule-maven-project/entitymodule/pom.xml diff --git a/maven-java-11/multimodule-maven-project/entitiymodule/src/main/java/com/baeldung/entity/User.java b/maven-java-11/multimodule-maven-project/entitymodule/src/main/java/com/baeldung/entity/User.java similarity index 100% rename from maven-java-11/multimodule-maven-project/entitiymodule/src/main/java/com/baeldung/entity/User.java rename to maven-java-11/multimodule-maven-project/entitymodule/src/main/java/com/baeldung/entity/User.java diff --git a/maven-java-11/multimodule-maven-project/entitiymodule/src/main/java/module-info.java b/maven-java-11/multimodule-maven-project/entitymodule/src/main/java/module-info.java similarity index 100% rename from maven-java-11/multimodule-maven-project/entitiymodule/src/main/java/module-info.java rename to maven-java-11/multimodule-maven-project/entitymodule/src/main/java/module-info.java diff --git a/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml b/maven-java-11/multimodule-maven-project/mainappmodule/pom.xml similarity index 97% rename from maven-java-11/multimodule-maven-project/mainppmodule/pom.xml rename to maven-java-11/multimodule-maven-project/mainappmodule/pom.xml index a4a6575906..1f4493c34c 100644 --- a/maven-java-11/multimodule-maven-project/mainppmodule/pom.xml +++ b/maven-java-11/multimodule-maven-project/mainappmodule/pom.xml @@ -12,9 +12,6 @@ com.baeldung.multimodule-maven-project multimodule-maven-project 1.0 - 1.0 - 1.0 - 1.0 @@ -35,4 +32,10 @@ + + 1.0 + 1.0 + 1.0 + + diff --git a/maven-java-11/multimodule-maven-project/mainppmodule/src/main/java/com/baeldung/mainapp/Application.java b/maven-java-11/multimodule-maven-project/mainappmodule/src/main/java/com/baeldung/mainapp/Application.java similarity index 100% rename from maven-java-11/multimodule-maven-project/mainppmodule/src/main/java/com/baeldung/mainapp/Application.java rename to maven-java-11/multimodule-maven-project/mainappmodule/src/main/java/com/baeldung/mainapp/Application.java diff --git a/maven-java-11/multimodule-maven-project/mainppmodule/src/main/java/module-info.java b/maven-java-11/multimodule-maven-project/mainappmodule/src/main/java/module-info.java similarity index 100% rename from maven-java-11/multimodule-maven-project/mainppmodule/src/main/java/module-info.java rename to maven-java-11/multimodule-maven-project/mainappmodule/src/main/java/module-info.java From 837ebef85832c3a5fdc59929370c815bf1924510 Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Tue, 1 Oct 2019 12:56:55 -0400 Subject: [PATCH 009/150] Add architecture module with Hexagonal example --- architecture/README.md | 3 ++ architecture/pom.xml | 33 ++++++++++++ .../HexagonalArchitectureTaskApplication.java | 12 +++++ .../application/task/AddNewDailyTask.java | 29 ++++++++++ .../application/task/AddNewTask.java | 22 ++++++++ .../application/task/GetTasks.java | 22 ++++++++ .../commands/task/CreateTask.java | 7 +++ .../commands/task/GetAllTasks.java | 7 +++ .../architecture/domain/task/Task.java | 53 +++++++++++++++++++ .../domain/task/TaskRepository.java | 7 +++ .../architecture/domain/task/TaskService.java | 22 ++++++++ .../framework/cli/StartupRunner.java | 25 +++++++++ .../http/task/TaskApiController.java | 42 +++++++++++++++ .../framework/http/task/TaskRequest.java | 29 ++++++++++ 14 files changed, 313 insertions(+) create mode 100644 architecture/README.md create mode 100644 architecture/pom.xml create mode 100644 architecture/src/main/java/com/baeldung/architecture/HexagonalArchitectureTaskApplication.java create mode 100644 architecture/src/main/java/com/baeldung/architecture/application/task/AddNewDailyTask.java create mode 100644 architecture/src/main/java/com/baeldung/architecture/application/task/AddNewTask.java create mode 100644 architecture/src/main/java/com/baeldung/architecture/application/task/GetTasks.java create mode 100644 architecture/src/main/java/com/baeldung/architecture/commands/task/CreateTask.java create mode 100644 architecture/src/main/java/com/baeldung/architecture/commands/task/GetAllTasks.java create mode 100644 architecture/src/main/java/com/baeldung/architecture/domain/task/Task.java create mode 100644 architecture/src/main/java/com/baeldung/architecture/domain/task/TaskRepository.java create mode 100644 architecture/src/main/java/com/baeldung/architecture/domain/task/TaskService.java create mode 100644 architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java create mode 100644 architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskApiController.java create mode 100644 architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskRequest.java diff --git a/architecture/README.md b/architecture/README.md new file mode 100644 index 0000000000..be093f25ed --- /dev/null +++ b/architecture/README.md @@ -0,0 +1,3 @@ +### Relevant articles + +- [A Quick and Practical Example of Hexagonal Architecture in Java](https://www.baeldung.com/a-quick-and-practical-example-of-hexagonal-architecture-in-java-3/) diff --git a/architecture/pom.xml b/architecture/pom.xml new file mode 100644 index 0000000000..4ad104293e --- /dev/null +++ b/architecture/pom.xml @@ -0,0 +1,33 @@ + + 4.0.0 + com.baeldung.architecture + architecture + 0.0.1-SNAPSHOT + architecture + jar + A Quick and Practical Example of Hexagonal Architecture in Java + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + runtime + + + org.springframework.boot + spring-boot-starter-web + + + diff --git a/architecture/src/main/java/com/baeldung/architecture/HexagonalArchitectureTaskApplication.java b/architecture/src/main/java/com/baeldung/architecture/HexagonalArchitectureTaskApplication.java new file mode 100644 index 0000000000..83e4fc4c0b --- /dev/null +++ b/architecture/src/main/java/com/baeldung/architecture/HexagonalArchitectureTaskApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.architecture; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class HexagonalArchitectureTaskApplication { + public static void main(String[] args) { + SpringApplication.run(HexagonalArchitectureTaskApplication.class, args); + } + +} diff --git a/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewDailyTask.java b/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewDailyTask.java new file mode 100644 index 0000000000..208d1bfcc9 --- /dev/null +++ b/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewDailyTask.java @@ -0,0 +1,29 @@ +package com.baeldung.architecture.application.task; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; + +import com.baeldung.architecture.commands.task.CreateTask; +import com.baeldung.architecture.domain.task.Task; + +import org.springframework.stereotype.Component; + +@Component +public class AddNewDailyTask implements CreateTask { + + private AddNewTask addNewTask; + + public AddNewDailyTask(AddNewTask addNewTask) { + this.addNewTask = addNewTask; + } + + @Override + public void create(Task newTask) { + Instant initialDueDate = newTask.getDueDate(); + String description = newTask.getDescription(); + for (int i = 1; i <= 5; i++) { + Task task = new Task(initialDueDate.plus(i, ChronoUnit.DAYS), description); + addNewTask.create(task); + } + } +}; diff --git a/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewTask.java b/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewTask.java new file mode 100644 index 0000000000..2e5aff4a53 --- /dev/null +++ b/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewTask.java @@ -0,0 +1,22 @@ +package com.baeldung.architecture.application.task; + +import com.baeldung.architecture.domain.task.Task; +import com.baeldung.architecture.domain.task.TaskService; +import com.baeldung.architecture.commands.task.*; + +import org.springframework.stereotype.Component; + +@Component +public class AddNewTask implements CreateTask { + + private TaskService taskService; + + public AddNewTask(TaskService taskService) { + this.taskService = taskService; + } + + @Override + public void create(Task newTask) { + taskService.createTask(newTask); + } +}; diff --git a/architecture/src/main/java/com/baeldung/architecture/application/task/GetTasks.java b/architecture/src/main/java/com/baeldung/architecture/application/task/GetTasks.java new file mode 100644 index 0000000000..54539290ba --- /dev/null +++ b/architecture/src/main/java/com/baeldung/architecture/application/task/GetTasks.java @@ -0,0 +1,22 @@ +package com.baeldung.architecture.application.task; + +import com.baeldung.architecture.domain.task.Task; +import com.baeldung.architecture.domain.task.TaskService; +import com.baeldung.architecture.commands.task.*; + +import org.springframework.stereotype.Component; + +@Component +public class GetTasks implements GetAllTasks { + + private TaskService taskService; + + public GetTasks(TaskService taskService) { + this.taskService = taskService; + } + + @Override + public Iterable getAll() { + return taskService.getAllTasks(); + } +}; diff --git a/architecture/src/main/java/com/baeldung/architecture/commands/task/CreateTask.java b/architecture/src/main/java/com/baeldung/architecture/commands/task/CreateTask.java new file mode 100644 index 0000000000..26e6da10e2 --- /dev/null +++ b/architecture/src/main/java/com/baeldung/architecture/commands/task/CreateTask.java @@ -0,0 +1,7 @@ +package com.baeldung.architecture.commands.task; + +import com.baeldung.architecture.domain.task.Task; + +public interface CreateTask { + public void create(Task newTask); +}; diff --git a/architecture/src/main/java/com/baeldung/architecture/commands/task/GetAllTasks.java b/architecture/src/main/java/com/baeldung/architecture/commands/task/GetAllTasks.java new file mode 100644 index 0000000000..d3c40db92f --- /dev/null +++ b/architecture/src/main/java/com/baeldung/architecture/commands/task/GetAllTasks.java @@ -0,0 +1,7 @@ +package com.baeldung.architecture.commands.task; + +import com.baeldung.architecture.domain.task.Task; + +public interface GetAllTasks { + public Iterable getAll(); +}; diff --git a/architecture/src/main/java/com/baeldung/architecture/domain/task/Task.java b/architecture/src/main/java/com/baeldung/architecture/domain/task/Task.java new file mode 100644 index 0000000000..240dc33571 --- /dev/null +++ b/architecture/src/main/java/com/baeldung/architecture/domain/task/Task.java @@ -0,0 +1,53 @@ +package com.baeldung.architecture.domain.task; + +import java.time.Instant; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Task { + @Id + @GeneratedValue(strategy=GenerationType.AUTO) + private Long id; + private Instant dueDate = Instant.now(); + private String description; + + public Task() {} + + public Task(Instant dueDate, String description) { + this.dueDate = dueDate; + this.description = description; + } + + public Task(Long id, Instant dueDate, String description) { + this(dueDate, description); + this.id = id; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Instant getDueDate() { + return dueDate; + } + + public void setDueDate(Instant dueDate) { + this.dueDate = dueDate; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +} diff --git a/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskRepository.java b/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskRepository.java new file mode 100644 index 0000000000..d896212714 --- /dev/null +++ b/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.architecture.domain.task; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface TaskRepository extends CrudRepository {}; diff --git a/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskService.java b/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskService.java new file mode 100644 index 0000000000..cace0614ad --- /dev/null +++ b/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskService.java @@ -0,0 +1,22 @@ +package com.baeldung.architecture.domain.task; + +import org.springframework.stereotype.Service; + +@Service +public class TaskService { + + private TaskRepository taskRepository; + + public TaskService(TaskRepository taskRepository) { + this.taskRepository = taskRepository; + } + + public void createTask(Task task) { + taskRepository.save(task); + } + + public Iterable getAllTasks() { + return taskRepository.findAll(); + } + +}; diff --git a/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java b/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java new file mode 100644 index 0000000000..260c033b71 --- /dev/null +++ b/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java @@ -0,0 +1,25 @@ +package com.baeldung.architecture.framework.cli; + +import com.baeldung.architecture.application.task.AddNewDailyTask; +import com.baeldung.architecture.domain.task.Task; + +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +@Component +public class StartupRunner implements ApplicationRunner { + + AddNewDailyTask addNewDailyTask; + + public StartupRunner(AddNewDailyTask addNewDailyTask) { + this.addNewDailyTask = addNewDailyTask; + } + @Override + public void run(ApplicationArguments args) throws Exception { + System.out.println("Adding daily tasks"); + Task task = new Task(); + task.setDescription("Startup Task"); + addNewDailyTask.create(task); + } +} \ No newline at end of file diff --git a/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskApiController.java b/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskApiController.java new file mode 100644 index 0000000000..c6f7bff2dd --- /dev/null +++ b/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskApiController.java @@ -0,0 +1,42 @@ +package com.baeldung.architecture.framework.http.task; + +import java.time.Instant; + +import com.baeldung.architecture.application.task.AddNewTask; +import com.baeldung.architecture.application.task.GetTasks; +import com.baeldung.architecture.domain.task.Task; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("task") +public class TaskApiController { + + private AddNewTask addNewTask; + private GetTasks getTasks; + + public TaskApiController( + AddNewTask addNewTask, + GetTasks getTasks + ) { + this.addNewTask = addNewTask; + this.getTasks = getTasks; + } + + @GetMapping + Iterable listTasks() { + return getTasks.getAll(); + } + + @PostMapping(consumes = "application/json", produces = "application/json") + void createTask(@RequestBody TaskRequest taskRequest) { + Task task = new Task(); + task.setDescription(taskRequest.getDescription()); + task.setDueDate(Instant.parse(taskRequest.getDueDate())); + addNewTask.create(task); + } +} \ No newline at end of file diff --git a/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskRequest.java b/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskRequest.java new file mode 100644 index 0000000000..2e353b079a --- /dev/null +++ b/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskRequest.java @@ -0,0 +1,29 @@ +package com.baeldung.architecture.framework.http.task; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; + +public class TaskRequest { + @JsonInclude(Include.NON_NULL) + private String description; + + @JsonInclude(Include.NON_NULL) + private String dueDate; + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDueDate() { + return dueDate; + } + + public void setDueDate(String dueDate) { + this.dueDate = dueDate; + } + +} \ No newline at end of file From 616364afc443e2c4ae4c03e0b1f43f49b5a77483 Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Tue, 1 Oct 2019 20:15:39 -0400 Subject: [PATCH 010/150] Fixup styling --- .../architecture/HexagonalArchitectureTaskApplication.java | 6 +++--- .../baeldung/architecture/application/task/AddNewTask.java | 2 +- .../baeldung/architecture/application/task/GetTasks.java | 2 +- .../baeldung/architecture/framework/cli/StartupRunner.java | 1 - 4 files changed, 5 insertions(+), 6 deletions(-) diff --git a/architecture/src/main/java/com/baeldung/architecture/HexagonalArchitectureTaskApplication.java b/architecture/src/main/java/com/baeldung/architecture/HexagonalArchitectureTaskApplication.java index 83e4fc4c0b..69c6f4b276 100644 --- a/architecture/src/main/java/com/baeldung/architecture/HexagonalArchitectureTaskApplication.java +++ b/architecture/src/main/java/com/baeldung/architecture/HexagonalArchitectureTaskApplication.java @@ -5,8 +5,8 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class HexagonalArchitectureTaskApplication { - public static void main(String[] args) { - SpringApplication.run(HexagonalArchitectureTaskApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(HexagonalArchitectureTaskApplication.class, args); + } } diff --git a/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewTask.java b/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewTask.java index 2e5aff4a53..70638378f9 100644 --- a/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewTask.java +++ b/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewTask.java @@ -19,4 +19,4 @@ public class AddNewTask implements CreateTask { public void create(Task newTask) { taskService.createTask(newTask); } -}; +} diff --git a/architecture/src/main/java/com/baeldung/architecture/application/task/GetTasks.java b/architecture/src/main/java/com/baeldung/architecture/application/task/GetTasks.java index 54539290ba..c876f7de85 100644 --- a/architecture/src/main/java/com/baeldung/architecture/application/task/GetTasks.java +++ b/architecture/src/main/java/com/baeldung/architecture/application/task/GetTasks.java @@ -19,4 +19,4 @@ public class GetTasks implements GetAllTasks { public Iterable getAll() { return taskService.getAllTasks(); } -}; +} diff --git a/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java b/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java index 260c033b71..cf38e5ee5e 100644 --- a/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java +++ b/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java @@ -17,7 +17,6 @@ public class StartupRunner implements ApplicationRunner { } @Override public void run(ApplicationArguments args) throws Exception { - System.out.println("Adding daily tasks"); Task task = new Task(); task.setDescription("Startup Task"); addNewDailyTask.create(task); From 646bd45c1824071ae5d17bae82799a89de69929e Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Tue, 1 Oct 2019 20:15:39 -0400 Subject: [PATCH 011/150] Fixup styling --- .../architecture/application/task/AddNewDailyTask.java | 2 +- .../com/baeldung/architecture/commands/task/CreateTask.java | 2 +- .../com/baeldung/architecture/commands/task/GetAllTasks.java | 2 +- .../com/baeldung/architecture/domain/task/TaskService.java | 2 +- .../com/baeldung/architecture/framework/cli/StartupRunner.java | 2 +- .../architecture/framework/http/task/TaskApiController.java | 2 +- .../baeldung/architecture/framework/http/task/TaskRequest.java | 3 +-- 7 files changed, 7 insertions(+), 8 deletions(-) diff --git a/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewDailyTask.java b/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewDailyTask.java index 208d1bfcc9..f9ee97542c 100644 --- a/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewDailyTask.java +++ b/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewDailyTask.java @@ -26,4 +26,4 @@ public class AddNewDailyTask implements CreateTask { addNewTask.create(task); } } -}; +} diff --git a/architecture/src/main/java/com/baeldung/architecture/commands/task/CreateTask.java b/architecture/src/main/java/com/baeldung/architecture/commands/task/CreateTask.java index 26e6da10e2..ec60868a22 100644 --- a/architecture/src/main/java/com/baeldung/architecture/commands/task/CreateTask.java +++ b/architecture/src/main/java/com/baeldung/architecture/commands/task/CreateTask.java @@ -4,4 +4,4 @@ import com.baeldung.architecture.domain.task.Task; public interface CreateTask { public void create(Task newTask); -}; +} diff --git a/architecture/src/main/java/com/baeldung/architecture/commands/task/GetAllTasks.java b/architecture/src/main/java/com/baeldung/architecture/commands/task/GetAllTasks.java index d3c40db92f..c9aa1be5f8 100644 --- a/architecture/src/main/java/com/baeldung/architecture/commands/task/GetAllTasks.java +++ b/architecture/src/main/java/com/baeldung/architecture/commands/task/GetAllTasks.java @@ -4,4 +4,4 @@ import com.baeldung.architecture.domain.task.Task; public interface GetAllTasks { public Iterable getAll(); -}; +} diff --git a/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskService.java b/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskService.java index cace0614ad..11ef0f3e19 100644 --- a/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskService.java +++ b/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskService.java @@ -19,4 +19,4 @@ public class TaskService { return taskRepository.findAll(); } -}; +} diff --git a/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java b/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java index cf38e5ee5e..449bc9386e 100644 --- a/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java +++ b/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java @@ -21,4 +21,4 @@ public class StartupRunner implements ApplicationRunner { task.setDescription("Startup Task"); addNewDailyTask.create(task); } -} \ No newline at end of file +} diff --git a/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskApiController.java b/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskApiController.java index c6f7bff2dd..87a8f5fe4b 100644 --- a/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskApiController.java +++ b/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskApiController.java @@ -39,4 +39,4 @@ public class TaskApiController { task.setDueDate(Instant.parse(taskRequest.getDueDate())); addNewTask.create(task); } -} \ No newline at end of file +} diff --git a/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskRequest.java b/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskRequest.java index 2e353b079a..70b98a32f9 100644 --- a/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskRequest.java +++ b/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskRequest.java @@ -25,5 +25,4 @@ public class TaskRequest { public void setDueDate(String dueDate) { this.dueDate = dueDate; } - -} \ No newline at end of file +} From 925a69b401f9817cce62e790435a5400c5eef7d1 Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Sat, 25 Apr 2020 07:01:34 -0400 Subject: [PATCH 012/150] Java example for Hibernate Types --- .../hibernate-types/.gitignore | 33 +++ persistence-modules/hibernate-types/README.md | 7 + .../hibernate-types/docker-compose.yml | 19 ++ .../docker-entrypoint-initdb.d/init-db.sql | 3 + .../docker/etc/mysql/conf.d/utf8.cnf | 7 + persistence-modules/hibernate-types/pom.xml | 214 ++++++++++++++++++ .../com/baeldung/hibernate/types/Album.java | 34 +++ .../hibernate/types/AlbumRepository.java | 8 + .../com/baeldung/hibernate/types/Artist.java | 72 ++++++ .../baeldung/hibernate/types/BaseEntity.java | 37 +++ .../baeldung/hibernate/types/CoverArt.java | 71 ++++++ .../types/HibernateTypesApplication.java | 13 ++ .../com/baeldung/hibernate/types/Song.java | 57 +++++ .../hibernate/types/SongRepository.java | 8 + .../src/main/resources/application.properties | 21 ++ .../main/resources/hibernate-types.properties | 1 + .../types/HibernateTypesIntegrationTest.java | 182 +++++++++++++++ persistence-modules/pom.xml | 1 + 18 files changed, 788 insertions(+) create mode 100644 persistence-modules/hibernate-types/.gitignore create mode 100644 persistence-modules/hibernate-types/README.md create mode 100644 persistence-modules/hibernate-types/docker-compose.yml create mode 100644 persistence-modules/hibernate-types/docker/docker-entrypoint-initdb.d/init-db.sql create mode 100644 persistence-modules/hibernate-types/docker/etc/mysql/conf.d/utf8.cnf create mode 100644 persistence-modules/hibernate-types/pom.xml create mode 100644 persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/Album.java create mode 100644 persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/AlbumRepository.java create mode 100644 persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/Artist.java create mode 100644 persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/BaseEntity.java create mode 100644 persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/CoverArt.java create mode 100644 persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/HibernateTypesApplication.java create mode 100644 persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/Song.java create mode 100644 persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/SongRepository.java create mode 100644 persistence-modules/hibernate-types/src/main/resources/application.properties create mode 100644 persistence-modules/hibernate-types/src/main/resources/hibernate-types.properties create mode 100644 persistence-modules/hibernate-types/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java diff --git a/persistence-modules/hibernate-types/.gitignore b/persistence-modules/hibernate-types/.gitignore new file mode 100644 index 0000000000..94b9c48616 --- /dev/null +++ b/persistence-modules/hibernate-types/.gitignore @@ -0,0 +1,33 @@ +.classpath +.project +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/persistence-modules/hibernate-types/README.md b/persistence-modules/hibernate-types/README.md new file mode 100644 index 0000000000..9d02d8c8f2 --- /dev/null +++ b/persistence-modules/hibernate-types/README.md @@ -0,0 +1,7 @@ +## Hibernate Types + +This module contains articles specific to use of Hibernate Types. + +### Relevant articles: + +- [A Guide to Hibernate Types Project](https://www.baeldung.com/a-guide-to-hibernate-types-project/) diff --git a/persistence-modules/hibernate-types/docker-compose.yml b/persistence-modules/hibernate-types/docker-compose.yml new file mode 100644 index 0000000000..3ea9fef2e7 --- /dev/null +++ b/persistence-modules/hibernate-types/docker-compose.yml @@ -0,0 +1,19 @@ +version: '3.2' + +services: + mysql: + image: mysql:5.7 + container_name: mysql57 + restart: unless-stopped + ports: + - 53306:3306 + environment: + - MYSQL_ALLOW_EMPTY_PASSWORD=true + volumes : + - ./docker/etc/mysql/conf.d:/etc/mysql/conf.d + - ./docker/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d + logging: + driver: "json-file" + options: + max-size: "50m" + max-file: "1" diff --git a/persistence-modules/hibernate-types/docker/docker-entrypoint-initdb.d/init-db.sql b/persistence-modules/hibernate-types/docker/docker-entrypoint-initdb.d/init-db.sql new file mode 100644 index 0000000000..1df234f5a1 --- /dev/null +++ b/persistence-modules/hibernate-types/docker/docker-entrypoint-initdb.d/init-db.sql @@ -0,0 +1,3 @@ +CREATE DATABASE hibernate_types; +use hibernate_types; +GRANT ALL PRIVILEGES ON hibernate_types.* TO 'mysql'@'%' IDENTIFIED BY 'admin'; diff --git a/persistence-modules/hibernate-types/docker/etc/mysql/conf.d/utf8.cnf b/persistence-modules/hibernate-types/docker/etc/mysql/conf.d/utf8.cnf new file mode 100644 index 0000000000..1885d83c8b --- /dev/null +++ b/persistence-modules/hibernate-types/docker/etc/mysql/conf.d/utf8.cnf @@ -0,0 +1,7 @@ +[mysqld] +init_connect='SET collation_connection = utf8_unicode_ci' +character-set-server = utf8 +collation-server = utf8_unicode_ci + +[client] +default-character-set = utf8 \ No newline at end of file diff --git a/persistence-modules/hibernate-types/pom.xml b/persistence-modules/hibernate-types/pom.xml new file mode 100644 index 0000000000..9fa5d66347 --- /dev/null +++ b/persistence-modules/hibernate-types/pom.xml @@ -0,0 +1,214 @@ + + + 4.0.0 + hibernate-types + 0.0.1-SNAPSHOT + hibernate-types + Introduction into hibernate types library + + + com.baeldung + persistence-modules + 1.0.0-SNAPSHOT + + + + + com.vladmihalcea + hibernate-types-52 + ${hibernate-types.version} + + + org.springframework.boot + spring-boot-starter-data-jpa + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + test + + + org.junit.vintage + junit-vintage-engine + + + + + org.springframework.boot + spring-boot-devtools + ${spring-boot.version} + runtime + true + + + org.hibernate + hibernate-core + ${hibernate.version} + provided + + + org.hibernate + hibernate-ehcache + ${hibernate.version} + test + + + org.hibernate + hibernate-testing + ${hibernate.version} + test + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + mysql + mysql-connector-java + ${mysql.version} + runtime + + + org.slf4j + slf4j-api + ${slf4j.version} + provided + true + + + ch.qos.logback + logback-classic + ${logback.version} + provided + true + + + javax.xml.bind + jaxb-api + ${jaxb.version} + + + org.javassist + javassist + ${javassist.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + provided + true + + + com.google.guava + guava + ${guava.version} + provided + true + + + net.ttddyy + datasource-proxy + ${datasource-proxy.version} + test + + + com.integralblue + log4jdbc-spring-boot-starter + ${log4jdbc.version} + + + + + hibernate-types + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-war-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.version} + + ${source.version} + ${target.version} + + + + org.apache.maven.plugins + maven-surefire-plugin + + 3 + true + + **/*IntegrationTest.java + + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*IntegrationTest.java + + + + + + + + + + + + 3.15.0 + 1.6 + 29.0-jre + 2.9.7 + 5.4.14.Final + 2.10.3 + 1.8 + 3.27.0-GA + 2.3.1 + 2.0.0 + 1.2.3 + 3.0.2 + 2.22.2 + 3.8.1 + 3.7.0 + 8.0.19 + 1.7.30 + 2.1.3.RELEASE + + + diff --git a/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/Album.java b/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/Album.java new file mode 100644 index 0000000000..f18818c3a9 --- /dev/null +++ b/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/Album.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.types; + +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.util.List; + +@Entity(name = "Album") +@Table(name = "album") +public class Album extends BaseEntity { + @Type(type = "json") + @Column(columnDefinition = "json") + private CoverArt coverArt; + + @OneToMany(fetch = FetchType.EAGER) + private List songs; + + public CoverArt getCoverArt() { + return coverArt; + } + + public void setCoverArt(CoverArt coverArt) { + this.coverArt = coverArt; + } + + + public List getSongs() { + return songs; + } + + public void setSong(List songs) { + this.songs = songs; + } +} diff --git a/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/AlbumRepository.java b/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/AlbumRepository.java new file mode 100644 index 0000000000..d89542de46 --- /dev/null +++ b/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/AlbumRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate.types; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface AlbumRepository extends CrudRepository { +} diff --git a/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/Artist.java b/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/Artist.java new file mode 100644 index 0000000000..8f3ccb44c5 --- /dev/null +++ b/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/Artist.java @@ -0,0 +1,72 @@ +package com.baeldung.hibernate.types; + +import java.io.Serializable; + +public class Artist implements Serializable { + + private String name; + private String country; + private String genre; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getGenre() { + return genre; + } + + public void setGenre(String genre) { + this.genre = genre; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((country == null) ? 0 : country.hashCode()); + result = prime * result + ((genre == null) ? 0 : genre.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Artist other = (Artist) obj; + if (country == null) { + if (other.country != null) + return false; + } else if (!country.equals(other.country)) + return false; + if (genre == null) { + if (other.genre != null) + return false; + } else if (!genre.equals(other.genre)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + } diff --git a/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/BaseEntity.java b/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/BaseEntity.java new file mode 100644 index 0000000000..3e0fbc7595 --- /dev/null +++ b/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/BaseEntity.java @@ -0,0 +1,37 @@ +package com.baeldung.hibernate.types; + +import com.vladmihalcea.hibernate.type.json.JsonBinaryType; +import com.vladmihalcea.hibernate.type.json.JsonStringType; +import org.hibernate.annotations.TypeDef; +import org.hibernate.annotations.TypeDefs; + +import javax.persistence.*; + +@TypeDefs({ + @TypeDef(name = "json", typeClass = JsonStringType.class), + @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class) +}) +@MappedSuperclass +public class BaseEntity { + @Id + @GeneratedValue(strategy=GenerationType.AUTO) + @Column(name = "id", unique = true, nullable = false) + long id; + String name; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/CoverArt.java b/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/CoverArt.java new file mode 100644 index 0000000000..bd71edc53c --- /dev/null +++ b/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/CoverArt.java @@ -0,0 +1,71 @@ +package com.baeldung.hibernate.types; + +import java.io.Serializable; + +public class CoverArt implements Serializable { + + private String frontCoverArtUrl; + private String backCoverArtUrl; + private String upcCode; + + public String getFrontCoverArtUrl() { + return frontCoverArtUrl; + } + + public void setFrontCoverArtUrl(String frontCoverArtUrl) { + this.frontCoverArtUrl = frontCoverArtUrl; + } + + public String getBackCoverArtUrl() { + return backCoverArtUrl; + } + + public void setBackCoverArtUrl(String backCoverArtUrl) { + this.backCoverArtUrl = backCoverArtUrl; + } + + public String getUpcCode() { + return upcCode; + } + + public void setUpcCode(String upcCode) { + this.upcCode = upcCode; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((backCoverArtUrl == null) ? 0 : backCoverArtUrl.hashCode()); + result = prime * result + ((frontCoverArtUrl == null) ? 0 : frontCoverArtUrl.hashCode()); + result = prime * result + ((upcCode == null) ? 0 : upcCode.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + CoverArt other = (CoverArt) obj; + if (backCoverArtUrl == null) { + if (other.backCoverArtUrl != null) + return false; + } else if (!backCoverArtUrl.equals(other.backCoverArtUrl)) + return false; + if (frontCoverArtUrl == null) { + if (other.frontCoverArtUrl != null) + return false; + } else if (!frontCoverArtUrl.equals(other.frontCoverArtUrl)) + return false; + if (upcCode == null) { + if (other.upcCode != null) + return false; + } else if (!upcCode.equals(other.upcCode)) + return false; + return true; + } +} diff --git a/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/HibernateTypesApplication.java b/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/HibernateTypesApplication.java new file mode 100644 index 0000000000..ac379f9ee2 --- /dev/null +++ b/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/HibernateTypesApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.hibernate.types; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class HibernateTypesApplication { + + public static void main(String[] args) { + SpringApplication.run(HibernateTypesApplication.class, args); + } + +} diff --git a/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/Song.java b/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/Song.java new file mode 100644 index 0000000000..2d22296024 --- /dev/null +++ b/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/Song.java @@ -0,0 +1,57 @@ +package com.baeldung.hibernate.types; + +import org.hibernate.annotations.Type; +import org.hibernate.annotations.TypeDef; + +import java.time.YearMonth; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; + +import com.vladmihalcea.hibernate.type.basic.YearMonthIntegerType; + +@Entity(name = "Song") +@Table(name = "song") +@TypeDef( + typeClass = YearMonthIntegerType.class, + defaultForType = YearMonth.class +) +public class Song extends BaseEntity { + + private Long length = 0L; + + @Type(type = "json") + @Column(columnDefinition = "json") + private Artist artist; + + @Column( + name = "recorded_on", + columnDefinition = "mediumint" + ) + private YearMonth recordedOn = YearMonth.now(); + + public Long getLength() { + return length; + } + + public void setLength(Long length) { + this.length = length; + } + + public Artist getArtist() { + return artist; + } + + public void setArtist(Artist artist) { + this.artist = artist; + } + + public YearMonth getRecordedOn() { + return recordedOn; + } + + public void setRecordedOn(YearMonth recordedOn) { + this.recordedOn = recordedOn; + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/SongRepository.java b/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/SongRepository.java new file mode 100644 index 0000000000..e79e88108b --- /dev/null +++ b/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/SongRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.hibernate.types; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface SongRepository extends CrudRepository { +} diff --git a/persistence-modules/hibernate-types/src/main/resources/application.properties b/persistence-modules/hibernate-types/src/main/resources/application.properties new file mode 100644 index 0000000000..bcd21578dd --- /dev/null +++ b/persistence-modules/hibernate-types/src/main/resources/application.properties @@ -0,0 +1,21 @@ +log4jdbc.dump.sql.addsemicolon=true +log4jdbc.dump.sql.maxlinelength=0 +log4jdbc.trim.sql.extrablanklines=false +logging.level.jdbc.audit=fatal +logging.level.jdbc.connection=fatal +logging.level.jdbc.resultset=fatal +logging.level.jdbc.resultsettable=info +logging.level.jdbc.sqlonly=fatal +logging.level.jdbc.sqltiming=info +# logging.level.org.hibernate.SQL=DEBUG +# logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE +# logging.level.org.hibernate.type.descriptor.sql=trace +# logging.level.org.springframework.jdbc.core.JdbcTemplate=DEBUG +# logging.level.org.springframework.jdbc.core.StatementCreatorUtils=TRACE +spring.datasource.url=jdbc:mysql://localhost:53306/hibernate_types?serverTimezone=UTC&useSSL=false +spring.datasource.username=root +spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect +spring.jpa.hibernate.ddl-auto=create +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect +# spring.jpa.properties.hibernate.format_sql=false +# spring.jpa.show-sql=false \ No newline at end of file diff --git a/persistence-modules/hibernate-types/src/main/resources/hibernate-types.properties b/persistence-modules/hibernate-types/src/main/resources/hibernate-types.properties new file mode 100644 index 0000000000..226b50fafd --- /dev/null +++ b/persistence-modules/hibernate-types/src/main/resources/hibernate-types.properties @@ -0,0 +1 @@ +hibernate.types.print.banner=false diff --git a/persistence-modules/hibernate-types/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java b/persistence-modules/hibernate-types/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java new file mode 100644 index 0000000000..cf3c34777e --- /dev/null +++ b/persistence-modules/hibernate-types/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java @@ -0,0 +1,182 @@ +package com.baeldung.hibernate.types; + +import com.google.common.collect.Lists; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.time.Duration; +import java.time.YearMonth; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +public class HibernateTypesIntegrationTest { + + @Autowired + AlbumRepository albumRepository; + + @Autowired + SongRepository songRepository; + + private void deleteAll() { + albumRepository.deleteAll(); + songRepository.deleteAll(); + } + + @BeforeEach + public void setUp() { + deleteAll(); + } + + @BeforeEach + public void tearDown() { + setUp(); + } + + + @Test + void hibernateTypeJsonTest() { + Album nullAlbum = new Album(); + nullAlbum = albumRepository.save(nullAlbum); + + Song nullSong = new Song(); + nullSong = songRepository.save(nullSong); + + Artist artist0 = new Artist(); + artist0.setCountry("England"); + artist0.setGenre("Pop"); + artist0.setName("Superstar"); + + Song song0 = new Song(); + song0.setArtist(artist0); + song0.setName("A Happy Song"); + song0.setLength(Duration.ofMinutes(4).getSeconds()); + song0 = songRepository.save(song0); + + Song song1 = new Song(); + song1.setArtist(artist0); + song1.setName("A Sad Song"); + song1.setLength(Duration.ofMinutes(2).getSeconds()); + song1 = songRepository.save(song1); + + Song song2 = new Song(); + song2.setArtist(artist0); + song2.setName("Another Happy Song"); + song2.setLength(Duration.ofMinutes(3).getSeconds()); + song2 = songRepository.save(song2); + + Artist artist1 = new Artist(); + artist1.setCountry("Jamaica"); + artist1.setGenre("Reggae"); + artist1.setName("Newcomer"); + + Song song3 = new Song(); + song3.setArtist(artist1); + song3.setName("A New Song"); + song3.setLength(Duration.ofMinutes(5).getSeconds()); + song3 = songRepository.save(song3); + + CoverArt album0CoverArt = new CoverArt(); + album0CoverArt.setUpcCode(UUID.randomUUID().toString()); + album0CoverArt.setFrontCoverArtUrl("http://fakeurl-0"); + album0CoverArt.setBackCoverArtUrl("http://fakeurl-1"); + + Album album0 = new Album(); + album0.setCoverArt(album0CoverArt); + album0.setName("Album 0"); + album0.setSong(Lists.newArrayList(song0, song1, song2)); + album0 = albumRepository.save(album0); + + CoverArt album1CoverArt = new CoverArt(); + album1CoverArt.setUpcCode(UUID.randomUUID().toString()); + album1CoverArt.setFrontCoverArtUrl("http://fakeurl-2"); + album1CoverArt.setBackCoverArtUrl("http://fakeurl-3"); + + Album album1 = new Album(); + album1.setCoverArt(album1CoverArt); + album1.setName("Album 1"); + album1.setSong(Lists.newArrayList(song3)); + albumRepository.save(album1); + + Iterable queryAlbumsResult = albumRepository.findAll(); + assertThat(queryAlbumsResult).hasSize(3); + + Iterable querySongsResult = songRepository.findAll(); + assertThat(querySongsResult).hasSize(5); + + Album queryAlbumResult; + + queryAlbumResult = albumRepository.findById(nullAlbum.getId()).get(); + assertThat(queryAlbumResult.getName()).isNull(); + assertThat(queryAlbumResult.getCoverArt()).isNull(); + assertThat(queryAlbumResult.getSongs()).isNullOrEmpty(); + + queryAlbumResult = albumRepository.findById(album0.getId()).get(); + assertThat(queryAlbumResult.getName()).isEqualTo("Album 0"); + assertThat(queryAlbumResult.getCoverArt().getFrontCoverArtUrl()).isEqualTo("http://fakeurl-0"); + assertThat(queryAlbumResult.getCoverArt().getBackCoverArtUrl()).isEqualTo("http://fakeurl-1"); + assertThat(queryAlbumResult.getSongs()).hasSize(3); + assertThat(queryAlbumResult.getSongs()).usingFieldByFieldElementComparator().containsExactlyInAnyOrder(song0, song1, song2); + + queryAlbumResult = albumRepository.findById(album1.getId()).get(); + assertThat(queryAlbumResult.getName()).isEqualTo("Album 1"); + assertThat(queryAlbumResult.getCoverArt().getFrontCoverArtUrl()).isEqualTo("http://fakeurl-2"); + assertThat(queryAlbumResult.getCoverArt().getBackCoverArtUrl()).isEqualTo("http://fakeurl-3"); + assertThat(queryAlbumResult.getSongs()).hasSize(1); + assertThat(queryAlbumResult.getSongs()).usingFieldByFieldElementComparator().containsExactlyInAnyOrder(song3); + + Song querySongResult; + + querySongResult = songRepository.findById(nullSong.getId()).get(); + assertThat(querySongResult.getName()).isNull(); + assertThat(querySongResult.getLength()).isZero(); + assertThat(querySongResult.getArtist()).isNull(); + + querySongResult = songRepository.findById(song0.getId()).get(); + assertThat(querySongResult.getName()).isEqualTo("A Happy Song"); + assertThat(querySongResult.getLength()).isEqualTo(Duration.ofMinutes(4).getSeconds()); + assertThat(querySongResult.getArtist().getName()).isEqualTo("Superstar"); + assertThat(querySongResult.getArtist().getGenre()).isEqualTo("Pop"); + assertThat(querySongResult.getArtist().getCountry()).isEqualTo("England"); + + querySongResult = songRepository.findById(song1.getId()).get(); + assertThat(querySongResult.getName()).isEqualTo("A Sad Song"); + assertThat(querySongResult.getLength()).isEqualTo(Duration.ofMinutes(2).getSeconds()); + assertThat(querySongResult.getArtist().getName()).isEqualTo("Superstar"); + assertThat(querySongResult.getArtist().getGenre()).isEqualTo("Pop"); + assertThat(querySongResult.getArtist().getCountry()).isEqualTo("England"); + + querySongResult = songRepository.findById(song2.getId()).get(); + assertThat(querySongResult.getName()).isEqualTo("Another Happy Song"); + assertThat(querySongResult.getLength()).isEqualTo(Duration.ofMinutes(3).getSeconds()); + assertThat(querySongResult.getArtist().getName()).isEqualTo("Superstar"); + assertThat(querySongResult.getArtist().getGenre()).isEqualTo("Pop"); + assertThat(querySongResult.getArtist().getCountry()).isEqualTo("England"); + + querySongResult = songRepository.findById(song3.getId()).get(); + assertThat(querySongResult.getName()).isEqualTo("A New Song"); + assertThat(querySongResult.getLength()).isEqualTo(Duration.ofMinutes(5).getSeconds()); + assertThat(querySongResult.getArtist().getName()).isEqualTo("Newcomer"); + assertThat(querySongResult.getArtist().getGenre()).isEqualTo("Reggae"); + assertThat(querySongResult.getArtist().getCountry()).isEqualTo("Jamaica"); + } + + @Test + void hibernateTypeYearMonthTest() { + Song mySong = new Song(); + YearMonth now = YearMonth.of(2019, 12); + mySong.setArtist(new Artist()); + mySong.setName("My Song"); + mySong.setLength(Duration.ofMinutes(1).getSeconds()); + mySong.setRecordedOn(now); + mySong = songRepository.save(mySong); + + Song queryResult; + queryResult = songRepository.findById(mySong.getId()).get(); + assertThat(queryResult.getRecordedOn().getYear()).isEqualTo(2019); + assertThat(queryResult.getRecordedOn().getMonthValue()).isEqualTo(12); + } +} diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index ec7f0bcec2..4d39b2d98b 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -24,6 +24,7 @@ hibernate-mapping hibernate-ogm hibernate-annotations + hibernate-types hibernate-jpa hibernate-queries hibernate-enterprise From 4426454a9aa71e43def26b27e0912c84ad06b0f4 Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Sat, 25 Apr 2020 07:42:28 -0400 Subject: [PATCH 013/150] Fixup variable names --- .../types/HibernateTypesIntegrationTest.java | 212 +++++++++--------- 1 file changed, 106 insertions(+), 106 deletions(-) diff --git a/persistence-modules/hibernate-types/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java b/persistence-modules/hibernate-types/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java index cf3c34777e..af28eadfb8 100644 --- a/persistence-modules/hibernate-types/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java +++ b/persistence-modules/hibernate-types/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java @@ -38,134 +38,134 @@ public class HibernateTypesIntegrationTest { @Test - void hibernateTypeJsonTest() { - Album nullAlbum = new Album(); - nullAlbum = albumRepository.save(nullAlbum); + void whenSavingHibernateTypes_thenTheCorrectJsonIsStoredInTheDatabase() { + Album emptyAlbum = new Album(); + emptyAlbum = albumRepository.save(emptyAlbum); - Song nullSong = new Song(); - nullSong = songRepository.save(nullSong); + Song emptySong = new Song(); + emptySong = songRepository.save(emptySong); - Artist artist0 = new Artist(); - artist0.setCountry("England"); - artist0.setGenre("Pop"); - artist0.setName("Superstar"); + Artist superstarArtist = new Artist(); + superstarArtist.setCountry("England"); + superstarArtist.setGenre("Pop"); + superstarArtist.setName("Superstar"); - Song song0 = new Song(); - song0.setArtist(artist0); - song0.setName("A Happy Song"); - song0.setLength(Duration.ofMinutes(4).getSeconds()); - song0 = songRepository.save(song0); + Song aHappySong = new Song(); + aHappySong.setArtist(superstarArtist); + aHappySong.setName("A Happy Song"); + aHappySong.setLength(Duration.ofMinutes(4).getSeconds()); + aHappySong = songRepository.save(aHappySong); - Song song1 = new Song(); - song1.setArtist(artist0); - song1.setName("A Sad Song"); - song1.setLength(Duration.ofMinutes(2).getSeconds()); - song1 = songRepository.save(song1); + Song aSadSong = new Song(); + aSadSong.setArtist(superstarArtist); + aSadSong.setName("A Sad Song"); + aSadSong.setLength(Duration.ofMinutes(2).getSeconds()); + aSadSong = songRepository.save(aSadSong); - Song song2 = new Song(); - song2.setArtist(artist0); - song2.setName("Another Happy Song"); - song2.setLength(Duration.ofMinutes(3).getSeconds()); - song2 = songRepository.save(song2); + Song anotherHappySong = new Song(); + anotherHappySong.setArtist(superstarArtist); + anotherHappySong.setName("Another Happy Song"); + anotherHappySong.setLength(Duration.ofMinutes(3).getSeconds()); + anotherHappySong = songRepository.save(anotherHappySong); - Artist artist1 = new Artist(); - artist1.setCountry("Jamaica"); - artist1.setGenre("Reggae"); - artist1.setName("Newcomer"); + Artist newcomer = new Artist(); + newcomer.setCountry("Jamaica"); + newcomer.setGenre("Reggae"); + newcomer.setName("Newcomer"); - Song song3 = new Song(); - song3.setArtist(artist1); - song3.setName("A New Song"); - song3.setLength(Duration.ofMinutes(5).getSeconds()); - song3 = songRepository.save(song3); + Song aNewSong = new Song(); + aNewSong.setArtist(newcomer); + aNewSong.setName("A New Song"); + aNewSong.setLength(Duration.ofMinutes(5).getSeconds()); + aNewSong = songRepository.save(aNewSong); - CoverArt album0CoverArt = new CoverArt(); - album0CoverArt.setUpcCode(UUID.randomUUID().toString()); - album0CoverArt.setFrontCoverArtUrl("http://fakeurl-0"); - album0CoverArt.setBackCoverArtUrl("http://fakeurl-1"); + CoverArt superstarAlbumCoverArt = new CoverArt(); + superstarAlbumCoverArt.setUpcCode(UUID.randomUUID().toString()); + superstarAlbumCoverArt.setFrontCoverArtUrl("http://fakeurl-0"); + superstarAlbumCoverArt.setBackCoverArtUrl("http://fakeurl-1"); - Album album0 = new Album(); - album0.setCoverArt(album0CoverArt); - album0.setName("Album 0"); - album0.setSong(Lists.newArrayList(song0, song1, song2)); - album0 = albumRepository.save(album0); + Album superstarAlbum = new Album(); + superstarAlbum.setCoverArt(superstarAlbumCoverArt); + superstarAlbum.setName("The Superstar Album"); + superstarAlbum.setSong(Lists.newArrayList(aHappySong, aSadSong, anotherHappySong)); + superstarAlbum = albumRepository.save(superstarAlbum); - CoverArt album1CoverArt = new CoverArt(); - album1CoverArt.setUpcCode(UUID.randomUUID().toString()); - album1CoverArt.setFrontCoverArtUrl("http://fakeurl-2"); - album1CoverArt.setBackCoverArtUrl("http://fakeurl-3"); + CoverArt newcomerAlbumCoverArt = new CoverArt(); + newcomerAlbumCoverArt.setUpcCode(UUID.randomUUID().toString()); + newcomerAlbumCoverArt.setFrontCoverArtUrl("http://fakeurl-2"); + newcomerAlbumCoverArt.setBackCoverArtUrl("http://fakeurl-3"); - Album album1 = new Album(); - album1.setCoverArt(album1CoverArt); - album1.setName("Album 1"); - album1.setSong(Lists.newArrayList(song3)); - albumRepository.save(album1); + Album newcomerAlbum = new Album(); + newcomerAlbum.setCoverArt(newcomerAlbumCoverArt); + newcomerAlbum.setName("The Newcomer Album"); + newcomerAlbum.setSong(Lists.newArrayList(aNewSong)); + albumRepository.save(newcomerAlbum); - Iterable queryAlbumsResult = albumRepository.findAll(); - assertThat(queryAlbumsResult).hasSize(3); + Iterable selectAlbumsQueryResult = albumRepository.findAll(); + assertThat(selectAlbumsQueryResult).hasSize(3); - Iterable querySongsResult = songRepository.findAll(); - assertThat(querySongsResult).hasSize(5); + Iterable selectSongsQueryResult = songRepository.findAll(); + assertThat(selectSongsQueryResult).hasSize(5); - Album queryAlbumResult; + Album selectAlbumQueryResult; - queryAlbumResult = albumRepository.findById(nullAlbum.getId()).get(); - assertThat(queryAlbumResult.getName()).isNull(); - assertThat(queryAlbumResult.getCoverArt()).isNull(); - assertThat(queryAlbumResult.getSongs()).isNullOrEmpty(); + selectAlbumQueryResult = albumRepository.findById(emptyAlbum.getId()).get(); + assertThat(selectAlbumQueryResult.getName()).isNull(); + assertThat(selectAlbumQueryResult.getCoverArt()).isNull(); + assertThat(selectAlbumQueryResult.getSongs()).isNullOrEmpty(); - queryAlbumResult = albumRepository.findById(album0.getId()).get(); - assertThat(queryAlbumResult.getName()).isEqualTo("Album 0"); - assertThat(queryAlbumResult.getCoverArt().getFrontCoverArtUrl()).isEqualTo("http://fakeurl-0"); - assertThat(queryAlbumResult.getCoverArt().getBackCoverArtUrl()).isEqualTo("http://fakeurl-1"); - assertThat(queryAlbumResult.getSongs()).hasSize(3); - assertThat(queryAlbumResult.getSongs()).usingFieldByFieldElementComparator().containsExactlyInAnyOrder(song0, song1, song2); + selectAlbumQueryResult = albumRepository.findById(superstarAlbum.getId()).get(); + assertThat(selectAlbumQueryResult.getName()).isEqualTo("Album 0"); + assertThat(selectAlbumQueryResult.getCoverArt().getFrontCoverArtUrl()).isEqualTo("http://fakeurl-0"); + assertThat(selectAlbumQueryResult.getCoverArt().getBackCoverArtUrl()).isEqualTo("http://fakeurl-1"); + assertThat(selectAlbumQueryResult.getSongs()).hasSize(3); + assertThat(selectAlbumQueryResult.getSongs()).usingFieldByFieldElementComparator().containsExactlyInAnyOrder(aHappySong, aSadSong, anotherHappySong); - queryAlbumResult = albumRepository.findById(album1.getId()).get(); - assertThat(queryAlbumResult.getName()).isEqualTo("Album 1"); - assertThat(queryAlbumResult.getCoverArt().getFrontCoverArtUrl()).isEqualTo("http://fakeurl-2"); - assertThat(queryAlbumResult.getCoverArt().getBackCoverArtUrl()).isEqualTo("http://fakeurl-3"); - assertThat(queryAlbumResult.getSongs()).hasSize(1); - assertThat(queryAlbumResult.getSongs()).usingFieldByFieldElementComparator().containsExactlyInAnyOrder(song3); + selectAlbumQueryResult = albumRepository.findById(superstarAlbum.getId()).get(); + assertThat(selectAlbumQueryResult.getName()).isEqualTo("Album 1"); + assertThat(selectAlbumQueryResult.getCoverArt().getFrontCoverArtUrl()).isEqualTo("http://fakeurl-2"); + assertThat(selectAlbumQueryResult.getCoverArt().getBackCoverArtUrl()).isEqualTo("http://fakeurl-3"); + assertThat(selectAlbumQueryResult.getSongs()).hasSize(1); + assertThat(selectAlbumQueryResult.getSongs()).usingFieldByFieldElementComparator().containsExactlyInAnyOrder(aNewSong); - Song querySongResult; + Song selectSongQueryResult; - querySongResult = songRepository.findById(nullSong.getId()).get(); - assertThat(querySongResult.getName()).isNull(); - assertThat(querySongResult.getLength()).isZero(); - assertThat(querySongResult.getArtist()).isNull(); + selectSongQueryResult = songRepository.findById(emptySong.getId()).get(); + assertThat(selectSongQueryResult.getName()).isNull(); + assertThat(selectSongQueryResult.getLength()).isZero(); + assertThat(selectSongQueryResult.getArtist()).isNull(); - querySongResult = songRepository.findById(song0.getId()).get(); - assertThat(querySongResult.getName()).isEqualTo("A Happy Song"); - assertThat(querySongResult.getLength()).isEqualTo(Duration.ofMinutes(4).getSeconds()); - assertThat(querySongResult.getArtist().getName()).isEqualTo("Superstar"); - assertThat(querySongResult.getArtist().getGenre()).isEqualTo("Pop"); - assertThat(querySongResult.getArtist().getCountry()).isEqualTo("England"); + selectSongQueryResult = songRepository.findById(aHappySong.getId()).get(); + assertThat(selectSongQueryResult.getName()).isEqualTo("A Happy Song"); + assertThat(selectSongQueryResult.getLength()).isEqualTo(Duration.ofMinutes(4).getSeconds()); + assertThat(selectSongQueryResult.getArtist().getName()).isEqualTo("Superstar"); + assertThat(selectSongQueryResult.getArtist().getGenre()).isEqualTo("Pop"); + assertThat(selectSongQueryResult.getArtist().getCountry()).isEqualTo("England"); - querySongResult = songRepository.findById(song1.getId()).get(); - assertThat(querySongResult.getName()).isEqualTo("A Sad Song"); - assertThat(querySongResult.getLength()).isEqualTo(Duration.ofMinutes(2).getSeconds()); - assertThat(querySongResult.getArtist().getName()).isEqualTo("Superstar"); - assertThat(querySongResult.getArtist().getGenre()).isEqualTo("Pop"); - assertThat(querySongResult.getArtist().getCountry()).isEqualTo("England"); + selectSongQueryResult = songRepository.findById(aSadSong.getId()).get(); + assertThat(selectSongQueryResult.getName()).isEqualTo("A Sad Song"); + assertThat(selectSongQueryResult.getLength()).isEqualTo(Duration.ofMinutes(2).getSeconds()); + assertThat(selectSongQueryResult.getArtist().getName()).isEqualTo("Superstar"); + assertThat(selectSongQueryResult.getArtist().getGenre()).isEqualTo("Pop"); + assertThat(selectSongQueryResult.getArtist().getCountry()).isEqualTo("England"); - querySongResult = songRepository.findById(song2.getId()).get(); - assertThat(querySongResult.getName()).isEqualTo("Another Happy Song"); - assertThat(querySongResult.getLength()).isEqualTo(Duration.ofMinutes(3).getSeconds()); - assertThat(querySongResult.getArtist().getName()).isEqualTo("Superstar"); - assertThat(querySongResult.getArtist().getGenre()).isEqualTo("Pop"); - assertThat(querySongResult.getArtist().getCountry()).isEqualTo("England"); + selectSongQueryResult = songRepository.findById(anotherHappySong.getId()).get(); + assertThat(selectSongQueryResult.getName()).isEqualTo("Another Happy Song"); + assertThat(selectSongQueryResult.getLength()).isEqualTo(Duration.ofMinutes(3).getSeconds()); + assertThat(selectSongQueryResult.getArtist().getName()).isEqualTo("Superstar"); + assertThat(selectSongQueryResult.getArtist().getGenre()).isEqualTo("Pop"); + assertThat(selectSongQueryResult.getArtist().getCountry()).isEqualTo("England"); - querySongResult = songRepository.findById(song3.getId()).get(); - assertThat(querySongResult.getName()).isEqualTo("A New Song"); - assertThat(querySongResult.getLength()).isEqualTo(Duration.ofMinutes(5).getSeconds()); - assertThat(querySongResult.getArtist().getName()).isEqualTo("Newcomer"); - assertThat(querySongResult.getArtist().getGenre()).isEqualTo("Reggae"); - assertThat(querySongResult.getArtist().getCountry()).isEqualTo("Jamaica"); + selectSongQueryResult = songRepository.findById(aNewSong.getId()).get(); + assertThat(selectSongQueryResult.getName()).isEqualTo("A New Song"); + assertThat(selectSongQueryResult.getLength()).isEqualTo(Duration.ofMinutes(5).getSeconds()); + assertThat(selectSongQueryResult.getArtist().getName()).isEqualTo("Newcomer"); + assertThat(selectSongQueryResult.getArtist().getGenre()).isEqualTo("Reggae"); + assertThat(selectSongQueryResult.getArtist().getCountry()).isEqualTo("Jamaica"); } @Test - void hibernateTypeYearMonthTest() { + void whenSavingAHibernateTypeYearMonth_thenTheCorrectValueIsStoredInTheDatabase() { Song mySong = new Song(); YearMonth now = YearMonth.of(2019, 12); mySong.setArtist(new Artist()); @@ -174,9 +174,9 @@ public class HibernateTypesIntegrationTest { mySong.setRecordedOn(now); mySong = songRepository.save(mySong); - Song queryResult; - queryResult = songRepository.findById(mySong.getId()).get(); - assertThat(queryResult.getRecordedOn().getYear()).isEqualTo(2019); - assertThat(queryResult.getRecordedOn().getMonthValue()).isEqualTo(12); + Song selectSongQueryResult; + selectSongQueryResult = songRepository.findById(mySong.getId()).get(); + assertThat(selectSongQueryResult.getRecordedOn().getYear()).isEqualTo(2019); + assertThat(selectSongQueryResult.getRecordedOn().getMonthValue()).isEqualTo(12); } } From a667a0191a4bc099ce92e1acf09455412938f073 Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Sat, 25 Apr 2020 07:48:01 -0400 Subject: [PATCH 014/150] Fix integration test --- .../hibernate/types/HibernateTypesIntegrationTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/persistence-modules/hibernate-types/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java b/persistence-modules/hibernate-types/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java index af28eadfb8..08d4cf919d 100644 --- a/persistence-modules/hibernate-types/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java +++ b/persistence-modules/hibernate-types/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java @@ -115,14 +115,14 @@ public class HibernateTypesIntegrationTest { assertThat(selectAlbumQueryResult.getSongs()).isNullOrEmpty(); selectAlbumQueryResult = albumRepository.findById(superstarAlbum.getId()).get(); - assertThat(selectAlbumQueryResult.getName()).isEqualTo("Album 0"); + assertThat(selectAlbumQueryResult.getName()).isEqualTo("The Superstar Album"); assertThat(selectAlbumQueryResult.getCoverArt().getFrontCoverArtUrl()).isEqualTo("http://fakeurl-0"); assertThat(selectAlbumQueryResult.getCoverArt().getBackCoverArtUrl()).isEqualTo("http://fakeurl-1"); assertThat(selectAlbumQueryResult.getSongs()).hasSize(3); assertThat(selectAlbumQueryResult.getSongs()).usingFieldByFieldElementComparator().containsExactlyInAnyOrder(aHappySong, aSadSong, anotherHappySong); - selectAlbumQueryResult = albumRepository.findById(superstarAlbum.getId()).get(); - assertThat(selectAlbumQueryResult.getName()).isEqualTo("Album 1"); + selectAlbumQueryResult = albumRepository.findById(newcomerAlbum.getId()).get(); + assertThat(selectAlbumQueryResult.getName()).isEqualTo("The Newcomer Album"); assertThat(selectAlbumQueryResult.getCoverArt().getFrontCoverArtUrl()).isEqualTo("http://fakeurl-2"); assertThat(selectAlbumQueryResult.getCoverArt().getBackCoverArtUrl()).isEqualTo("http://fakeurl-3"); assertThat(selectAlbumQueryResult.getSongs()).hasSize(1); From dc3f7039cb7c38e4ef07fdcb6d09de265fbc07df Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Sat, 25 Apr 2020 13:41:10 -0400 Subject: [PATCH 015/150] Revert "Fixup styling" This reverts commit 72addaf8c354879197e0c252e4d8153cc54e0e2c. --- .../architecture/application/task/AddNewDailyTask.java | 2 +- .../com/baeldung/architecture/commands/task/CreateTask.java | 2 +- .../com/baeldung/architecture/commands/task/GetAllTasks.java | 2 +- .../com/baeldung/architecture/domain/task/TaskService.java | 2 +- .../com/baeldung/architecture/framework/cli/StartupRunner.java | 2 +- .../architecture/framework/http/task/TaskApiController.java | 2 +- .../baeldung/architecture/framework/http/task/TaskRequest.java | 3 ++- 7 files changed, 8 insertions(+), 7 deletions(-) diff --git a/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewDailyTask.java b/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewDailyTask.java index f9ee97542c..208d1bfcc9 100644 --- a/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewDailyTask.java +++ b/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewDailyTask.java @@ -26,4 +26,4 @@ public class AddNewDailyTask implements CreateTask { addNewTask.create(task); } } -} +}; diff --git a/architecture/src/main/java/com/baeldung/architecture/commands/task/CreateTask.java b/architecture/src/main/java/com/baeldung/architecture/commands/task/CreateTask.java index ec60868a22..26e6da10e2 100644 --- a/architecture/src/main/java/com/baeldung/architecture/commands/task/CreateTask.java +++ b/architecture/src/main/java/com/baeldung/architecture/commands/task/CreateTask.java @@ -4,4 +4,4 @@ import com.baeldung.architecture.domain.task.Task; public interface CreateTask { public void create(Task newTask); -} +}; diff --git a/architecture/src/main/java/com/baeldung/architecture/commands/task/GetAllTasks.java b/architecture/src/main/java/com/baeldung/architecture/commands/task/GetAllTasks.java index c9aa1be5f8..d3c40db92f 100644 --- a/architecture/src/main/java/com/baeldung/architecture/commands/task/GetAllTasks.java +++ b/architecture/src/main/java/com/baeldung/architecture/commands/task/GetAllTasks.java @@ -4,4 +4,4 @@ import com.baeldung.architecture.domain.task.Task; public interface GetAllTasks { public Iterable getAll(); -} +}; diff --git a/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskService.java b/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskService.java index 11ef0f3e19..cace0614ad 100644 --- a/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskService.java +++ b/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskService.java @@ -19,4 +19,4 @@ public class TaskService { return taskRepository.findAll(); } -} +}; diff --git a/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java b/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java index 449bc9386e..cf38e5ee5e 100644 --- a/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java +++ b/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java @@ -21,4 +21,4 @@ public class StartupRunner implements ApplicationRunner { task.setDescription("Startup Task"); addNewDailyTask.create(task); } -} +} \ No newline at end of file diff --git a/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskApiController.java b/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskApiController.java index 87a8f5fe4b..c6f7bff2dd 100644 --- a/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskApiController.java +++ b/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskApiController.java @@ -39,4 +39,4 @@ public class TaskApiController { task.setDueDate(Instant.parse(taskRequest.getDueDate())); addNewTask.create(task); } -} +} \ No newline at end of file diff --git a/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskRequest.java b/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskRequest.java index 70b98a32f9..2e353b079a 100644 --- a/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskRequest.java +++ b/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskRequest.java @@ -25,4 +25,5 @@ public class TaskRequest { public void setDueDate(String dueDate) { this.dueDate = dueDate; } -} + +} \ No newline at end of file From a2efde1d8707cb85898c6fb0eb5321ab0dce392d Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Sat, 25 Apr 2020 13:41:33 -0400 Subject: [PATCH 016/150] Revert "Fixup styling" This reverts commit 6cb35dd535bfddad1243feaae2f3d2af0dc932d7. --- .../architecture/HexagonalArchitectureTaskApplication.java | 6 +++--- .../baeldung/architecture/application/task/AddNewTask.java | 2 +- .../baeldung/architecture/application/task/GetTasks.java | 2 +- .../baeldung/architecture/framework/cli/StartupRunner.java | 1 + 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/architecture/src/main/java/com/baeldung/architecture/HexagonalArchitectureTaskApplication.java b/architecture/src/main/java/com/baeldung/architecture/HexagonalArchitectureTaskApplication.java index 69c6f4b276..83e4fc4c0b 100644 --- a/architecture/src/main/java/com/baeldung/architecture/HexagonalArchitectureTaskApplication.java +++ b/architecture/src/main/java/com/baeldung/architecture/HexagonalArchitectureTaskApplication.java @@ -5,8 +5,8 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class HexagonalArchitectureTaskApplication { - public static void main(String[] args) { - SpringApplication.run(HexagonalArchitectureTaskApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(HexagonalArchitectureTaskApplication.class, args); + } } diff --git a/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewTask.java b/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewTask.java index 70638378f9..2e5aff4a53 100644 --- a/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewTask.java +++ b/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewTask.java @@ -19,4 +19,4 @@ public class AddNewTask implements CreateTask { public void create(Task newTask) { taskService.createTask(newTask); } -} +}; diff --git a/architecture/src/main/java/com/baeldung/architecture/application/task/GetTasks.java b/architecture/src/main/java/com/baeldung/architecture/application/task/GetTasks.java index c876f7de85..54539290ba 100644 --- a/architecture/src/main/java/com/baeldung/architecture/application/task/GetTasks.java +++ b/architecture/src/main/java/com/baeldung/architecture/application/task/GetTasks.java @@ -19,4 +19,4 @@ public class GetTasks implements GetAllTasks { public Iterable getAll() { return taskService.getAllTasks(); } -} +}; diff --git a/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java b/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java index cf38e5ee5e..260c033b71 100644 --- a/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java +++ b/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java @@ -17,6 +17,7 @@ public class StartupRunner implements ApplicationRunner { } @Override public void run(ApplicationArguments args) throws Exception { + System.out.println("Adding daily tasks"); Task task = new Task(); task.setDescription("Startup Task"); addNewDailyTask.create(task); From 6008e4446787ab8e4a638fabfb5f734e39ecc384 Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Sat, 25 Apr 2020 13:41:47 -0400 Subject: [PATCH 017/150] Revert "Add architecture module with Hexagonal example" This reverts commit 50efbf3dfb3a951d276c13ab3b8f1a0cadb114d4. --- architecture/README.md | 3 -- architecture/pom.xml | 33 ------------ .../HexagonalArchitectureTaskApplication.java | 12 ----- .../application/task/AddNewDailyTask.java | 29 ---------- .../application/task/AddNewTask.java | 22 -------- .../application/task/GetTasks.java | 22 -------- .../commands/task/CreateTask.java | 7 --- .../commands/task/GetAllTasks.java | 7 --- .../architecture/domain/task/Task.java | 53 ------------------- .../domain/task/TaskRepository.java | 7 --- .../architecture/domain/task/TaskService.java | 22 -------- .../framework/cli/StartupRunner.java | 25 --------- .../http/task/TaskApiController.java | 42 --------------- .../framework/http/task/TaskRequest.java | 29 ---------- 14 files changed, 313 deletions(-) delete mode 100644 architecture/README.md delete mode 100644 architecture/pom.xml delete mode 100644 architecture/src/main/java/com/baeldung/architecture/HexagonalArchitectureTaskApplication.java delete mode 100644 architecture/src/main/java/com/baeldung/architecture/application/task/AddNewDailyTask.java delete mode 100644 architecture/src/main/java/com/baeldung/architecture/application/task/AddNewTask.java delete mode 100644 architecture/src/main/java/com/baeldung/architecture/application/task/GetTasks.java delete mode 100644 architecture/src/main/java/com/baeldung/architecture/commands/task/CreateTask.java delete mode 100644 architecture/src/main/java/com/baeldung/architecture/commands/task/GetAllTasks.java delete mode 100644 architecture/src/main/java/com/baeldung/architecture/domain/task/Task.java delete mode 100644 architecture/src/main/java/com/baeldung/architecture/domain/task/TaskRepository.java delete mode 100644 architecture/src/main/java/com/baeldung/architecture/domain/task/TaskService.java delete mode 100644 architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java delete mode 100644 architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskApiController.java delete mode 100644 architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskRequest.java diff --git a/architecture/README.md b/architecture/README.md deleted file mode 100644 index be093f25ed..0000000000 --- a/architecture/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant articles - -- [A Quick and Practical Example of Hexagonal Architecture in Java](https://www.baeldung.com/a-quick-and-practical-example-of-hexagonal-architecture-in-java-3/) diff --git a/architecture/pom.xml b/architecture/pom.xml deleted file mode 100644 index 4ad104293e..0000000000 --- a/architecture/pom.xml +++ /dev/null @@ -1,33 +0,0 @@ - - 4.0.0 - com.baeldung.architecture - architecture - 0.0.1-SNAPSHOT - architecture - jar - A Quick and Practical Example of Hexagonal Architecture in Java - - - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - com.h2database - h2 - runtime - - - org.springframework.boot - spring-boot-starter-web - - - diff --git a/architecture/src/main/java/com/baeldung/architecture/HexagonalArchitectureTaskApplication.java b/architecture/src/main/java/com/baeldung/architecture/HexagonalArchitectureTaskApplication.java deleted file mode 100644 index 83e4fc4c0b..0000000000 --- a/architecture/src/main/java/com/baeldung/architecture/HexagonalArchitectureTaskApplication.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.architecture; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class HexagonalArchitectureTaskApplication { - public static void main(String[] args) { - SpringApplication.run(HexagonalArchitectureTaskApplication.class, args); - } - -} diff --git a/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewDailyTask.java b/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewDailyTask.java deleted file mode 100644 index 208d1bfcc9..0000000000 --- a/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewDailyTask.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.architecture.application.task; - -import java.time.Instant; -import java.time.temporal.ChronoUnit; - -import com.baeldung.architecture.commands.task.CreateTask; -import com.baeldung.architecture.domain.task.Task; - -import org.springframework.stereotype.Component; - -@Component -public class AddNewDailyTask implements CreateTask { - - private AddNewTask addNewTask; - - public AddNewDailyTask(AddNewTask addNewTask) { - this.addNewTask = addNewTask; - } - - @Override - public void create(Task newTask) { - Instant initialDueDate = newTask.getDueDate(); - String description = newTask.getDescription(); - for (int i = 1; i <= 5; i++) { - Task task = new Task(initialDueDate.plus(i, ChronoUnit.DAYS), description); - addNewTask.create(task); - } - } -}; diff --git a/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewTask.java b/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewTask.java deleted file mode 100644 index 2e5aff4a53..0000000000 --- a/architecture/src/main/java/com/baeldung/architecture/application/task/AddNewTask.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.architecture.application.task; - -import com.baeldung.architecture.domain.task.Task; -import com.baeldung.architecture.domain.task.TaskService; -import com.baeldung.architecture.commands.task.*; - -import org.springframework.stereotype.Component; - -@Component -public class AddNewTask implements CreateTask { - - private TaskService taskService; - - public AddNewTask(TaskService taskService) { - this.taskService = taskService; - } - - @Override - public void create(Task newTask) { - taskService.createTask(newTask); - } -}; diff --git a/architecture/src/main/java/com/baeldung/architecture/application/task/GetTasks.java b/architecture/src/main/java/com/baeldung/architecture/application/task/GetTasks.java deleted file mode 100644 index 54539290ba..0000000000 --- a/architecture/src/main/java/com/baeldung/architecture/application/task/GetTasks.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.architecture.application.task; - -import com.baeldung.architecture.domain.task.Task; -import com.baeldung.architecture.domain.task.TaskService; -import com.baeldung.architecture.commands.task.*; - -import org.springframework.stereotype.Component; - -@Component -public class GetTasks implements GetAllTasks { - - private TaskService taskService; - - public GetTasks(TaskService taskService) { - this.taskService = taskService; - } - - @Override - public Iterable getAll() { - return taskService.getAllTasks(); - } -}; diff --git a/architecture/src/main/java/com/baeldung/architecture/commands/task/CreateTask.java b/architecture/src/main/java/com/baeldung/architecture/commands/task/CreateTask.java deleted file mode 100644 index 26e6da10e2..0000000000 --- a/architecture/src/main/java/com/baeldung/architecture/commands/task/CreateTask.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.architecture.commands.task; - -import com.baeldung.architecture.domain.task.Task; - -public interface CreateTask { - public void create(Task newTask); -}; diff --git a/architecture/src/main/java/com/baeldung/architecture/commands/task/GetAllTasks.java b/architecture/src/main/java/com/baeldung/architecture/commands/task/GetAllTasks.java deleted file mode 100644 index d3c40db92f..0000000000 --- a/architecture/src/main/java/com/baeldung/architecture/commands/task/GetAllTasks.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.architecture.commands.task; - -import com.baeldung.architecture.domain.task.Task; - -public interface GetAllTasks { - public Iterable getAll(); -}; diff --git a/architecture/src/main/java/com/baeldung/architecture/domain/task/Task.java b/architecture/src/main/java/com/baeldung/architecture/domain/task/Task.java deleted file mode 100644 index 240dc33571..0000000000 --- a/architecture/src/main/java/com/baeldung/architecture/domain/task/Task.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.architecture.domain.task; - -import java.time.Instant; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Task { - @Id - @GeneratedValue(strategy=GenerationType.AUTO) - private Long id; - private Instant dueDate = Instant.now(); - private String description; - - public Task() {} - - public Task(Instant dueDate, String description) { - this.dueDate = dueDate; - this.description = description; - } - - public Task(Long id, Instant dueDate, String description) { - this(dueDate, description); - this.id = id; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Instant getDueDate() { - return dueDate; - } - - public void setDueDate(Instant dueDate) { - this.dueDate = dueDate; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } -} diff --git a/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskRepository.java b/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskRepository.java deleted file mode 100644 index d896212714..0000000000 --- a/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskRepository.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.architecture.domain.task; - -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface TaskRepository extends CrudRepository {}; diff --git a/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskService.java b/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskService.java deleted file mode 100644 index cace0614ad..0000000000 --- a/architecture/src/main/java/com/baeldung/architecture/domain/task/TaskService.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.architecture.domain.task; - -import org.springframework.stereotype.Service; - -@Service -public class TaskService { - - private TaskRepository taskRepository; - - public TaskService(TaskRepository taskRepository) { - this.taskRepository = taskRepository; - } - - public void createTask(Task task) { - taskRepository.save(task); - } - - public Iterable getAllTasks() { - return taskRepository.findAll(); - } - -}; diff --git a/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java b/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java deleted file mode 100644 index 260c033b71..0000000000 --- a/architecture/src/main/java/com/baeldung/architecture/framework/cli/StartupRunner.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.architecture.framework.cli; - -import com.baeldung.architecture.application.task.AddNewDailyTask; -import com.baeldung.architecture.domain.task.Task; - -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.stereotype.Component; - -@Component -public class StartupRunner implements ApplicationRunner { - - AddNewDailyTask addNewDailyTask; - - public StartupRunner(AddNewDailyTask addNewDailyTask) { - this.addNewDailyTask = addNewDailyTask; - } - @Override - public void run(ApplicationArguments args) throws Exception { - System.out.println("Adding daily tasks"); - Task task = new Task(); - task.setDescription("Startup Task"); - addNewDailyTask.create(task); - } -} \ No newline at end of file diff --git a/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskApiController.java b/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskApiController.java deleted file mode 100644 index c6f7bff2dd..0000000000 --- a/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskApiController.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.architecture.framework.http.task; - -import java.time.Instant; - -import com.baeldung.architecture.application.task.AddNewTask; -import com.baeldung.architecture.application.task.GetTasks; -import com.baeldung.architecture.domain.task.Task; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("task") -public class TaskApiController { - - private AddNewTask addNewTask; - private GetTasks getTasks; - - public TaskApiController( - AddNewTask addNewTask, - GetTasks getTasks - ) { - this.addNewTask = addNewTask; - this.getTasks = getTasks; - } - - @GetMapping - Iterable listTasks() { - return getTasks.getAll(); - } - - @PostMapping(consumes = "application/json", produces = "application/json") - void createTask(@RequestBody TaskRequest taskRequest) { - Task task = new Task(); - task.setDescription(taskRequest.getDescription()); - task.setDueDate(Instant.parse(taskRequest.getDueDate())); - addNewTask.create(task); - } -} \ No newline at end of file diff --git a/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskRequest.java b/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskRequest.java deleted file mode 100644 index 2e353b079a..0000000000 --- a/architecture/src/main/java/com/baeldung/architecture/framework/http/task/TaskRequest.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.architecture.framework.http.task; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonInclude.Include; - -public class TaskRequest { - @JsonInclude(Include.NON_NULL) - private String description; - - @JsonInclude(Include.NON_NULL) - private String dueDate; - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getDueDate() { - return dueDate; - } - - public void setDueDate(String dueDate) { - this.dueDate = dueDate; - } - -} \ No newline at end of file From cabe3381634a24af850c504ae76ac9844e2d70fe Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Sat, 25 Apr 2020 13:59:02 -0400 Subject: [PATCH 018/150] Update application.properties --- .../src/main/resources/application.properties | 7 ------- 1 file changed, 7 deletions(-) diff --git a/persistence-modules/hibernate-types/src/main/resources/application.properties b/persistence-modules/hibernate-types/src/main/resources/application.properties index bcd21578dd..9588139eb0 100644 --- a/persistence-modules/hibernate-types/src/main/resources/application.properties +++ b/persistence-modules/hibernate-types/src/main/resources/application.properties @@ -7,15 +7,8 @@ logging.level.jdbc.resultset=fatal logging.level.jdbc.resultsettable=info logging.level.jdbc.sqlonly=fatal logging.level.jdbc.sqltiming=info -# logging.level.org.hibernate.SQL=DEBUG -# logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE -# logging.level.org.hibernate.type.descriptor.sql=trace -# logging.level.org.springframework.jdbc.core.JdbcTemplate=DEBUG -# logging.level.org.springframework.jdbc.core.StatementCreatorUtils=TRACE spring.datasource.url=jdbc:mysql://localhost:53306/hibernate_types?serverTimezone=UTC&useSSL=false spring.datasource.username=root spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect spring.jpa.hibernate.ddl-auto=create spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect -# spring.jpa.properties.hibernate.format_sql=false -# spring.jpa.show-sql=false \ No newline at end of file From e91d8d6a6cc9fe1fbb0ad3ea66f6277bb6c37193 Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Sat, 25 Apr 2020 14:33:28 -0400 Subject: [PATCH 019/150] Update pom --- persistence-modules/hibernate-types/pom.xml | 2 +- .../baeldung/hibernate/types/HibernateTypesIntegrationTest.java | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/persistence-modules/hibernate-types/pom.xml b/persistence-modules/hibernate-types/pom.xml index 9fa5d66347..4d686c72a5 100644 --- a/persistence-modules/hibernate-types/pom.xml +++ b/persistence-modules/hibernate-types/pom.xml @@ -205,7 +205,7 @@ 3.0.2 2.22.2 3.8.1 - 3.7.0 + 3.8.1 8.0.19 1.7.30 2.1.3.RELEASE diff --git a/persistence-modules/hibernate-types/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java b/persistence-modules/hibernate-types/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java index 08d4cf919d..9d7479e77d 100644 --- a/persistence-modules/hibernate-types/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java +++ b/persistence-modules/hibernate-types/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java @@ -36,7 +36,6 @@ public class HibernateTypesIntegrationTest { setUp(); } - @Test void whenSavingHibernateTypes_thenTheCorrectJsonIsStoredInTheDatabase() { Album emptyAlbum = new Album(); From caadf4ceb4b3826979a60112eabfde93f8f6fc6c Mon Sep 17 00:00:00 2001 From: John Richardson <42470533+John-Richardson@users.noreply.github.com> Date: Sun, 26 Apr 2020 13:17:19 +0200 Subject: [PATCH 020/150] Replaced for loop with enhanced for --- data-structures/src/main/java/com/baeldung/trie/Trie.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/data-structures/src/main/java/com/baeldung/trie/Trie.java b/data-structures/src/main/java/com/baeldung/trie/Trie.java index dac1a64733..9f0be5c647 100644 --- a/data-structures/src/main/java/com/baeldung/trie/Trie.java +++ b/data-structures/src/main/java/com/baeldung/trie/Trie.java @@ -10,8 +10,8 @@ class Trie { void insert(String word) { TrieNode current = root; - for (int i = 0; i < word.length(); i++) { - current = current.getChildren().computeIfAbsent(word.charAt(i), c -> new TrieNode()); + for (char l : word.toCharArray()) { + current = current.getChildren().computeIfAbsent(l, c -> new TrieNode()); } current.setEndOfWord(true); } @@ -59,4 +59,4 @@ class Trie { } return false; } -} \ No newline at end of file +} From 28e73e30f4af6fdc9ead15460306b5d2757c354a Mon Sep 17 00:00:00 2001 From: Lukasz Rys Date: Sun, 26 Apr 2020 14:33:20 +0200 Subject: [PATCH 021/150] BAEL-3751: Add code needed for CI/CD --- .../.mvn/wrapper/maven-wrapper.properties | 2 + spring-boot-ci-cd/.travis.yml | 13 + spring-boot-ci-cd/mvnw | 310 ++++++++++++++++++ spring-boot-ci-cd/mvnw.cmd | 182 ++++++++++ spring-boot-ci-cd/pom.xml | 64 +++- 5 files changed, 567 insertions(+), 4 deletions(-) create mode 100644 spring-boot-ci-cd/.mvn/wrapper/maven-wrapper.properties create mode 100644 spring-boot-ci-cd/.travis.yml create mode 100755 spring-boot-ci-cd/mvnw create mode 100644 spring-boot-ci-cd/mvnw.cmd diff --git a/spring-boot-ci-cd/.mvn/wrapper/maven-wrapper.properties b/spring-boot-ci-cd/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..642d572ce9 --- /dev/null +++ b/spring-boot-ci-cd/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/spring-boot-ci-cd/.travis.yml b/spring-boot-ci-cd/.travis.yml new file mode 100644 index 0000000000..b932f8969c --- /dev/null +++ b/spring-boot-ci-cd/.travis.yml @@ -0,0 +1,13 @@ +language: java +jdk: + - openjdk11 +services: + - docker + +before_install: + - echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" --password-stdin + - docker pull openjdk:11-jre-slim-sid + +script: + - ./mvnw clean install + - ./mvnw heroku:deploy -P deploy-heroku,deploy-docker \ No newline at end of file diff --git a/spring-boot-ci-cd/mvnw b/spring-boot-ci-cd/mvnw new file mode 100755 index 0000000000..41c0f0c23d --- /dev/null +++ b/spring-boot-ci-cd/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/spring-boot-ci-cd/mvnw.cmd b/spring-boot-ci-cd/mvnw.cmd new file mode 100644 index 0000000000..86115719e5 --- /dev/null +++ b/spring-boot-ci-cd/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/spring-boot-ci-cd/pom.xml b/spring-boot-ci-cd/pom.xml index 070294fdce..982abd6ff8 100644 --- a/spring-boot-ci-cd/pom.xml +++ b/spring-boot-ci-cd/pom.xml @@ -29,11 +29,67 @@ - - org.springframework.boot - spring-boot-maven-plugin - + + org.springframework.boot + spring-boot-maven-plugin + + + + deploy-heroku + + true + + + + + com.heroku.sdk + heroku-maven-plugin + 3.0.2 + + spring-boot-ci-cd + + java $JAVA_OPTS -jar -Dserver.port=$PORT target/${project.build.finalName}.jar + + + + + + + + deploy-docker + + true + + + + + com.spotify + dockerfile-maven-plugin + 1.4.13 + + + default + + build + push + + + + + lukaszrys/spring-boot-ci-cd + ${project.version} + latest + + ${project.build.finalName}.jar + + + + + + + + \ No newline at end of file From f22de7eecf89b63b7cfc73fd6308c4a7da406666 Mon Sep 17 00:00:00 2001 From: Lukasz Rys Date: Mon, 27 Apr 2020 12:33:39 +0200 Subject: [PATCH 022/150] Codecov --- .../.mvn/wrapper/MavenWrapperDownloader.java | 117 ++++++++++++++++++ spring-boot-ci-cd/.travis.yml | 7 +- spring-boot-ci-cd/pom.xml | 20 +++ 3 files changed, 142 insertions(+), 2 deletions(-) create mode 100644 spring-boot-ci-cd/.mvn/wrapper/MavenWrapperDownloader.java diff --git a/spring-boot-ci-cd/.mvn/wrapper/MavenWrapperDownloader.java b/spring-boot-ci-cd/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000000..b901097f2d --- /dev/null +++ b/spring-boot-ci-cd/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/spring-boot-ci-cd/.travis.yml b/spring-boot-ci-cd/.travis.yml index b932f8969c..46333d2680 100644 --- a/spring-boot-ci-cd/.travis.yml +++ b/spring-boot-ci-cd/.travis.yml @@ -9,5 +9,8 @@ before_install: - docker pull openjdk:11-jre-slim-sid script: - - ./mvnw clean install - - ./mvnw heroku:deploy -P deploy-heroku,deploy-docker \ No newline at end of file + - ./mvnw clean org.jacoco:jacoco-maven-plugin:prepare-agent install + - ./mvnw heroku:deploy -P deploy-heroku,deploy-docker + +after_success: + - bash <(curl -s https://codecov.io/bash) \ No newline at end of file diff --git a/spring-boot-ci-cd/pom.xml b/spring-boot-ci-cd/pom.xml index 982abd6ff8..5e32fe105e 100644 --- a/spring-boot-ci-cd/pom.xml +++ b/spring-boot-ci-cd/pom.xml @@ -33,6 +33,26 @@ org.springframework.boot spring-boot-maven-plugin + + org.jacoco + jacoco-maven-plugin + 0.8.5 + + + default-prepare-agent + + prepare-agent + + + + report + test + + report + + + + From d5d6236ae1639f6bb662e1e28782672fd0b2f26f Mon Sep 17 00:00:00 2001 From: Lukasz Rys Date: Mon, 27 Apr 2020 12:51:31 +0200 Subject: [PATCH 023/150] BAEL-3751: Add integration test --- .../cicd/CiCdApplicationIntegrationTest.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 spring-boot-ci-cd/src/test/java/com/baeldung/cicd/CiCdApplicationIntegrationTest.java diff --git a/spring-boot-ci-cd/src/test/java/com/baeldung/cicd/CiCdApplicationIntegrationTest.java b/spring-boot-ci-cd/src/test/java/com/baeldung/cicd/CiCdApplicationIntegrationTest.java new file mode 100644 index 0000000000..7ab246faf8 --- /dev/null +++ b/spring-boot-ci-cd/src/test/java/com/baeldung/cicd/CiCdApplicationIntegrationTest.java @@ -0,0 +1,15 @@ +package com.baeldung.cicd; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class CiCdApplicationIntegrationTest { + + @Test + public void contextLoads() { + + } +} \ No newline at end of file From f8edc08ca60739e0c3bba37fc33f3a29024ceafc Mon Sep 17 00:00:00 2001 From: Lukasz Rys Date: Wed, 29 Apr 2020 23:34:30 +0200 Subject: [PATCH 024/150] [ BAEL-3751 ]: Replace spotify docker plugin with JIB --- spring-boot-ci-cd/.travis.yml | 2 +- spring-boot-ci-cd/pom.xml | 28 ++++++++++------------------ 2 files changed, 11 insertions(+), 19 deletions(-) diff --git a/spring-boot-ci-cd/.travis.yml b/spring-boot-ci-cd/.travis.yml index 46333d2680..8467e11408 100644 --- a/spring-boot-ci-cd/.travis.yml +++ b/spring-boot-ci-cd/.travis.yml @@ -10,7 +10,7 @@ before_install: script: - ./mvnw clean org.jacoco:jacoco-maven-plugin:prepare-agent install - - ./mvnw heroku:deploy -P deploy-heroku,deploy-docker + - ./mvnw heroku:deploy jib:build -P deploy-heroku,deploy-docker after_success: - bash <(curl -s https://codecov.io/bash) \ No newline at end of file diff --git a/spring-boot-ci-cd/pom.xml b/spring-boot-ci-cd/pom.xml index 5e32fe105e..32d0950d78 100644 --- a/spring-boot-ci-cd/pom.xml +++ b/spring-boot-ci-cd/pom.xml @@ -86,25 +86,17 @@ - com.spotify - dockerfile-maven-plugin - 1.4.13 - - - default - - build - push - - - + com.google.cloud.tools + jib-maven-plugin + 2.2.0 - lukaszrys/spring-boot-ci-cd - ${project.version} - latest - - ${project.build.finalName}.jar - + + registry.hub.docker.com/baeldungjib/baeldung-ci-cd-process + + ${project.version} + latest + + From 80caea157507e5edf3c368342ad6b97de57872e1 Mon Sep 17 00:00:00 2001 From: Lukasz Rys Date: Thu, 30 Apr 2020 23:36:38 +0200 Subject: [PATCH 025/150] [ BAEL-3751] : Reformat pom.xml --- spring-boot-ci-cd/pom.xml | 192 +++++++++++++++++++------------------- 1 file changed, 96 insertions(+), 96 deletions(-) diff --git a/spring-boot-ci-cd/pom.xml b/spring-boot-ci-cd/pom.xml index 32d0950d78..e5204d53fd 100644 --- a/spring-boot-ci-cd/pom.xml +++ b/spring-boot-ci-cd/pom.xml @@ -1,107 +1,107 @@ - 4.0.0 - spring-boot-ci-cd - 0.0.1-SNAPSHOT - spring-boot-ci-cd - jar - - - com.baeldung - parent-boot-2 + 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 + spring-boot-ci-cd 0.0.1-SNAPSHOT - ../parent-boot-2 - + spring-boot-ci-cd + jar - - - org.springframework.boot - spring-boot-starter-web - + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + - - org.springframework.boot - spring-boot-starter-actuator - - + + + org.springframework.boot + spring-boot-starter-web + - - - - org.springframework.boot - spring-boot-maven-plugin - - - org.jacoco - jacoco-maven-plugin - 0.8.5 - - - default-prepare-agent - - prepare-agent - - - - report - test - - report - - - - - - + + org.springframework.boot + spring-boot-starter-actuator + + - - - deploy-heroku - - true - - + - - com.heroku.sdk - heroku-maven-plugin - 3.0.2 - - spring-boot-ci-cd - - java $JAVA_OPTS -jar -Dserver.port=$PORT target/${project.build.finalName}.jar - - - + + org.springframework.boot + spring-boot-maven-plugin + + + org.jacoco + jacoco-maven-plugin + 0.8.5 + + + default-prepare-agent + + prepare-agent + + + + report + test + + report + + + + - - - - deploy-docker - - true - - - - - com.google.cloud.tools - jib-maven-plugin - 2.2.0 - - - registry.hub.docker.com/baeldungjib/baeldung-ci-cd-process - - ${project.version} - latest - - - - - - - - + + + + + deploy-heroku + + true + + + + + com.heroku.sdk + heroku-maven-plugin + 3.0.2 + + spring-boot-ci-cd + + java $JAVA_OPTS -jar -Dserver.port=$PORT target/${project.build.finalName}.jar + + + + + + + + deploy-docker + + true + + + + + com.google.cloud.tools + jib-maven-plugin + 2.2.0 + + + registry.hub.docker.com/baeldungjib/baeldung-ci-cd-process + + ${project.version} + latest + + + + + + + + \ No newline at end of file From 44cb3a230a894f86783575a92b8f5b322e26211a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samet=20Y=C4=B1lmaz?= Date: Fri, 1 May 2020 20:50:13 +0300 Subject: [PATCH 026/150] Consumer changed as DefaultConsumer. --- rabbitmq/src/main/java/com/baeldung/consumer/Receiver.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rabbitmq/src/main/java/com/baeldung/consumer/Receiver.java b/rabbitmq/src/main/java/com/baeldung/consumer/Receiver.java index d0612406e9..b2779a6b29 100644 --- a/rabbitmq/src/main/java/com/baeldung/consumer/Receiver.java +++ b/rabbitmq/src/main/java/com/baeldung/consumer/Receiver.java @@ -17,7 +17,7 @@ public class Receiver { channel.queueDeclare(QUEUE_NAME, false, false, false, null); - Consumer consumer = new DefaultConsumer(channel) { + DefaultConsumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, From cbaf84501df11108b9afadcfcbf4b7a5e82f699d Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sun, 3 May 2020 16:03:06 +0530 Subject: [PATCH 027/150] update spring 4 version to latest --- parent-spring-4/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/parent-spring-4/pom.xml b/parent-spring-4/pom.xml index 3f9a22fb03..931cad374b 100644 --- a/parent-spring-4/pom.xml +++ b/parent-spring-4/pom.xml @@ -53,7 +53,7 @@ - 4.3.26.RELEASE + 4.3.27.RELEASE 1.6.1 From bae59eade948e8f1ebb479db84e36637336a66ff Mon Sep 17 00:00:00 2001 From: CHANDRAKANT Kumar Date: Tue, 5 May 2020 14:41:10 +0530 Subject: [PATCH 028/150] Adding the sourcecode for tutorial tracked under BAEL-2957 --- java-es-cqrs/.gitignore | 29 +++++ java-es-cqrs/pom.xml | 20 +++ .../java/com/baeldung/patterns/cqrs/Main.java | 57 ++++++++ .../cqrs/aggregates/UserAggregate.java | 30 +++++ .../cqrs/commands/CreateUserCommand.java | 14 ++ .../cqrs/commands/UpdateUserCommand.java | 20 +++ .../cqrs/projections/UserProjection.java | 37 ++++++ .../cqrs/projectors/UserProjector.java | 56 ++++++++ .../cqrs/queries/AddressByRegionQuery.java | 12 ++ .../cqrs/queries/ContactByTypeQuery.java | 12 ++ .../cqrs/repository/UserReadRepository.java | 31 +++++ .../cqrs/repository/UserWriteRepository.java | 20 +++ .../java/com/baeldung/patterns/crud/Main.java | 48 +++++++ .../crud/repository/UserRepository.java | 20 +++ .../patterns/crud/service/UserService.java | 55 ++++++++ .../com/baeldung/patterns/domain/Address.java | 14 ++ .../com/baeldung/patterns/domain/Contact.java | 13 ++ .../com/baeldung/patterns/domain/User.java | 22 ++++ .../baeldung/patterns/domain/UserAddress.java | 16 +++ .../baeldung/patterns/domain/UserContact.java | 16 +++ .../java/com/baeldung/patterns/es/Main.java | 48 +++++++ .../baeldung/patterns/es/events/Event.java | 15 +++ .../es/events/UserAddressAddedEvent.java | 16 +++ .../es/events/UserAddressRemovedEvent.java | 16 +++ .../es/events/UserContactAddedEvent.java | 15 +++ .../es/events/UserContactRemovedEvent.java | 15 +++ .../patterns/es/events/UserCreatedEvent.java | 16 +++ .../patterns/es/events/UserRemovedEvent.java | 12 ++ .../patterns/es/repository/EventStore.java | 29 +++++ .../patterns/es/service/UserService.java | 94 +++++++++++++ .../patterns/es/service/UserUtility.java | 66 ++++++++++ .../com/baeldung/patterns/escqrs/Main.java | 61 +++++++++ .../escqrs/aggregates/UserAggregate.java | 87 +++++++++++++ .../escqrs/projectors/UserProjector.java | 123 ++++++++++++++++++ 34 files changed, 1155 insertions(+) create mode 100644 java-es-cqrs/.gitignore create mode 100644 java-es-cqrs/pom.xml create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/Main.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/aggregates/UserAggregate.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/commands/CreateUserCommand.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/commands/UpdateUserCommand.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/projections/UserProjection.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/projectors/UserProjector.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/queries/AddressByRegionQuery.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/queries/ContactByTypeQuery.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/repository/UserReadRepository.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/repository/UserWriteRepository.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/crud/Main.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/crud/repository/UserRepository.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/crud/service/UserService.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/domain/Address.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/domain/Contact.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/domain/User.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserAddress.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserContact.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/es/Main.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/Event.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserAddressAddedEvent.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserAddressRemovedEvent.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserContactAddedEvent.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserContactRemovedEvent.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserCreatedEvent.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserRemovedEvent.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/es/repository/EventStore.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserService.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserUtility.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/Main.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/aggregates/UserAggregate.java create mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/projectors/UserProjector.java diff --git a/java-es-cqrs/.gitignore b/java-es-cqrs/.gitignore new file mode 100644 index 0000000000..153c9335eb --- /dev/null +++ b/java-es-cqrs/.gitignore @@ -0,0 +1,29 @@ +HELP.md +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +/build/ + +### VS Code ### +.vscode/ diff --git a/java-es-cqrs/pom.xml b/java-es-cqrs/pom.xml new file mode 100644 index 0000000000..4160c62b0c --- /dev/null +++ b/java-es-cqrs/pom.xml @@ -0,0 +1,20 @@ + + 4.0.0 + com.sapient.learning + java-events + 0.0.1-SNAPSHOT + java-es-cqrs + + 1.8 + 1.8 + + + + org.projectlombok + lombok + 1.18.12 + + + \ No newline at end of file diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/Main.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/Main.java new file mode 100644 index 0000000000..4e9c872cf1 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/Main.java @@ -0,0 +1,57 @@ +package com.baeldung.patterns.cqrs; + +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import com.baeldung.patterns.cqrs.aggregates.UserAggregate; +import com.baeldung.patterns.cqrs.commands.CreateUserCommand; +import com.baeldung.patterns.cqrs.commands.UpdateUserCommand; +import com.baeldung.patterns.cqrs.projections.UserProjection; +import com.baeldung.patterns.cqrs.projectors.UserProjector; +import com.baeldung.patterns.cqrs.queries.AddressByRegionQuery; +import com.baeldung.patterns.cqrs.queries.ContactByTypeQuery; +import com.baeldung.patterns.cqrs.repository.UserReadRepository; +import com.baeldung.patterns.cqrs.repository.UserWriteRepository; +import com.baeldung.patterns.domain.Address; +import com.baeldung.patterns.domain.Contact; +import com.baeldung.patterns.domain.User; + +public class Main { + + public static void main(String[] args) throws Exception { + UserWriteRepository writeRepository = new UserWriteRepository(); + UserReadRepository readRepository = new UserReadRepository(); + UserProjector projector = new UserProjector(readRepository); + UserAggregate userAggregate = new UserAggregate(writeRepository); + UserProjection userProjection = new UserProjection(readRepository); + + String userId = UUID.randomUUID() + .toString(); + User user = null; + CreateUserCommand createUserCommand = new CreateUserCommand(userId, "Tom", "Sawyer"); + user = userAggregate.handleCreateUserCommand(createUserCommand); + projector.project(user); + + UpdateUserCommand updateUserCommand = new UpdateUserCommand(user.getUserid(), Stream.of(new Address("New York", "NY", "10001"), new Address("Los Angeles", "CA", "90001")) + .collect(Collectors.toSet()), + Stream.of(new Contact("EMAIL", "tom.sawyer@gmail.com"), new Contact("EMAIL", "tom.sawyer@rediff.com")) + .collect(Collectors.toSet())); + user = userAggregate.handleUpdateUserCommand(updateUserCommand); + projector.project(user); + + updateUserCommand = new UpdateUserCommand(userId, Stream.of(new Address("New York", "NY", "10001"), new Address("Housten", "TX", "77001")) + .collect(Collectors.toSet()), + Stream.of(new Contact("EMAIL", "tom.sawyer@gmail.com"), new Contact("PHONE", "700-000-0001")) + .collect(Collectors.toSet())); + user = userAggregate.handleUpdateUserCommand(updateUserCommand); + projector.project(user); + + AddressByRegionQuery addressByRegionQuery = new AddressByRegionQuery(user.getUserid(), "NY"); + System.out.println(userProjection.handle(addressByRegionQuery)); + + ContactByTypeQuery contactByTypeQuery = new ContactByTypeQuery(user.getUserid(), "EMAIL"); + System.out.println(userProjection.handle(contactByTypeQuery)); + } + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/aggregates/UserAggregate.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/aggregates/UserAggregate.java new file mode 100644 index 0000000000..b5e16cff0e --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/aggregates/UserAggregate.java @@ -0,0 +1,30 @@ +package com.baeldung.patterns.cqrs.aggregates; + +import com.baeldung.patterns.cqrs.commands.CreateUserCommand; +import com.baeldung.patterns.cqrs.commands.UpdateUserCommand; +import com.baeldung.patterns.cqrs.repository.UserWriteRepository; +import com.baeldung.patterns.domain.User; + +public class UserAggregate { + + private UserWriteRepository writeRepository; + + public UserAggregate(UserWriteRepository repository) { + this.writeRepository = repository; + } + + public User handleCreateUserCommand(CreateUserCommand command) { + User user = new User(command.getUserId(), command.getFiratName(), command.getLastName()); + writeRepository.addUser(user.getUserid(), user); + return user; + } + + public User handleUpdateUserCommand(UpdateUserCommand command) { + User user = writeRepository.getUser(command.getUserId()); + user.setAddresses(command.getAddresses()); + user.setContacts(command.getContacts()); + writeRepository.addUser(user.getUserid(), user); + return user; + } + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/commands/CreateUserCommand.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/commands/CreateUserCommand.java new file mode 100644 index 0000000000..4ab939dbab --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/commands/CreateUserCommand.java @@ -0,0 +1,14 @@ +package com.baeldung.patterns.cqrs.commands; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class CreateUserCommand { + + private String userId; + private String firatName; + private String lastName; + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/commands/UpdateUserCommand.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/commands/UpdateUserCommand.java new file mode 100644 index 0000000000..58a4889458 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/commands/UpdateUserCommand.java @@ -0,0 +1,20 @@ +package com.baeldung.patterns.cqrs.commands; + +import java.util.HashSet; +import java.util.Set; + +import com.baeldung.patterns.domain.Address; +import com.baeldung.patterns.domain.Contact; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class UpdateUserCommand { + + private String userId; + private Set
addresses = new HashSet<>(); + private Set contacts = new HashSet<>(); + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/projections/UserProjection.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/projections/UserProjection.java new file mode 100644 index 0000000000..40a56e727f --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/projections/UserProjection.java @@ -0,0 +1,37 @@ +package com.baeldung.patterns.cqrs.projections; + +import java.util.Set; + +import com.baeldung.patterns.cqrs.queries.AddressByRegionQuery; +import com.baeldung.patterns.cqrs.queries.ContactByTypeQuery; +import com.baeldung.patterns.cqrs.repository.UserReadRepository; +import com.baeldung.patterns.domain.Address; +import com.baeldung.patterns.domain.Contact; +import com.baeldung.patterns.domain.UserAddress; +import com.baeldung.patterns.domain.UserContact; + +public class UserProjection { + + private UserReadRepository repository; + + public UserProjection(UserReadRepository repository) { + this.repository = repository; + } + + public Set handle(ContactByTypeQuery query) throws Exception { + UserContact userContact = repository.getUserContact(query.getUserId()); + if (userContact == null) + throw new Exception("User does not exist."); + return userContact.getContactByType() + .get(query.getContactType()); + } + + public Set
handle(AddressByRegionQuery query) throws Exception { + UserAddress userAddress = repository.getUserAddress(query.getUserId()); + if (userAddress == null) + throw new Exception("User does not exist."); + return userAddress.getAddressByRegion() + .get(query.getState()); + } + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/projectors/UserProjector.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/projectors/UserProjector.java new file mode 100644 index 0000000000..25c10094c1 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/projectors/UserProjector.java @@ -0,0 +1,56 @@ +package com.baeldung.patterns.cqrs.projectors; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import com.baeldung.patterns.cqrs.repository.UserReadRepository; +import com.baeldung.patterns.domain.Address; +import com.baeldung.patterns.domain.Contact; +import com.baeldung.patterns.domain.User; +import com.baeldung.patterns.domain.UserAddress; +import com.baeldung.patterns.domain.UserContact; + +public class UserProjector { + + UserReadRepository readRepository = new UserReadRepository(); + + public UserProjector(UserReadRepository readRepository) { + this.readRepository = readRepository; + } + + public void project(User user) { + UserContact userContact = readRepository.getUserContact(user.getUserid()); + if (userContact == null) + userContact = new UserContact(); + userContact.setContacts(user.getContacts()); + Map> contactByType = new HashMap<>(); + for (Contact contact : user.getContacts()) { + Set contacts = contactByType.get(contact.getType()); + if (contacts == null) + contacts = new HashSet<>(); + contacts.add(contact); + contactByType.put(contact.getType(), contacts); + } + userContact.setContactByType(contactByType); + readRepository.addUserContact(user.getUserid(), userContact); + + UserAddress userAddress = readRepository.getUserAddress(user.getUserid()); + if (userAddress == null) + userAddress = new UserAddress(); + userAddress.setAddresses(user.getAddresses()); + Map> addressByRegion = new HashMap<>(); + for (Address address : user.getAddresses()) { + Set
addresses = addressByRegion.get(address.getState()); + if (addresses == null) + addresses = new HashSet<>(); + addresses.add(address); + addressByRegion.put(address.getState(), addresses); + } + userAddress.setAddressByRegion(addressByRegion); + readRepository.addUserAddress(user.getUserid(), userAddress); + + } + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/queries/AddressByRegionQuery.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/queries/AddressByRegionQuery.java new file mode 100644 index 0000000000..4a0f0769f2 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/queries/AddressByRegionQuery.java @@ -0,0 +1,12 @@ +package com.baeldung.patterns.cqrs.queries; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class AddressByRegionQuery { + + private String userId; + private String state; +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/queries/ContactByTypeQuery.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/queries/ContactByTypeQuery.java new file mode 100644 index 0000000000..b6c271b472 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/queries/ContactByTypeQuery.java @@ -0,0 +1,12 @@ +package com.baeldung.patterns.cqrs.queries; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class ContactByTypeQuery { + + private String userId; + private String contactType; +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/repository/UserReadRepository.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/repository/UserReadRepository.java new file mode 100644 index 0000000000..a7ef2f6f96 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/repository/UserReadRepository.java @@ -0,0 +1,31 @@ +package com.baeldung.patterns.cqrs.repository; + +import java.util.HashMap; +import java.util.Map; + +import com.baeldung.patterns.domain.UserAddress; +import com.baeldung.patterns.domain.UserContact; + +public class UserReadRepository { + + private Map userAddress = new HashMap<>(); + + private Map userContact = new HashMap<>(); + + public void addUserAddress(String id, UserAddress user) { + userAddress.put(id, user); + } + + public UserAddress getUserAddress(String id) { + return userAddress.get(id); + } + + public void addUserContact(String id, UserContact user) { + userContact.put(id, user); + } + + public UserContact getUserContact(String id) { + return userContact.get(id); + } + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/repository/UserWriteRepository.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/repository/UserWriteRepository.java new file mode 100644 index 0000000000..8636e36225 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/repository/UserWriteRepository.java @@ -0,0 +1,20 @@ +package com.baeldung.patterns.cqrs.repository; + +import java.util.HashMap; +import java.util.Map; + +import com.baeldung.patterns.domain.User; + +public class UserWriteRepository { + + private Map store = new HashMap<>(); + + public void addUser(String id, User user) { + store.put(id, user); + } + + public User getUser(String id) { + return store.get(id); + } + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/crud/Main.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/crud/Main.java new file mode 100644 index 0000000000..1f20e0be38 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/crud/Main.java @@ -0,0 +1,48 @@ +package com.baeldung.patterns.crud; + +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import com.baeldung.patterns.crud.repository.UserRepository; +import com.baeldung.patterns.crud.service.UserService; +import com.baeldung.patterns.domain.Address; +import com.baeldung.patterns.domain.Contact; + +public class Main { + + public static void main(String[] args) throws Exception { + + UserRepository repository = new UserRepository(); + UserService service = new UserService(repository); + String userId = UUID.randomUUID() + .toString(); + + service.createUser(userId, "Tom", "Sawyer"); + service.updateUser(userId, + Stream.of( + new Contact("EMAIL", "tom.sawyer@gmail.com"), + new Contact("EMAIL", "tom.sawyer@rediff.com"), + new Contact("PHONE", "700-000-0001")) + .collect(Collectors.toSet()), + Stream.of( + new Address("New York", "NY", "10001"), + new Address("Los Angeles", "CA", "90001"), + new Address("Housten", "TX", "77001")) + .collect(Collectors.toSet())); + service.updateUser(userId, + Stream.of( + new Contact("EMAIL", "tom.sawyer@gmail.com"), + new Contact("PHONE", "700-000-0001")) + .collect(Collectors.toSet()), + Stream.of( + new Address("New York", "NY", "10001"), + new Address("Housten", "TX", "77001")) + .collect(Collectors.toSet())); + + System.out.println(service.getContactByType(userId, "EMAIL")); + System.out.println(service.getAddressByRegion(userId, "NY")); + + } + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/crud/repository/UserRepository.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/crud/repository/UserRepository.java new file mode 100644 index 0000000000..b22d40e6e0 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/crud/repository/UserRepository.java @@ -0,0 +1,20 @@ +package com.baeldung.patterns.crud.repository; + +import java.util.HashMap; +import java.util.Map; + +import com.baeldung.patterns.domain.User; + +public class UserRepository { + + private Map store = new HashMap<>(); + + public void addUser(String id, User user) { + store.put(id, user); + } + + public User getUser(String id) { + return store.get(id); + } + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/crud/service/UserService.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/crud/service/UserService.java new file mode 100644 index 0000000000..d21a796304 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/crud/service/UserService.java @@ -0,0 +1,55 @@ +package com.baeldung.patterns.crud.service; + +import java.util.Set; +import java.util.stream.Collectors; + +import com.baeldung.patterns.crud.repository.UserRepository; +import com.baeldung.patterns.domain.Address; +import com.baeldung.patterns.domain.Contact; +import com.baeldung.patterns.domain.User; + +public class UserService { + + private UserRepository repository; + + public UserService(UserRepository repository) { + this.repository = repository; + } + + public void createUser(String userId, String firstName, String lastName) { + User user = new User(userId, firstName, lastName); + repository.addUser(userId, user); + } + + public void updateUser(String userId, Set contacts, Set
addresses) throws Exception { + User user = repository.getUser(userId); + if (user == null) + throw new Exception("User does not exist."); + user.setContacts(contacts); + user.setAddresses(addresses); + repository.addUser(userId, user); + } + + public Set getContactByType(String userId, String contactType) throws Exception { + User user = repository.getUser(userId); + if (user == null) + throw new Exception("User does not exit."); + Set contacts = user.getContacts(); + return contacts.stream() + .filter(c -> c.getType() + .equals(contactType)) + .collect(Collectors.toSet()); + } + + public Set
getAddressByRegion(String userId, String state) throws Exception { + User user = repository.getUser(userId); + if (user == null) + throw new Exception("User does not exist."); + Set
addresses = user.getAddresses(); + return addresses.stream() + .filter(a -> a.getState() + .equals(state)) + .collect(Collectors.toSet()); + } + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/Address.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/Address.java new file mode 100644 index 0000000000..dfaa724434 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/Address.java @@ -0,0 +1,14 @@ +package com.baeldung.patterns.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class Address { + + private String city; + private String state; + private String postcode; + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/Contact.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/Contact.java new file mode 100644 index 0000000000..a151cdb4ff --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/Contact.java @@ -0,0 +1,13 @@ +package com.baeldung.patterns.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class Contact { + + private String type; + private String detail; + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/User.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/User.java new file mode 100644 index 0000000000..8f59723894 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/User.java @@ -0,0 +1,22 @@ +package com.baeldung.patterns.domain; + +import java.util.HashSet; +import java.util.Set; + +import lombok.Data; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; + +@Data +@RequiredArgsConstructor +public class User { + @NonNull + private String userid; + @NonNull + private String firstname; + @NonNull + private String lastname; + private Set contacts = new HashSet<>(); + private Set
addresses = new HashSet<>(); + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserAddress.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserAddress.java new file mode 100644 index 0000000000..33f9bdf28f --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserAddress.java @@ -0,0 +1,16 @@ +package com.baeldung.patterns.domain; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import lombok.Data; + +@Data +public class UserAddress { + + private Set
addresses = new HashSet<>(); + private Map> addressByRegion = new HashMap<>(); + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserContact.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserContact.java new file mode 100644 index 0000000000..4f2ba812a4 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserContact.java @@ -0,0 +1,16 @@ +package com.baeldung.patterns.domain; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import lombok.Data; + +@Data +public class UserContact { + + private Set contacts = new HashSet<>(); + private Map> contactByType = new HashMap<>(); + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/Main.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/Main.java new file mode 100644 index 0000000000..77649088e9 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/Main.java @@ -0,0 +1,48 @@ +package com.baeldung.patterns.es; + +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import com.baeldung.patterns.domain.Address; +import com.baeldung.patterns.domain.Contact; +import com.baeldung.patterns.es.repository.EventStore; +import com.baeldung.patterns.es.service.UserService; + +public class Main { + + public static void main(String[] args) throws Exception { + + EventStore repository = new EventStore(); + UserService service = new UserService(repository); + String userId = UUID.randomUUID() + .toString(); + + service.createUser(userId, "Tom", "Sawyer"); + service.updateUser(userId, + Stream.of( + new Contact("EMAIL", "tom.sawyer@gmail.com"), + new Contact("EMAIL", "tom.sawyer@rediff.com"), + new Contact("PHONE", "700-000-0001")) + .collect(Collectors.toSet()), + Stream.of( + new Address("New York", "NY", "10001"), + new Address("Los Angeles", "CA", "90001"), + new Address("Housten", "TX", "77001")) + .collect(Collectors.toSet())); + service.updateUser(userId, + Stream.of( + new Contact("EMAIL", "tom.sawyer@gmail.com"), + new Contact("PHONE", "700-000-0001")) + .collect(Collectors.toSet()), + Stream.of( + new Address("New York", "NY", "10001"), + new Address("Housten", "TX", "77001")) + .collect(Collectors.toSet())); + + System.out.println(service.getContactByType(userId, "EMAIL")); + System.out.println(service.getAddressByRegion(userId, "NY")); + + } + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/Event.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/Event.java new file mode 100644 index 0000000000..4718450cac --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/Event.java @@ -0,0 +1,15 @@ +package com.baeldung.patterns.es.events; + +import java.util.Date; +import java.util.UUID; + +import lombok.ToString; + +@ToString +public abstract class Event { + + public final UUID id = UUID.randomUUID(); + + public final Date created = new Date(); + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserAddressAddedEvent.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserAddressAddedEvent.java new file mode 100644 index 0000000000..caa640798b --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserAddressAddedEvent.java @@ -0,0 +1,16 @@ +package com.baeldung.patterns.es.events; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@AllArgsConstructor +@EqualsAndHashCode(callSuper = false) +public class UserAddressAddedEvent extends Event { + + private String city; + private String state; + private String postCode; + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserAddressRemovedEvent.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserAddressRemovedEvent.java new file mode 100644 index 0000000000..f0702d8810 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserAddressRemovedEvent.java @@ -0,0 +1,16 @@ +package com.baeldung.patterns.es.events; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@AllArgsConstructor +@EqualsAndHashCode(callSuper = false) +public class UserAddressRemovedEvent extends Event { + + private String city; + private String state; + private String postCode; + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserContactAddedEvent.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserContactAddedEvent.java new file mode 100644 index 0000000000..0bce2f997e --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserContactAddedEvent.java @@ -0,0 +1,15 @@ +package com.baeldung.patterns.es.events; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@AllArgsConstructor +@EqualsAndHashCode(callSuper = false) +public class UserContactAddedEvent extends Event { + + private String contactType; + private String contactDetails; + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserContactRemovedEvent.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserContactRemovedEvent.java new file mode 100644 index 0000000000..9c043971e7 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserContactRemovedEvent.java @@ -0,0 +1,15 @@ +package com.baeldung.patterns.es.events; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@AllArgsConstructor +@EqualsAndHashCode(callSuper = false) +public class UserContactRemovedEvent extends Event { + + private String contactType; + private String contactDetails; + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserCreatedEvent.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserCreatedEvent.java new file mode 100644 index 0000000000..8e725cd667 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserCreatedEvent.java @@ -0,0 +1,16 @@ +package com.baeldung.patterns.es.events; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@AllArgsConstructor +@EqualsAndHashCode(callSuper = false) +public class UserCreatedEvent extends Event { + + private String userId; + private String firstName; + private String lastName; + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserRemovedEvent.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserRemovedEvent.java new file mode 100644 index 0000000000..b609cb1daf --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserRemovedEvent.java @@ -0,0 +1,12 @@ +package com.baeldung.patterns.es.events; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@AllArgsConstructor +@EqualsAndHashCode(callSuper = false) +public class UserRemovedEvent extends Event { + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/repository/EventStore.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/repository/EventStore.java new file mode 100644 index 0000000000..87914d8c12 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/repository/EventStore.java @@ -0,0 +1,29 @@ +package com.baeldung.patterns.es.repository; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.baeldung.patterns.es.events.Event; + +public class EventStore { + + private Map> store = new HashMap<>(); + + public void addEvent(String id, Event event) { + List events = store.get(id); + if (events == null) { + events = new ArrayList(); + events.add(event); + store.put(id, events); + } else { + events.add(event); + } + } + + public List getEvents(String id) { + return store.get(id); + } + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserService.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserService.java new file mode 100644 index 0000000000..0233453d68 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserService.java @@ -0,0 +1,94 @@ +package com.baeldung.patterns.es.service; + +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import com.baeldung.patterns.domain.Address; +import com.baeldung.patterns.domain.Contact; +import com.baeldung.patterns.domain.User; +import com.baeldung.patterns.es.events.UserAddressAddedEvent; +import com.baeldung.patterns.es.events.UserAddressRemovedEvent; +import com.baeldung.patterns.es.events.UserContactAddedEvent; +import com.baeldung.patterns.es.events.UserContactRemovedEvent; +import com.baeldung.patterns.es.events.UserCreatedEvent; +import com.baeldung.patterns.es.repository.EventStore; + +public class UserService { + + private EventStore repository; + + public UserService(EventStore repository) { + this.repository = repository; + } + + public void createUser(String userId, String firstName, String lastName) { + UserCreatedEvent event = new UserCreatedEvent(userId, firstName, lastName); + repository.addEvent(userId, event); + } + + public void updateUser(String userId, Set contacts, Set
addresses) throws Exception { + User user = UserUtility.recreateUserState(repository, userId); + if (user == null) + throw new Exception("User does not exist."); + + List contactsToRemove = user.getContacts() + .stream() + .filter(c -> !contacts.contains(c)) + .collect(Collectors.toList()); + for (Contact contact : contactsToRemove) { + UserContactRemovedEvent contactRemovedEvent = new UserContactRemovedEvent(contact.getType(), contact.getDetail()); + repository.addEvent(userId, contactRemovedEvent); + } + + List contactsToAdd = contacts.stream() + .filter(c -> !user.getContacts() + .contains(c)) + .collect(Collectors.toList()); + for (Contact contact : contactsToAdd) { + UserContactAddedEvent contactAddedEvent = new UserContactAddedEvent(contact.getType(), contact.getDetail()); + repository.addEvent(userId, contactAddedEvent); + } + + List
addressesToRemove = user.getAddresses() + .stream() + .filter(a -> !addresses.contains(a)) + .collect(Collectors.toList()); + for (Address address : addressesToRemove) { + UserAddressRemovedEvent addressRemovedEvent = new UserAddressRemovedEvent(address.getCity(), address.getState(), address.getPostcode()); + repository.addEvent(userId, addressRemovedEvent); + } + + List
addressesToAdd = addresses.stream() + .filter(a -> !user.getAddresses() + .contains(a)) + .collect(Collectors.toList()); + for (Address address : addressesToAdd) { + UserAddressAddedEvent addressAddedEvent = new UserAddressAddedEvent(address.getCity(), address.getState(), address.getPostcode()); + repository.addEvent(userId, addressAddedEvent); + } + } + + public Set getContactByType(String userId, String contactType) throws Exception { + User user = UserUtility.recreateUserState(repository, userId); + if (user == null) + throw new Exception("User does not exist."); + Set contacts = user.getContacts(); + return contacts.stream() + .filter(c -> c.getType() + .equals(contactType)) + .collect(Collectors.toSet()); + } + + public Set
getAddressByRegion(String userId, String state) throws Exception { + User user = UserUtility.recreateUserState(repository, userId); + if (user == null) + throw new Exception("User does not exist."); + Set
addresses = user.getAddresses(); + return addresses.stream() + .filter(a -> a.getState() + .equals(state)) + .collect(Collectors.toSet()); + } + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserUtility.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserUtility.java new file mode 100644 index 0000000000..b7ed9208b2 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserUtility.java @@ -0,0 +1,66 @@ +package com.baeldung.patterns.es.service; + +import java.util.List; +import java.util.UUID; + +import com.baeldung.patterns.domain.Address; +import com.baeldung.patterns.domain.Contact; +import com.baeldung.patterns.domain.User; +import com.baeldung.patterns.es.events.Event; +import com.baeldung.patterns.es.events.UserAddressAddedEvent; +import com.baeldung.patterns.es.events.UserAddressRemovedEvent; +import com.baeldung.patterns.es.events.UserContactAddedEvent; +import com.baeldung.patterns.es.events.UserContactRemovedEvent; +import com.baeldung.patterns.es.events.UserCreatedEvent; +import com.baeldung.patterns.es.events.UserRemovedEvent; +import com.baeldung.patterns.es.repository.EventStore; + +public class UserUtility { + + public static User recreateUserState(EventStore store, String userId) { + User user = null; + + List events = store.getEvents(userId); + for (Event event : events) { + if (event instanceof UserCreatedEvent) { + UserCreatedEvent e = (UserCreatedEvent) event; + user = new User(UUID.randomUUID() + .toString(), e.getFirstName(), e.getLastName()); + } + if (event instanceof UserRemovedEvent) { + user = null; + } + if (event instanceof UserAddressAddedEvent) { + UserAddressAddedEvent e = (UserAddressAddedEvent) event; + Address address = new Address(e.getCity(), e.getState(), e.getPostCode()); + if (user != null) + user.getAddresses() + .add(address); + } + if (event instanceof UserAddressRemovedEvent) { + UserAddressRemovedEvent e = (UserAddressRemovedEvent) event; + Address address = new Address(e.getCity(), e.getState(), e.getPostCode()); + if (user != null) + user.getAddresses() + .remove(address); + } + if (event instanceof UserContactAddedEvent) { + UserContactAddedEvent e = (UserContactAddedEvent) event; + Contact contact = new Contact(e.getContactType(), e.getContactDetails()); + if (user != null) + user.getContacts() + .add(contact); + } + if (event instanceof UserContactRemovedEvent) { + UserContactRemovedEvent e = (UserContactRemovedEvent) event; + Contact contact = new Contact(e.getContactType(), e.getContactDetails()); + if (user != null) + user.getContacts() + .remove(contact); + } + } + + return user; + } + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/Main.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/Main.java new file mode 100644 index 0000000000..44395a75a7 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/Main.java @@ -0,0 +1,61 @@ +package com.baeldung.patterns.escqrs; + +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import com.baeldung.patterns.cqrs.commands.CreateUserCommand; +import com.baeldung.patterns.cqrs.commands.UpdateUserCommand; +import com.baeldung.patterns.cqrs.projections.UserProjection; +import com.baeldung.patterns.cqrs.queries.AddressByRegionQuery; +import com.baeldung.patterns.cqrs.queries.ContactByTypeQuery; +import com.baeldung.patterns.cqrs.repository.UserReadRepository; +import com.baeldung.patterns.domain.Address; +import com.baeldung.patterns.domain.Contact; +import com.baeldung.patterns.es.events.Event; +import com.baeldung.patterns.es.repository.EventStore; +import com.baeldung.patterns.escqrs.aggregates.UserAggregate; +import com.baeldung.patterns.escqrs.projectors.UserProjector; + +public class Main { + + public static void main(String[] args) throws Exception { + + EventStore writeRepository = new EventStore(); + UserReadRepository readRepository = new UserReadRepository(); + UserProjector projector = new UserProjector(readRepository); + UserAggregate userAggregate = new UserAggregate(writeRepository); + UserProjection userProjection = new UserProjection(readRepository); + + String userId = UUID.randomUUID() + .toString(); + List events = null; + CreateUserCommand createUserCommand = new CreateUserCommand(userId, "Kumar", "Chandrakant"); + events = userAggregate.handleCreateUserCommand(createUserCommand); + + projector.project(userId, events); + + UpdateUserCommand updateUserCommand = new UpdateUserCommand(userId, Stream.of(new Address("New York", "NY", "10001"), new Address("Los Angeles", "CA", "90001")) + .collect(Collectors.toSet()), + Stream.of(new Contact("EMAIL", "tom.sawyer@gmail.com"), new Contact("EMAIL", "tom.sawyer@rediff.com")) + .collect(Collectors.toSet())); + events = userAggregate.handleUpdateUserCommand(updateUserCommand); + projector.project(userId, events); + + updateUserCommand = new UpdateUserCommand(userId, Stream.of(new Address("New York", "NY", "10001"), new Address("Housten", "TX", "77001")) + .collect(Collectors.toSet()), + Stream.of(new Contact("EMAIL", "tom.sawyer@gmail.com"), new Contact("PHONE", "700-000-0001")) + .collect(Collectors.toSet())); + events = userAggregate.handleUpdateUserCommand(updateUserCommand); + projector.project(userId, events); + + AddressByRegionQuery addressByRegionQuery = new AddressByRegionQuery(userId, "NY"); + System.out.println(userProjection.handle(addressByRegionQuery)); + + ContactByTypeQuery contactByTypeQuery = new ContactByTypeQuery(userId, "EMAIL"); + System.out.println(userProjection.handle(contactByTypeQuery)); + + } + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/aggregates/UserAggregate.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/aggregates/UserAggregate.java new file mode 100644 index 0000000000..7d32aeb2a2 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/aggregates/UserAggregate.java @@ -0,0 +1,87 @@ +package com.baeldung.patterns.escqrs.aggregates; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import com.baeldung.patterns.cqrs.commands.CreateUserCommand; +import com.baeldung.patterns.cqrs.commands.UpdateUserCommand; +import com.baeldung.patterns.domain.Address; +import com.baeldung.patterns.domain.Contact; +import com.baeldung.patterns.domain.User; +import com.baeldung.patterns.es.events.Event; +import com.baeldung.patterns.es.events.UserAddressAddedEvent; +import com.baeldung.patterns.es.events.UserAddressRemovedEvent; +import com.baeldung.patterns.es.events.UserContactAddedEvent; +import com.baeldung.patterns.es.events.UserContactRemovedEvent; +import com.baeldung.patterns.es.events.UserCreatedEvent; +import com.baeldung.patterns.es.repository.EventStore; +import com.baeldung.patterns.es.service.UserUtility; + +public class UserAggregate { + + private EventStore writeRepository; + + public UserAggregate(EventStore repository) { + this.writeRepository = repository; + } + + public List handleCreateUserCommand(CreateUserCommand command) { + UserCreatedEvent event = new UserCreatedEvent(command.getUserId(), command.getFiratName(), command.getLastName()); + writeRepository.addEvent(command.getUserId(), event); + return Arrays.asList(event); + } + + public List handleUpdateUserCommand(UpdateUserCommand command) { + User user = UserUtility.recreateUserState(writeRepository, command.getUserId()); + List events = new ArrayList<>(); + + List contactsToRemove = user.getContacts() + .stream() + .filter(c -> !command.getContacts() + .contains(c)) + .collect(Collectors.toList()); + for (Contact contact : contactsToRemove) { + UserContactRemovedEvent contactRemovedEvent = new UserContactRemovedEvent(contact.getType(), contact.getDetail()); + events.add(contactRemovedEvent); + writeRepository.addEvent(command.getUserId(), contactRemovedEvent); + } + + List contactsToAdd = command.getContacts() + .stream() + .filter(c -> !user.getContacts() + .contains(c)) + .collect(Collectors.toList()); + for (Contact contact : contactsToAdd) { + UserContactAddedEvent contactAddedEvent = new UserContactAddedEvent(contact.getType(), contact.getDetail()); + events.add(contactAddedEvent); + writeRepository.addEvent(command.getUserId(), contactAddedEvent); + } + + List
addressesToRemove = user.getAddresses() + .stream() + .filter(a -> !command.getAddresses() + .contains(a)) + .collect(Collectors.toList()); + for (Address address : addressesToRemove) { + UserAddressRemovedEvent addressRemovedEvent = new UserAddressRemovedEvent(address.getCity(), address.getState(), address.getPostcode()); + events.add(addressRemovedEvent); + writeRepository.addEvent(command.getUserId(), addressRemovedEvent); + } + + List
addressesToAdd = command.getAddresses() + .stream() + .filter(a -> !user.getAddresses() + .contains(a)) + .collect(Collectors.toList()); + for (Address address : addressesToAdd) { + UserAddressAddedEvent addressAddedEvent = new UserAddressAddedEvent(address.getCity(), address.getState(), address.getPostcode()); + events.add(addressAddedEvent); + writeRepository.addEvent(command.getUserId(), addressAddedEvent); + } + + return events; + } + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/projectors/UserProjector.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/projectors/UserProjector.java new file mode 100644 index 0000000000..036b6e8396 --- /dev/null +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/projectors/UserProjector.java @@ -0,0 +1,123 @@ +package com.baeldung.patterns.escqrs.projectors; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import com.baeldung.patterns.cqrs.repository.UserReadRepository; +import com.baeldung.patterns.domain.Address; +import com.baeldung.patterns.domain.Contact; +import com.baeldung.patterns.domain.UserAddress; +import com.baeldung.patterns.domain.UserContact; +import com.baeldung.patterns.es.events.Event; +import com.baeldung.patterns.es.events.UserAddressAddedEvent; +import com.baeldung.patterns.es.events.UserAddressRemovedEvent; +import com.baeldung.patterns.es.events.UserContactAddedEvent; +import com.baeldung.patterns.es.events.UserContactRemovedEvent; +import com.baeldung.patterns.es.events.UserCreatedEvent; +import com.baeldung.patterns.es.events.UserRemovedEvent; + +public class UserProjector { + + UserReadRepository readRepository = new UserReadRepository(); + + public UserProjector(UserReadRepository readRepository) { + this.readRepository = readRepository; + } + + public void project(String userId, List events) { + + for (Event event : events) { + if (event instanceof UserCreatedEvent) + apply(userId, (UserCreatedEvent) event); + if (event instanceof UserRemovedEvent) + apply(userId, (UserRemovedEvent) event); + if (event instanceof UserAddressAddedEvent) + apply(userId, (UserAddressAddedEvent) event); + if (event instanceof UserAddressRemovedEvent) + apply(userId, (UserAddressRemovedEvent) event); + if (event instanceof UserContactAddedEvent) + apply(userId, (UserContactAddedEvent) event); + if (event instanceof UserContactRemovedEvent) + apply(userId, (UserContactRemovedEvent) event); + } + + } + + public void apply(String userId, UserCreatedEvent event) { + + } + + public void apply(String userId, UserRemovedEvent event) { + + } + + public void apply(String userId, UserAddressAddedEvent event) { + Address address = new Address(event.getCity(), event.getState(), event.getPostCode()); + UserAddress userAddress = readRepository.getUserAddress(userId); + if (userAddress == null) + userAddress = new UserAddress(); + userAddress.getAddresses() + .add(address); + Set
addresses = userAddress.getAddressByRegion() + .get(address.getState()); + if (addresses == null) + addresses = new HashSet<>(); + addresses.add(address); + userAddress.getAddressByRegion() + .put(address.getState(), addresses); + readRepository.addUserAddress(userId, userAddress); + } + + public void apply(String userId, UserAddressRemovedEvent event) { + Address address = new Address(event.getCity(), event.getState(), event.getPostCode()); + UserAddress userAddress = readRepository.getUserAddress(userId); + if (userAddress != null) { + userAddress.getAddresses() + .remove(address); + Set
addresses = userAddress.getAddressByRegion() + .get(address.getState()); + if (addresses != null) { + addresses.remove(address); + userAddress.getAddressByRegion() + .put(address.getState(), addresses); + } + readRepository.addUserAddress(userId, userAddress); + } + } + + public void apply(String userId, UserContactAddedEvent event) { + Contact contact = new Contact(event.getContactType(), event.getContactDetails()); + UserContact userContact = readRepository.getUserContact(userId); + if (userContact == null) + userContact = new UserContact(); + userContact.getContacts() + .add(contact); + Set contacts = userContact.getContactByType() + .get(contact.getType()); + if (contacts == null) + contacts = new HashSet<>(); + contacts.add(contact); + userContact.getContactByType() + .put(contact.getType(), contacts); + readRepository.addUserContact(userId, userContact); + } + + public void apply(String userId, UserContactRemovedEvent event) { + Contact contact = new Contact(event.getContactType(), event.getContactDetails()); + UserContact userContact = readRepository.getUserContact(userId); + if (userContact != null) { + userContact.getContacts() + .remove(contact); + Set contacts = userContact.getContactByType() + .get(contact.getType()); + if (contacts != null) { + contacts.remove(contact); + userContact.getContactByType() + .put(contact.getType(), contacts); + } + readRepository.addUserContact(userId, userContact); + } + } + +} From 0774d2f238d938c9fc37dea58421f486e863861a Mon Sep 17 00:00:00 2001 From: mthomas Date: Tue, 5 May 2020 22:38:52 -0500 Subject: [PATCH 029/150] BAEL-3974 - Add unit test for streaming Base64 encoding --- .../pdf/base64/EncodeDecodeUnitTest.java | 31 ++++++++++++++++--- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java index 0fb61ea121..faade80884 100644 --- a/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java @@ -1,17 +1,19 @@ package com.baeldung.pdf.base64; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - +import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; +import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; import org.junit.BeforeClass; import org.junit.Test; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + public class EncodeDecodeUnitTest { private static final String IN_FILE = "src/test/resources/input.pdf"; @@ -39,6 +41,27 @@ public class EncodeDecodeUnitTest { } + @Test + public void givenJavaBase64_whenEncodedStream_thenDecodedStreamOK() throws IOException { + + try (OutputStream os = java.util.Base64.getEncoder().wrap(new FileOutputStream(OUT_FILE)); + FileInputStream fis = new FileInputStream(IN_FILE)) { + byte[] bytes = new byte[1024]; + int read; + while ((read = fis.read(bytes)) > -1) { + os.write(bytes, 0, read); + } + } + + byte[] encoded = java.util.Base64.getEncoder().encode(inFileBytes); + byte[] encodedOnDisk = Files.readAllBytes(Paths.get(OUT_FILE)); + assertArrayEquals(encoded, encodedOnDisk); + + byte[] decoded = java.util.Base64.getDecoder().decode(encoded); + byte[] decodedOnDisk = java.util.Base64.getDecoder().decode(encodedOnDisk); + assertArrayEquals(decoded, decodedOnDisk); + } + @Test public void givenApacheCommons_givenJavaBase64_whenEncoded_thenDecodedOK() throws IOException { From 355cce7cc706959d3069a905128c966960082b6f Mon Sep 17 00:00:00 2001 From: mthomas Date: Wed, 6 May 2020 02:56:12 -0500 Subject: [PATCH 030/150] BAEL-3974 - Put imports back in place --- .../com/baeldung/pdf/base64/EncodeDecodeUnitTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java index faade80884..0df6f58136 100644 --- a/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java @@ -1,5 +1,9 @@ package com.baeldung.pdf.base64; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; @@ -10,10 +14,6 @@ import java.nio.file.Paths; import org.junit.BeforeClass; import org.junit.Test; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - public class EncodeDecodeUnitTest { private static final String IN_FILE = "src/test/resources/input.pdf"; From 6b28cb46d0ca341d0f4b1eb6db88dd33d9862143 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Wed, 6 May 2020 13:54:59 +0200 Subject: [PATCH 031/150] BAEL-3916 --- .../junit/SeleniumJavaScriptClickTest.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumJavaScriptClickTest.java diff --git a/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumJavaScriptClickTest.java b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumJavaScriptClickTest.java new file mode 100644 index 0000000000..dafafd72ef --- /dev/null +++ b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumJavaScriptClickTest.java @@ -0,0 +1,56 @@ +package java.com.baeldung.selenium.junit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.openqa.selenium.By; +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.chrome.ChromeDriver; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; + +import static org.junit.Assert.assertEquals; + +public class SeleniumJavaScriptClickTest { + + private WebDriver driver; + private WebDriverWait wait; + + @Before + public void setUp() { + System.setProperty("webdriver.chrome.driver", "chromedriver.exe"); + driver = new ChromeDriver(); + wait = new WebDriverWait(driver, 5000); + } + + @After + public void cleanUp() { + driver.close(); + } + + @Test + public void should_search_for_selenium_articles() { + driver.get("https://baeldung.com"); + String title = driver.getTitle(); + assertEquals("Baeldung | Java, Spring and Web Development tutorials", title); + + wait.until(ExpectedConditions.elementToBeClickable(By.className("menu-search"))); + WebElement searchButton = driver.findElement(By.className("menu-search")); + clickElement(searchButton); + + WebElement searchInput = driver.findElement(By.id("search")); + searchInput.sendKeys("Selenium"); + + wait.until(ExpectedConditions.elementToBeClickable(By.className("btn-search"))); + WebElement seeSearchResultsButton = driver.findElement(By.className("btn-search")); + clickElement(seeSearchResultsButton); + } + + private void clickElement(WebElement element) { + JavascriptExecutor executor = (JavascriptExecutor) driver; + executor.executeScript("arguments[0].click();", element); + } + +} From dbbcfc21186c55469413b73ca08c82b33fdcbf40 Mon Sep 17 00:00:00 2001 From: CHANDRAKANT Kumar Date: Wed, 6 May 2020 22:19:19 +0530 Subject: [PATCH 032/150] Refactored the codebase. --- java-es-cqrs/pom.xml | 9 ++- .../cqrs/projectors/UserProjector.java | 25 +++----- .../java/com/baeldung/patterns/crud/Main.java | 48 --------------- .../baeldung/patterns/domain/UserAddress.java | 2 - .../baeldung/patterns/domain/UserContact.java | 2 - .../java/com/baeldung/patterns/es/Main.java | 48 --------------- .../patterns/es/events/UserRemovedEvent.java | 12 ---- .../patterns/es/service/UserService.java | 48 +++++---------- .../patterns/es/service/UserUtility.java | 4 -- .../escqrs/projectors/UserProjector.java | 58 +++++-------------- .../patterns/cqrs/ApplicationUnitTest.java} | 39 +++++++++---- .../patterns/crud/ApplicationUnitTest.java | 48 +++++++++++++++ .../patterns/es/ApplicationUnitTest.java | 50 ++++++++++++++++ .../patterns/escqrs/ApplicationUnitTest.java} | 37 ++++++++---- 14 files changed, 195 insertions(+), 235 deletions(-) delete mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/crud/Main.java delete mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/es/Main.java delete mode 100644 java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserRemovedEvent.java rename java-es-cqrs/src/{main/java/com/baeldung/patterns/cqrs/Main.java => test/java/com/baeldung/patterns/cqrs/ApplicationUnitTest.java} (66%) create mode 100644 java-es-cqrs/src/test/java/com/baeldung/patterns/crud/ApplicationUnitTest.java create mode 100644 java-es-cqrs/src/test/java/com/baeldung/patterns/es/ApplicationUnitTest.java rename java-es-cqrs/src/{main/java/com/baeldung/patterns/escqrs/Main.java => test/java/com/baeldung/patterns/escqrs/ApplicationUnitTest.java} (69%) diff --git a/java-es-cqrs/pom.xml b/java-es-cqrs/pom.xml index 4160c62b0c..b1ebbf1d57 100644 --- a/java-es-cqrs/pom.xml +++ b/java-es-cqrs/pom.xml @@ -3,7 +3,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.sapient.learning - java-events + java-es-cqrs 0.0.1-SNAPSHOT java-es-cqrs @@ -16,5 +16,12 @@ lombok 1.18.12 + + junit + junit + 4.13 + test + + \ No newline at end of file diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/projectors/UserProjector.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/projectors/UserProjector.java index 25c10094c1..0344c352d9 100644 --- a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/projectors/UserProjector.java +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/projectors/UserProjector.java @@ -3,6 +3,7 @@ package com.baeldung.patterns.cqrs.projectors; import java.util.HashMap; import java.util.HashSet; import java.util.Map; +import java.util.Optional; import java.util.Set; import com.baeldung.patterns.cqrs.repository.UserReadRepository; @@ -21,36 +22,28 @@ public class UserProjector { } public void project(User user) { - UserContact userContact = readRepository.getUserContact(user.getUserid()); - if (userContact == null) - userContact = new UserContact(); - userContact.setContacts(user.getContacts()); + UserContact userContact = Optional.ofNullable(readRepository.getUserContact(user.getUserid())) + .orElse(new UserContact()); Map> contactByType = new HashMap<>(); for (Contact contact : user.getContacts()) { - Set contacts = contactByType.get(contact.getType()); - if (contacts == null) - contacts = new HashSet<>(); + Set contacts = Optional.ofNullable(contactByType.get(contact.getType())) + .orElse(new HashSet<>()); contacts.add(contact); contactByType.put(contact.getType(), contacts); } userContact.setContactByType(contactByType); readRepository.addUserContact(user.getUserid(), userContact); - UserAddress userAddress = readRepository.getUserAddress(user.getUserid()); - if (userAddress == null) - userAddress = new UserAddress(); - userAddress.setAddresses(user.getAddresses()); + UserAddress userAddress = Optional.ofNullable(readRepository.getUserAddress(user.getUserid())) + .orElse(new UserAddress()); Map> addressByRegion = new HashMap<>(); for (Address address : user.getAddresses()) { - Set
addresses = addressByRegion.get(address.getState()); - if (addresses == null) - addresses = new HashSet<>(); + Set
addresses = Optional.ofNullable(addressByRegion.get(address.getState())) + .orElse(new HashSet<>()); addresses.add(address); addressByRegion.put(address.getState(), addresses); } userAddress.setAddressByRegion(addressByRegion); readRepository.addUserAddress(user.getUserid(), userAddress); - } - } diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/crud/Main.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/crud/Main.java deleted file mode 100644 index 1f20e0be38..0000000000 --- a/java-es-cqrs/src/main/java/com/baeldung/patterns/crud/Main.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.patterns.crud; - -import java.util.UUID; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import com.baeldung.patterns.crud.repository.UserRepository; -import com.baeldung.patterns.crud.service.UserService; -import com.baeldung.patterns.domain.Address; -import com.baeldung.patterns.domain.Contact; - -public class Main { - - public static void main(String[] args) throws Exception { - - UserRepository repository = new UserRepository(); - UserService service = new UserService(repository); - String userId = UUID.randomUUID() - .toString(); - - service.createUser(userId, "Tom", "Sawyer"); - service.updateUser(userId, - Stream.of( - new Contact("EMAIL", "tom.sawyer@gmail.com"), - new Contact("EMAIL", "tom.sawyer@rediff.com"), - new Contact("PHONE", "700-000-0001")) - .collect(Collectors.toSet()), - Stream.of( - new Address("New York", "NY", "10001"), - new Address("Los Angeles", "CA", "90001"), - new Address("Housten", "TX", "77001")) - .collect(Collectors.toSet())); - service.updateUser(userId, - Stream.of( - new Contact("EMAIL", "tom.sawyer@gmail.com"), - new Contact("PHONE", "700-000-0001")) - .collect(Collectors.toSet()), - Stream.of( - new Address("New York", "NY", "10001"), - new Address("Housten", "TX", "77001")) - .collect(Collectors.toSet())); - - System.out.println(service.getContactByType(userId, "EMAIL")); - System.out.println(service.getAddressByRegion(userId, "NY")); - - } - -} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserAddress.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserAddress.java index 33f9bdf28f..8105a53265 100644 --- a/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserAddress.java +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserAddress.java @@ -1,7 +1,6 @@ package com.baeldung.patterns.domain; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; import java.util.Set; @@ -10,7 +9,6 @@ import lombok.Data; @Data public class UserAddress { - private Set
addresses = new HashSet<>(); private Map> addressByRegion = new HashMap<>(); } diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserContact.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserContact.java index 4f2ba812a4..1768dadc39 100644 --- a/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserContact.java +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserContact.java @@ -1,7 +1,6 @@ package com.baeldung.patterns.domain; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; import java.util.Set; @@ -10,7 +9,6 @@ import lombok.Data; @Data public class UserContact { - private Set contacts = new HashSet<>(); private Map> contactByType = new HashMap<>(); } diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/Main.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/Main.java deleted file mode 100644 index 77649088e9..0000000000 --- a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/Main.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.patterns.es; - -import java.util.UUID; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import com.baeldung.patterns.domain.Address; -import com.baeldung.patterns.domain.Contact; -import com.baeldung.patterns.es.repository.EventStore; -import com.baeldung.patterns.es.service.UserService; - -public class Main { - - public static void main(String[] args) throws Exception { - - EventStore repository = new EventStore(); - UserService service = new UserService(repository); - String userId = UUID.randomUUID() - .toString(); - - service.createUser(userId, "Tom", "Sawyer"); - service.updateUser(userId, - Stream.of( - new Contact("EMAIL", "tom.sawyer@gmail.com"), - new Contact("EMAIL", "tom.sawyer@rediff.com"), - new Contact("PHONE", "700-000-0001")) - .collect(Collectors.toSet()), - Stream.of( - new Address("New York", "NY", "10001"), - new Address("Los Angeles", "CA", "90001"), - new Address("Housten", "TX", "77001")) - .collect(Collectors.toSet())); - service.updateUser(userId, - Stream.of( - new Contact("EMAIL", "tom.sawyer@gmail.com"), - new Contact("PHONE", "700-000-0001")) - .collect(Collectors.toSet()), - Stream.of( - new Address("New York", "NY", "10001"), - new Address("Housten", "TX", "77001")) - .collect(Collectors.toSet())); - - System.out.println(service.getContactByType(userId, "EMAIL")); - System.out.println(service.getAddressByRegion(userId, "NY")); - - } - -} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserRemovedEvent.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserRemovedEvent.java deleted file mode 100644 index b609cb1daf..0000000000 --- a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserRemovedEvent.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.patterns.es.events; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; - -@Data -@AllArgsConstructor -@EqualsAndHashCode(callSuper = false) -public class UserRemovedEvent extends Event { - -} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserService.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserService.java index 0233453d68..9650c4294f 100644 --- a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserService.java +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserService.java @@ -1,6 +1,5 @@ package com.baeldung.patterns.es.service; -import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -23,8 +22,7 @@ public class UserService { } public void createUser(String userId, String firstName, String lastName) { - UserCreatedEvent event = new UserCreatedEvent(userId, firstName, lastName); - repository.addEvent(userId, event); + repository.addEvent(userId, new UserCreatedEvent(userId, firstName, lastName)); } public void updateUser(String userId, Set contacts, Set
addresses) throws Exception { @@ -32,49 +30,30 @@ public class UserService { if (user == null) throw new Exception("User does not exist."); - List contactsToRemove = user.getContacts() + user.getContacts() .stream() .filter(c -> !contacts.contains(c)) - .collect(Collectors.toList()); - for (Contact contact : contactsToRemove) { - UserContactRemovedEvent contactRemovedEvent = new UserContactRemovedEvent(contact.getType(), contact.getDetail()); - repository.addEvent(userId, contactRemovedEvent); - } - - List contactsToAdd = contacts.stream() + .forEach(c -> repository.addEvent(userId, new UserContactRemovedEvent(c.getType(), c.getDetail()))); + contacts.stream() .filter(c -> !user.getContacts() .contains(c)) - .collect(Collectors.toList()); - for (Contact contact : contactsToAdd) { - UserContactAddedEvent contactAddedEvent = new UserContactAddedEvent(contact.getType(), contact.getDetail()); - repository.addEvent(userId, contactAddedEvent); - } - - List
addressesToRemove = user.getAddresses() + .forEach(c -> repository.addEvent(userId, new UserContactAddedEvent(c.getType(), c.getDetail()))); + user.getAddresses() .stream() .filter(a -> !addresses.contains(a)) - .collect(Collectors.toList()); - for (Address address : addressesToRemove) { - UserAddressRemovedEvent addressRemovedEvent = new UserAddressRemovedEvent(address.getCity(), address.getState(), address.getPostcode()); - repository.addEvent(userId, addressRemovedEvent); - } - - List
addressesToAdd = addresses.stream() + .forEach(a -> repository.addEvent(userId, new UserAddressRemovedEvent(a.getCity(), a.getState(), a.getPostcode()))); + addresses.stream() .filter(a -> !user.getAddresses() .contains(a)) - .collect(Collectors.toList()); - for (Address address : addressesToAdd) { - UserAddressAddedEvent addressAddedEvent = new UserAddressAddedEvent(address.getCity(), address.getState(), address.getPostcode()); - repository.addEvent(userId, addressAddedEvent); - } + .forEach(a -> repository.addEvent(userId, new UserAddressAddedEvent(a.getCity(), a.getState(), a.getPostcode()))); } public Set getContactByType(String userId, String contactType) throws Exception { User user = UserUtility.recreateUserState(repository, userId); if (user == null) throw new Exception("User does not exist."); - Set contacts = user.getContacts(); - return contacts.stream() + return user.getContacts() + .stream() .filter(c -> c.getType() .equals(contactType)) .collect(Collectors.toSet()); @@ -84,11 +63,10 @@ public class UserService { User user = UserUtility.recreateUserState(repository, userId); if (user == null) throw new Exception("User does not exist."); - Set
addresses = user.getAddresses(); - return addresses.stream() + return user.getAddresses() + .stream() .filter(a -> a.getState() .equals(state)) .collect(Collectors.toSet()); } - } diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserUtility.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserUtility.java index b7ed9208b2..e44e404588 100644 --- a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserUtility.java +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserUtility.java @@ -12,7 +12,6 @@ import com.baeldung.patterns.es.events.UserAddressRemovedEvent; import com.baeldung.patterns.es.events.UserContactAddedEvent; import com.baeldung.patterns.es.events.UserContactRemovedEvent; import com.baeldung.patterns.es.events.UserCreatedEvent; -import com.baeldung.patterns.es.events.UserRemovedEvent; import com.baeldung.patterns.es.repository.EventStore; public class UserUtility { @@ -27,9 +26,6 @@ public class UserUtility { user = new User(UUID.randomUUID() .toString(), e.getFirstName(), e.getLastName()); } - if (event instanceof UserRemovedEvent) { - user = null; - } if (event instanceof UserAddressAddedEvent) { UserAddressAddedEvent e = (UserAddressAddedEvent) event; Address address = new Address(e.getCity(), e.getState(), e.getPostCode()); diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/projectors/UserProjector.java b/java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/projectors/UserProjector.java index 036b6e8396..d388abe7cb 100644 --- a/java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/projectors/UserProjector.java +++ b/java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/projectors/UserProjector.java @@ -2,6 +2,7 @@ package com.baeldung.patterns.escqrs.projectors; import java.util.HashSet; import java.util.List; +import java.util.Optional; import java.util.Set; import com.baeldung.patterns.cqrs.repository.UserReadRepository; @@ -14,8 +15,6 @@ import com.baeldung.patterns.es.events.UserAddressAddedEvent; import com.baeldung.patterns.es.events.UserAddressRemovedEvent; import com.baeldung.patterns.es.events.UserContactAddedEvent; import com.baeldung.patterns.es.events.UserContactRemovedEvent; -import com.baeldung.patterns.es.events.UserCreatedEvent; -import com.baeldung.patterns.es.events.UserRemovedEvent; public class UserProjector { @@ -28,10 +27,6 @@ public class UserProjector { public void project(String userId, List events) { for (Event event : events) { - if (event instanceof UserCreatedEvent) - apply(userId, (UserCreatedEvent) event); - if (event instanceof UserRemovedEvent) - apply(userId, (UserRemovedEvent) event); if (event instanceof UserAddressAddedEvent) apply(userId, (UserAddressAddedEvent) event); if (event instanceof UserAddressRemovedEvent) @@ -44,25 +39,13 @@ public class UserProjector { } - public void apply(String userId, UserCreatedEvent event) { - - } - - public void apply(String userId, UserRemovedEvent event) { - - } - public void apply(String userId, UserAddressAddedEvent event) { Address address = new Address(event.getCity(), event.getState(), event.getPostCode()); - UserAddress userAddress = readRepository.getUserAddress(userId); - if (userAddress == null) - userAddress = new UserAddress(); - userAddress.getAddresses() - .add(address); - Set
addresses = userAddress.getAddressByRegion() - .get(address.getState()); - if (addresses == null) - addresses = new HashSet<>(); + UserAddress userAddress = Optional.ofNullable(readRepository.getUserAddress(userId)) + .orElse(new UserAddress()); + Set
addresses = Optional.ofNullable(userAddress.getAddressByRegion() + .get(address.getState())) + .orElse(new HashSet<>()); addresses.add(address); userAddress.getAddressByRegion() .put(address.getState(), addresses); @@ -73,30 +56,21 @@ public class UserProjector { Address address = new Address(event.getCity(), event.getState(), event.getPostCode()); UserAddress userAddress = readRepository.getUserAddress(userId); if (userAddress != null) { - userAddress.getAddresses() - .remove(address); Set
addresses = userAddress.getAddressByRegion() .get(address.getState()); - if (addresses != null) { + if (addresses != null) addresses.remove(address); - userAddress.getAddressByRegion() - .put(address.getState(), addresses); - } readRepository.addUserAddress(userId, userAddress); } } public void apply(String userId, UserContactAddedEvent event) { Contact contact = new Contact(event.getContactType(), event.getContactDetails()); - UserContact userContact = readRepository.getUserContact(userId); - if (userContact == null) - userContact = new UserContact(); - userContact.getContacts() - .add(contact); - Set contacts = userContact.getContactByType() - .get(contact.getType()); - if (contacts == null) - contacts = new HashSet<>(); + UserContact userContact = Optional.ofNullable(readRepository.getUserContact(userId)) + .orElse(new UserContact()); + Set contacts = Optional.ofNullable(userContact.getContactByType() + .get(contact.getType())) + .orElse(new HashSet<>()); contacts.add(contact); userContact.getContactByType() .put(contact.getType(), contacts); @@ -107,17 +81,11 @@ public class UserProjector { Contact contact = new Contact(event.getContactType(), event.getContactDetails()); UserContact userContact = readRepository.getUserContact(userId); if (userContact != null) { - userContact.getContacts() - .remove(contact); Set contacts = userContact.getContactByType() .get(contact.getType()); - if (contacts != null) { + if (contacts != null) contacts.remove(contact); - userContact.getContactByType() - .put(contact.getType(), contacts); - } readRepository.addUserContact(userId, userContact); } } - } diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/Main.java b/java-es-cqrs/src/test/java/com/baeldung/patterns/cqrs/ApplicationUnitTest.java similarity index 66% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/Main.java rename to java-es-cqrs/src/test/java/com/baeldung/patterns/cqrs/ApplicationUnitTest.java index 4e9c872cf1..4a324e72f6 100644 --- a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/Main.java +++ b/java-es-cqrs/src/test/java/com/baeldung/patterns/cqrs/ApplicationUnitTest.java @@ -1,9 +1,14 @@ package com.baeldung.patterns.cqrs; +import static org.junit.Assert.assertEquals; + import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.junit.Before; +import org.junit.Test; + import com.baeldung.patterns.cqrs.aggregates.UserAggregate; import com.baeldung.patterns.cqrs.commands.CreateUserCommand; import com.baeldung.patterns.cqrs.commands.UpdateUserCommand; @@ -17,15 +22,25 @@ import com.baeldung.patterns.domain.Address; import com.baeldung.patterns.domain.Contact; import com.baeldung.patterns.domain.User; -public class Main { +public class ApplicationUnitTest { - public static void main(String[] args) throws Exception { - UserWriteRepository writeRepository = new UserWriteRepository(); - UserReadRepository readRepository = new UserReadRepository(); - UserProjector projector = new UserProjector(readRepository); - UserAggregate userAggregate = new UserAggregate(writeRepository); - UserProjection userProjection = new UserProjection(readRepository); + private UserWriteRepository writeRepository; + private UserReadRepository readRepository; + private UserProjector projector; + private UserAggregate userAggregate; + private UserProjection userProjection; + @Before + public void setUp() { + writeRepository = new UserWriteRepository(); + readRepository = new UserReadRepository(); + projector = new UserProjector(readRepository); + userAggregate = new UserAggregate(writeRepository); + userProjection = new UserProjection(readRepository); + } + + @Test + public void testApplication() throws Exception { String userId = UUID.randomUUID() .toString(); User user = null; @@ -47,11 +62,13 @@ public class Main { user = userAggregate.handleUpdateUserCommand(updateUserCommand); projector.project(user); - AddressByRegionQuery addressByRegionQuery = new AddressByRegionQuery(user.getUserid(), "NY"); - System.out.println(userProjection.handle(addressByRegionQuery)); + ContactByTypeQuery contactByTypeQuery = new ContactByTypeQuery(userId, "EMAIL"); + assertEquals(Stream.of(new Contact("EMAIL", "tom.sawyer@gmail.com")) + .collect(Collectors.toSet()), userProjection.handle(contactByTypeQuery)); + AddressByRegionQuery addressByRegionQuery = new AddressByRegionQuery(userId, "NY"); + assertEquals(Stream.of(new Address("New York", "NY", "10001")) + .collect(Collectors.toSet()), userProjection.handle(addressByRegionQuery)); - ContactByTypeQuery contactByTypeQuery = new ContactByTypeQuery(user.getUserid(), "EMAIL"); - System.out.println(userProjection.handle(contactByTypeQuery)); } } diff --git a/java-es-cqrs/src/test/java/com/baeldung/patterns/crud/ApplicationUnitTest.java b/java-es-cqrs/src/test/java/com/baeldung/patterns/crud/ApplicationUnitTest.java new file mode 100644 index 0000000000..28c113bf46 --- /dev/null +++ b/java-es-cqrs/src/test/java/com/baeldung/patterns/crud/ApplicationUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.patterns.crud; + +import static org.junit.Assert.assertEquals; + +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.patterns.crud.repository.UserRepository; +import com.baeldung.patterns.crud.service.UserService; +import com.baeldung.patterns.domain.Address; +import com.baeldung.patterns.domain.Contact; + +public class ApplicationUnitTest { + + private UserRepository repository; + + @Before + public void setUp() { + repository = new UserRepository(); + } + + @Test + public void testApplication() throws Exception { + UserService service = new UserService(repository); + String userId = UUID.randomUUID() + .toString(); + + service.createUser(userId, "Tom", "Sawyer"); + service.updateUser(userId, Stream.of(new Contact("EMAIL", "tom.sawyer@gmail.com"), new Contact("EMAIL", "tom.sawyer@rediff.com"), new Contact("PHONE", "700-000-0001")) + .collect(Collectors.toSet()), + Stream.of(new Address("New York", "NY", "10001"), new Address("Los Angeles", "CA", "90001"), new Address("Housten", "TX", "77001")) + .collect(Collectors.toSet())); + service.updateUser(userId, Stream.of(new Contact("EMAIL", "tom.sawyer@gmail.com"), new Contact("PHONE", "700-000-0001")) + .collect(Collectors.toSet()), + Stream.of(new Address("New York", "NY", "10001"), new Address("Housten", "TX", "77001")) + .collect(Collectors.toSet())); + + assertEquals(Stream.of(new Contact("EMAIL", "tom.sawyer@gmail.com")) + .collect(Collectors.toSet()), service.getContactByType(userId, "EMAIL")); + assertEquals(Stream.of(new Address("New York", "NY", "10001")) + .collect(Collectors.toSet()), service.getAddressByRegion(userId, "NY")); + } + +} diff --git a/java-es-cqrs/src/test/java/com/baeldung/patterns/es/ApplicationUnitTest.java b/java-es-cqrs/src/test/java/com/baeldung/patterns/es/ApplicationUnitTest.java new file mode 100644 index 0000000000..52bdde449f --- /dev/null +++ b/java-es-cqrs/src/test/java/com/baeldung/patterns/es/ApplicationUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.patterns.es; + +import static org.junit.Assert.assertEquals; + +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.Before; +import org.junit.Test; + +import com.baeldung.patterns.domain.Address; +import com.baeldung.patterns.domain.Contact; +import com.baeldung.patterns.es.repository.EventStore; +import com.baeldung.patterns.es.service.UserService; + +public class ApplicationUnitTest { + + private EventStore repository; + private UserService service; + + @Before + public void setUp() { + repository = new EventStore(); + service = new UserService(repository); + } + + @Test + public void testApplication() throws Exception { + String userId = UUID.randomUUID() + .toString(); + + service.createUser(userId, "Tom", "Sawyer"); + service.updateUser(userId, Stream.of(new Contact("EMAIL", "tom.sawyer@gmail.com"), new Contact("EMAIL", "tom.sawyer@rediff.com"), new Contact("PHONE", "700-000-0001")) + .collect(Collectors.toSet()), + Stream.of(new Address("New York", "NY", "10001"), new Address("Los Angeles", "CA", "90001"), new Address("Housten", "TX", "77001")) + .collect(Collectors.toSet())); + service.updateUser(userId, Stream.of(new Contact("EMAIL", "tom.sawyer@gmail.com"), new Contact("PHONE", "700-000-0001")) + .collect(Collectors.toSet()), + Stream.of(new Address("New York", "NY", "10001"), new Address("Housten", "TX", "77001")) + .collect(Collectors.toSet())); + + assertEquals(Stream.of(new Contact("EMAIL", "tom.sawyer@gmail.com")) + .collect(Collectors.toSet()), service.getContactByType(userId, "EMAIL")); + assertEquals(Stream.of(new Address("New York", "NY", "10001")) + .collect(Collectors.toSet()), service.getAddressByRegion(userId, "NY")); + + } + +} diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/Main.java b/java-es-cqrs/src/test/java/com/baeldung/patterns/escqrs/ApplicationUnitTest.java similarity index 69% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/Main.java rename to java-es-cqrs/src/test/java/com/baeldung/patterns/escqrs/ApplicationUnitTest.java index 44395a75a7..22cb5235d1 100644 --- a/java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/Main.java +++ b/java-es-cqrs/src/test/java/com/baeldung/patterns/escqrs/ApplicationUnitTest.java @@ -1,10 +1,15 @@ package com.baeldung.patterns.escqrs; +import static org.junit.Assert.assertEquals; + import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.junit.Before; +import org.junit.Test; + import com.baeldung.patterns.cqrs.commands.CreateUserCommand; import com.baeldung.patterns.cqrs.commands.UpdateUserCommand; import com.baeldung.patterns.cqrs.projections.UserProjection; @@ -18,16 +23,25 @@ import com.baeldung.patterns.es.repository.EventStore; import com.baeldung.patterns.escqrs.aggregates.UserAggregate; import com.baeldung.patterns.escqrs.projectors.UserProjector; -public class Main { +public class ApplicationUnitTest { - public static void main(String[] args) throws Exception { + private EventStore writeRepository; + private UserReadRepository readRepository; + private UserProjector projector; + private UserAggregate userAggregate; + private UserProjection userProjection; - EventStore writeRepository = new EventStore(); - UserReadRepository readRepository = new UserReadRepository(); - UserProjector projector = new UserProjector(readRepository); - UserAggregate userAggregate = new UserAggregate(writeRepository); - UserProjection userProjection = new UserProjection(readRepository); + @Before + public void setUp() { + writeRepository = new EventStore(); + readRepository = new UserReadRepository(); + projector = new UserProjector(readRepository); + userAggregate = new UserAggregate(writeRepository); + userProjection = new UserProjection(readRepository); + } + @Test + public void testApplication() throws Exception { String userId = UUID.randomUUID() .toString(); List events = null; @@ -50,11 +64,12 @@ public class Main { events = userAggregate.handleUpdateUserCommand(updateUserCommand); projector.project(userId, events); - AddressByRegionQuery addressByRegionQuery = new AddressByRegionQuery(userId, "NY"); - System.out.println(userProjection.handle(addressByRegionQuery)); - ContactByTypeQuery contactByTypeQuery = new ContactByTypeQuery(userId, "EMAIL"); - System.out.println(userProjection.handle(contactByTypeQuery)); + assertEquals(Stream.of(new Contact("EMAIL", "tom.sawyer@gmail.com")) + .collect(Collectors.toSet()), userProjection.handle(contactByTypeQuery)); + AddressByRegionQuery addressByRegionQuery = new AddressByRegionQuery(userId, "NY"); + assertEquals(Stream.of(new Address("New York", "NY", "10001")) + .collect(Collectors.toSet()), userProjection.handle(addressByRegionQuery)); } From d27bcf564fef607739481695e3a12f0d4ff5af78 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Fri, 8 May 2020 14:02:17 +0200 Subject: [PATCH 033/150] update test name --- .../selenium/junit/SeleniumJavaScriptClickTest.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumJavaScriptClickTest.java b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumJavaScriptClickTest.java index dafafd72ef..68c60a7d14 100644 --- a/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumJavaScriptClickTest.java +++ b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumJavaScriptClickTest.java @@ -12,6 +12,7 @@ import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class SeleniumJavaScriptClickTest { @@ -31,7 +32,7 @@ public class SeleniumJavaScriptClickTest { } @Test - public void should_search_for_selenium_articles() { + public void whenSearchForSeleniumArticles_theReturnNotEmptyResults() { driver.get("https://baeldung.com"); String title = driver.getTitle(); assertEquals("Baeldung | Java, Spring and Web Development tutorials", title); @@ -40,12 +41,16 @@ public class SeleniumJavaScriptClickTest { WebElement searchButton = driver.findElement(By.className("menu-search")); clickElement(searchButton); + wait.until(ExpectedConditions.elementToBeClickable(By.id("search"))); WebElement searchInput = driver.findElement(By.id("search")); searchInput.sendKeys("Selenium"); wait.until(ExpectedConditions.elementToBeClickable(By.className("btn-search"))); WebElement seeSearchResultsButton = driver.findElement(By.className("btn-search")); clickElement(seeSearchResultsButton); + + int seleniumPostsCount = driver.findElements(By.className("post")).size(); + assertTrue(seleniumPostsCount > 0); } private void clickElement(WebElement element) { From 973cd2490677b11481ff9d741b4a2733a3f6a68f Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Fri, 8 May 2020 14:07:07 +0200 Subject: [PATCH 034/150] update test name --- .../baeldung/selenium/junit/SeleniumJavaScriptClickTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumJavaScriptClickTest.java b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumJavaScriptClickTest.java index 68c60a7d14..e738454ea7 100644 --- a/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumJavaScriptClickTest.java +++ b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumJavaScriptClickTest.java @@ -32,7 +32,7 @@ public class SeleniumJavaScriptClickTest { } @Test - public void whenSearchForSeleniumArticles_theReturnNotEmptyResults() { + public void whenSearchForSeleniumArticles_thenReturnNotEmptyResults() { driver.get("https://baeldung.com"); String title = driver.getTitle(); assertEquals("Baeldung | Java, Spring and Web Development tutorials", title); From ef16cf1587a59c8c2df94d098ab73e1af3911521 Mon Sep 17 00:00:00 2001 From: Marius Catalin Munteanu Date: Sat, 25 Apr 2020 12:23:24 +0300 Subject: [PATCH 035/150] BAEL-3016 Thymeleaf Formating Currencies --- .../currencies/CurrenciesController.java | 22 ++++++ .../templates/currencies/currencies.html | 21 ++++++ .../CurrenciesControllerIntegrationTest.java | 68 +++++++++++++++++++ 3 files changed, 111 insertions(+) create mode 100644 spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/currencies/CurrenciesController.java create mode 100644 spring-thymeleaf-3/src/main/resources/templates/currencies/currencies.html create mode 100644 spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/currencies/CurrenciesControllerIntegrationTest.java diff --git a/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/currencies/CurrenciesController.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/currencies/CurrenciesController.java new file mode 100644 index 0000000000..206cf32683 --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/currencies/CurrenciesController.java @@ -0,0 +1,22 @@ +package com.baeldung.thymeleaf.currencies; + +import java.util.List; +import java.util.Locale; +import java.util.Set; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; + +@Controller +public class CurrenciesController { + + @GetMapping(value = "/currency") + public String exchange( + @RequestParam(value = "amount", required = false) String amount, + @RequestParam(value = "amountList", required = false) List amountList, + Locale locale) { + + return "currencies/currencies"; + } +} diff --git a/spring-thymeleaf-3/src/main/resources/templates/currencies/currencies.html b/spring-thymeleaf-3/src/main/resources/templates/currencies/currencies.html new file mode 100644 index 0000000000..c2f44265dd --- /dev/null +++ b/spring-thymeleaf-3/src/main/resources/templates/currencies/currencies.html @@ -0,0 +1,21 @@ + + + + + Currency table + + +

Currency format by Locale

+

+ +

Currency Arrays format by Locale

+

+ +

Remove decimal values

+

+ +

Replace decimal points

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/currencies/CurrenciesControllerIntegrationTest.java b/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/currencies/CurrenciesControllerIntegrationTest.java new file mode 100644 index 0000000000..02bf8a9ee0 --- /dev/null +++ b/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/currencies/CurrenciesControllerIntegrationTest.java @@ -0,0 +1,68 @@ +package com.baeldung.thymeleaf.currencies; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +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; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc(printOnlyOnFailure = false) +public class CurrenciesControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenCallCurrencyWithSpanishLocale_ThenReturnProperCurrency() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/currency") + .header("Accept-Language", "es-ES") + .param("amount", "10032.5")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("10.032,50 €"))); + } + + @Test + public void whenCallCurrencyWithUSALocale_ThenReturnProperCurrency() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/currency") + .header("Accept-Language", "en-US") + .param("amount", "10032.5")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("$10,032.50"))); + } + + @Test + public void whenCallCurrencyWithRomanianLocaleWithArrays_ThenReturnLocaleCurrencies() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/currency") + .header("Accept-Language", "ro-RO") + .param("amountList", "10", "20", "30")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("10,00 RON, 20,00 RON, 30,00 RON"))); + } + + @Test + public void whenCallCurrencyWithUSALocaleWithoutDecimal_ThenReturnCurrencyWithoutTrailingZeros() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/currency") + .header("Accept-Language", "en-US") + .param("amount", "10032")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("$10,032"))); + } + + @Test + public void whenCallCurrencyWithUSALocale_ThenReturnReplacedDecimalPoint() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/currency") + .header("Accept-Language", "en-US") + .param("amount", "1.5")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("1,5"))); + } +} From f1dde2936b3405c112cb011afdc8b34d69d7ebe1 Mon Sep 17 00:00:00 2001 From: mikr Date: Fri, 8 May 2020 23:12:36 +0200 Subject: [PATCH 036/150] JAVA-618 Move code for 3 articles from core-java-exceptions to core-java-exceptions-2 --- .../core-java-exceptions-2/README.md | 3 +++ core-java-modules/core-java-exceptions-2/pom.xml | 6 ++++++ .../globalexceptionhandler/Arithmetic.java | 2 +- .../ArrayIndexOutOfBounds.java | 2 +- .../globalexceptionhandler/ClassCast.java | 2 +- .../globalexceptionhandler/FileNotFound.java | 2 +- .../GlobalExceptionHandler.java | 2 +- .../globalexceptionhandler/IllegalArgument.java | 2 +- .../globalexceptionhandler/IllegalState.java | 2 +- .../InterruptedExceptionExample.java | 2 +- .../globalexceptionhandler/MalformedURL.java | 2 +- .../globalexceptionhandler/NullPointer.java | 2 +- .../globalexceptionhandler/NumberFormat.java | 2 +- .../ParseExceptionExample.java | 2 +- .../StringIndexOutOfBounds.java | 2 +- .../rootcausefinder/RootCauseFinder.java | 2 +- .../trywithresource/AutoCloseableMain.java | 0 .../AutoCloseableResourcesFirst.java | 0 .../AutoCloseableResourcesSecond.java | 0 .../com/baeldung/trywithresource/MyResource.java | 0 .../GlobalExceptionHandlerUnitTest.java | 2 +- .../rootcausefinder/RootCauseFinderUnitTest.java | 15 +++++++-------- core-java-modules/core-java-exceptions/README.md | 4 ---- 23 files changed, 31 insertions(+), 27 deletions(-) rename core-java-modules/{core-java-exceptions/src/main/java/com/baeldung/exceptions => core-java-exceptions-2/src/main/java/com/baeldung}/globalexceptionhandler/Arithmetic.java (87%) rename core-java-modules/{core-java-exceptions/src/main/java/com/baeldung/exceptions => core-java-exceptions-2/src/main/java/com/baeldung}/globalexceptionhandler/ArrayIndexOutOfBounds.java (92%) rename core-java-modules/{core-java-exceptions/src/main/java/com/baeldung/exceptions => core-java-exceptions-2/src/main/java/com/baeldung}/globalexceptionhandler/ClassCast.java (92%) rename core-java-modules/{core-java-exceptions/src/main/java/com/baeldung/exceptions => core-java-exceptions-2/src/main/java/com/baeldung}/globalexceptionhandler/FileNotFound.java (91%) rename core-java-modules/{core-java-exceptions/src/main/java/com/baeldung/exceptions => core-java-exceptions-2/src/main/java/com/baeldung}/globalexceptionhandler/GlobalExceptionHandler.java (92%) rename core-java-modules/{core-java-exceptions/src/main/java/com/baeldung/exceptions => core-java-exceptions-2/src/main/java/com/baeldung}/globalexceptionhandler/IllegalArgument.java (87%) rename core-java-modules/{core-java-exceptions/src/main/java/com/baeldung/exceptions => core-java-exceptions-2/src/main/java/com/baeldung}/globalexceptionhandler/IllegalState.java (92%) rename core-java-modules/{core-java-exceptions/src/main/java/com/baeldung/exceptions => core-java-exceptions-2/src/main/java/com/baeldung}/globalexceptionhandler/InterruptedExceptionExample.java (91%) rename core-java-modules/{core-java-exceptions/src/main/java/com/baeldung/exceptions => core-java-exceptions-2/src/main/java/com/baeldung}/globalexceptionhandler/MalformedURL.java (89%) rename core-java-modules/{core-java-exceptions/src/main/java/com/baeldung/exceptions => core-java-exceptions-2/src/main/java/com/baeldung}/globalexceptionhandler/NullPointer.java (93%) rename core-java-modules/{core-java-exceptions/src/main/java/com/baeldung/exceptions => core-java-exceptions-2/src/main/java/com/baeldung}/globalexceptionhandler/NumberFormat.java (90%) rename core-java-modules/{core-java-exceptions/src/main/java/com/baeldung/exceptions => core-java-exceptions-2/src/main/java/com/baeldung}/globalexceptionhandler/ParseExceptionExample.java (90%) rename core-java-modules/{core-java-exceptions/src/main/java/com/baeldung/exceptions => core-java-exceptions-2/src/main/java/com/baeldung}/globalexceptionhandler/StringIndexOutOfBounds.java (91%) rename core-java-modules/{core-java-exceptions/src/main/java/com/baeldung/exceptions => core-java-exceptions-2/src/main/java/com/baeldung}/rootcausefinder/RootCauseFinder.java (98%) rename core-java-modules/{core-java-exceptions => core-java-exceptions-2}/src/main/java/com/baeldung/trywithresource/AutoCloseableMain.java (100%) rename core-java-modules/{core-java-exceptions => core-java-exceptions-2}/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesFirst.java (100%) rename core-java-modules/{core-java-exceptions => core-java-exceptions-2}/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesSecond.java (100%) rename core-java-modules/{core-java-exceptions => core-java-exceptions-2}/src/main/java/com/baeldung/trywithresource/MyResource.java (100%) rename core-java-modules/{core-java-exceptions/src/test/java/com/baeldung/exceptions => core-java-exceptions-2/src/test/java/com/baeldung}/globalexceptionhandler/GlobalExceptionHandlerUnitTest.java (97%) rename core-java-modules/{core-java-exceptions/src/test/java/com/baeldung/exceptions => core-java-exceptions-2/src/test/java/com/baeldung}/rootcausefinder/RootCauseFinderUnitTest.java (80%) diff --git a/core-java-modules/core-java-exceptions-2/README.md b/core-java-modules/core-java-exceptions-2/README.md index 1b8457acc4..46ffd490be 100644 --- a/core-java-modules/core-java-exceptions-2/README.md +++ b/core-java-modules/core-java-exceptions-2/README.md @@ -9,3 +9,6 @@ This module contains articles about core java exceptions - [java.net.UnknownHostException: Invalid Hostname for Server](https://www.baeldung.com/java-unknownhostexception) - [How to Handle Java SocketException](https://www.baeldung.com/java-socketexception) - [Java Suppressed Exceptions](https://www.baeldung.com/java-suppressed-exceptions) +- [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources) +- [Java Global Exception Handler](https://www.baeldung.com/java-global-exception-handler) +- [How to Find an Exception’s Root Cause in Java](https://www.baeldung.com/java-exception-root-cause) diff --git a/core-java-modules/core-java-exceptions-2/pom.xml b/core-java-modules/core-java-exceptions-2/pom.xml index cf8de3d5b6..915ec1da69 100644 --- a/core-java-modules/core-java-exceptions-2/pom.xml +++ b/core-java-modules/core-java-exceptions-2/pom.xml @@ -23,6 +23,11 @@ ${assertj-core.version} test + + org.apache.commons + commons-lang3 + ${commons.lang3.version} + @@ -30,6 +35,7 @@ UTF-8 + 3.10 3.10.0 diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/Arithmetic.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/Arithmetic.java similarity index 87% rename from core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/Arithmetic.java rename to core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/Arithmetic.java index db29198b39..57d022eb13 100644 --- a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/Arithmetic.java +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/Arithmetic.java @@ -1,4 +1,4 @@ -package com.baeldung.exceptions.globalexceptionhandler; +package com.baeldung.globalexceptionhandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/ArrayIndexOutOfBounds.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/ArrayIndexOutOfBounds.java similarity index 92% rename from core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/ArrayIndexOutOfBounds.java rename to core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/ArrayIndexOutOfBounds.java index 54c95f224c..b7c8bb1875 100644 --- a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/ArrayIndexOutOfBounds.java +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/ArrayIndexOutOfBounds.java @@ -1,4 +1,4 @@ -package com.baeldung.exceptions.globalexceptionhandler; +package com.baeldung.globalexceptionhandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/ClassCast.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/ClassCast.java similarity index 92% rename from core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/ClassCast.java rename to core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/ClassCast.java index 8f8a6cf9e6..1ef8399d3d 100644 --- a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/ClassCast.java +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/ClassCast.java @@ -1,4 +1,4 @@ -package com.baeldung.exceptions.globalexceptionhandler; +package com.baeldung.globalexceptionhandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/FileNotFound.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/FileNotFound.java similarity index 91% rename from core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/FileNotFound.java rename to core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/FileNotFound.java index a9f2e5ee84..a94e294016 100644 --- a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/FileNotFound.java +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/FileNotFound.java @@ -1,4 +1,4 @@ -package com.baeldung.exceptions.globalexceptionhandler; +package com.baeldung.globalexceptionhandler; import java.io.BufferedReader; import java.io.File; diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/GlobalExceptionHandler.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/GlobalExceptionHandler.java similarity index 92% rename from core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/GlobalExceptionHandler.java rename to core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/GlobalExceptionHandler.java index f2e89f44e3..4d3f7c1a98 100644 --- a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/GlobalExceptionHandler.java +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/GlobalExceptionHandler.java @@ -1,4 +1,4 @@ -package com.baeldung.exceptions.globalexceptionhandler; +package com.baeldung.globalexceptionhandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/IllegalArgument.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/IllegalArgument.java similarity index 87% rename from core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/IllegalArgument.java rename to core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/IllegalArgument.java index d54757dfac..cb7f981e17 100644 --- a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/IllegalArgument.java +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/IllegalArgument.java @@ -1,4 +1,4 @@ -package com.baeldung.exceptions.globalexceptionhandler; +package com.baeldung.globalexceptionhandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/IllegalState.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/IllegalState.java similarity index 92% rename from core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/IllegalState.java rename to core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/IllegalState.java index 0a812d2b82..105ca155b7 100644 --- a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/IllegalState.java +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/IllegalState.java @@ -1,4 +1,4 @@ -package com.baeldung.exceptions.globalexceptionhandler; +package com.baeldung.globalexceptionhandler; import java.util.ArrayList; import java.util.Iterator; diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/InterruptedExceptionExample.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/InterruptedExceptionExample.java similarity index 91% rename from core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/InterruptedExceptionExample.java rename to core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/InterruptedExceptionExample.java index d0c8bb2cd0..3b37168013 100644 --- a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/InterruptedExceptionExample.java +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/InterruptedExceptionExample.java @@ -1,4 +1,4 @@ -package com.baeldung.exceptions.globalexceptionhandler; +package com.baeldung.globalexceptionhandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/MalformedURL.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/MalformedURL.java similarity index 89% rename from core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/MalformedURL.java rename to core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/MalformedURL.java index 9a02f005fd..cc1f39ea69 100644 --- a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/MalformedURL.java +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/MalformedURL.java @@ -1,4 +1,4 @@ -package com.baeldung.exceptions.globalexceptionhandler; +package com.baeldung.globalexceptionhandler; import java.net.MalformedURLException; import java.net.URL; diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/NullPointer.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/NullPointer.java similarity index 93% rename from core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/NullPointer.java rename to core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/NullPointer.java index 445cbecdc8..6d6a1706a6 100644 --- a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/NullPointer.java +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/NullPointer.java @@ -1,4 +1,4 @@ -package com.baeldung.exceptions.globalexceptionhandler; +package com.baeldung.globalexceptionhandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/NumberFormat.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/NumberFormat.java similarity index 90% rename from core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/NumberFormat.java rename to core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/NumberFormat.java index 576fe51f78..7497d023ee 100644 --- a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/NumberFormat.java +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/NumberFormat.java @@ -1,4 +1,4 @@ -package com.baeldung.exceptions.globalexceptionhandler; +package com.baeldung.globalexceptionhandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/ParseExceptionExample.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/ParseExceptionExample.java similarity index 90% rename from core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/ParseExceptionExample.java rename to core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/ParseExceptionExample.java index e3b3e04b10..7def606786 100644 --- a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/ParseExceptionExample.java +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/ParseExceptionExample.java @@ -1,4 +1,4 @@ -package com.baeldung.exceptions.globalexceptionhandler; +package com.baeldung.globalexceptionhandler; import java.text.DateFormat; import java.text.ParseException; diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/StringIndexOutOfBounds.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/StringIndexOutOfBounds.java similarity index 91% rename from core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/StringIndexOutOfBounds.java rename to core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/StringIndexOutOfBounds.java index 0ee132e568..8652926777 100644 --- a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/globalexceptionhandler/StringIndexOutOfBounds.java +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/globalexceptionhandler/StringIndexOutOfBounds.java @@ -1,4 +1,4 @@ -package com.baeldung.exceptions.globalexceptionhandler; +package com.baeldung.globalexceptionhandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/rootcausefinder/RootCauseFinder.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/rootcausefinder/RootCauseFinder.java similarity index 98% rename from core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/rootcausefinder/RootCauseFinder.java rename to core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/rootcausefinder/RootCauseFinder.java index 06610f3874..cb04902dfa 100644 --- a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/rootcausefinder/RootCauseFinder.java +++ b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/rootcausefinder/RootCauseFinder.java @@ -1,4 +1,4 @@ -package com.baeldung.exceptions.rootcausefinder; +package com.baeldung.rootcausefinder; import java.time.LocalDate; import java.time.Period; diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableMain.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/trywithresource/AutoCloseableMain.java similarity index 100% rename from core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableMain.java rename to core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/trywithresource/AutoCloseableMain.java diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesFirst.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesFirst.java similarity index 100% rename from core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesFirst.java rename to core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesFirst.java diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesSecond.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesSecond.java similarity index 100% rename from core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesSecond.java rename to core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/trywithresource/AutoCloseableResourcesSecond.java diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/MyResource.java b/core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/trywithresource/MyResource.java similarity index 100% rename from core-java-modules/core-java-exceptions/src/main/java/com/baeldung/trywithresource/MyResource.java rename to core-java-modules/core-java-exceptions-2/src/main/java/com/baeldung/trywithresource/MyResource.java diff --git a/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/globalexceptionhandler/GlobalExceptionHandlerUnitTest.java b/core-java-modules/core-java-exceptions-2/src/test/java/com/baeldung/globalexceptionhandler/GlobalExceptionHandlerUnitTest.java similarity index 97% rename from core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/globalexceptionhandler/GlobalExceptionHandlerUnitTest.java rename to core-java-modules/core-java-exceptions-2/src/test/java/com/baeldung/globalexceptionhandler/GlobalExceptionHandlerUnitTest.java index 74ceb3b442..83347f9d9d 100644 --- a/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/globalexceptionhandler/GlobalExceptionHandlerUnitTest.java +++ b/core-java-modules/core-java-exceptions-2/src/test/java/com/baeldung/globalexceptionhandler/GlobalExceptionHandlerUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.exceptions.globalexceptionhandler; +package com.baeldung.globalexceptionhandler; import org.junit.After; import org.junit.Before; diff --git a/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/rootcausefinder/RootCauseFinderUnitTest.java b/core-java-modules/core-java-exceptions-2/src/test/java/com/baeldung/rootcausefinder/RootCauseFinderUnitTest.java similarity index 80% rename from core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/rootcausefinder/RootCauseFinderUnitTest.java rename to core-java-modules/core-java-exceptions-2/src/test/java/com/baeldung/rootcausefinder/RootCauseFinderUnitTest.java index f42388857a..ccf14c4cba 100644 --- a/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/rootcausefinder/RootCauseFinderUnitTest.java +++ b/core-java-modules/core-java-exceptions-2/src/test/java/com/baeldung/rootcausefinder/RootCauseFinderUnitTest.java @@ -1,7 +1,7 @@ -package com.baeldung.exceptions.rootcausefinder; +package com.baeldung.rootcausefinder; -import com.baeldung.exceptions.rootcausefinder.RootCauseFinder.CalculationException; -import com.baeldung.exceptions.rootcausefinder.RootCauseFinder.DateOutOfRangeException; +import com.baeldung.rootcausefinder.RootCauseFinder.CalculationException; +import com.baeldung.rootcausefinder.RootCauseFinder.DateOutOfRangeException; import com.google.common.base.Throwables; import org.apache.commons.lang3.exception.ExceptionUtils; import org.junit.jupiter.api.Assertions; @@ -11,8 +11,7 @@ import java.time.LocalDate; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoUnit; -import static com.baeldung.exceptions.rootcausefinder.RootCauseFinder.AgeCalculator; -import static com.baeldung.exceptions.rootcausefinder.RootCauseFinder.findCauseUsingPlainJava; +import static com.baeldung.rootcausefinder.RootCauseFinder.AgeCalculator; import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -38,7 +37,7 @@ public class RootCauseFinderUnitTest { try { AgeCalculator.calculateAge("010102"); } catch (CalculationException ex) { - assertTrue(findCauseUsingPlainJava(ex) instanceof DateTimeParseException); + assertTrue(RootCauseFinder.findCauseUsingPlainJava(ex) instanceof DateTimeParseException); } } @@ -47,7 +46,7 @@ public class RootCauseFinderUnitTest { try { AgeCalculator.calculateAge("2020-04-04"); } catch (CalculationException ex) { - assertTrue(findCauseUsingPlainJava(ex) instanceof DateOutOfRangeException); + assertTrue(RootCauseFinder.findCauseUsingPlainJava(ex) instanceof DateOutOfRangeException); } } @@ -56,7 +55,7 @@ public class RootCauseFinderUnitTest { try { AgeCalculator.calculateAge(null); } catch (Exception ex) { - assertTrue(findCauseUsingPlainJava(ex) instanceof IllegalArgumentException); + assertTrue(RootCauseFinder.findCauseUsingPlainJava(ex) instanceof IllegalArgumentException); } } diff --git a/core-java-modules/core-java-exceptions/README.md b/core-java-modules/core-java-exceptions/README.md index b7222540e9..5f47aa69fb 100644 --- a/core-java-modules/core-java-exceptions/README.md +++ b/core-java-modules/core-java-exceptions/README.md @@ -12,9 +12,5 @@ This module contains articles about core java exceptions - [“Sneaky Throws” in Java](https://www.baeldung.com/java-sneaky-throws) - [The StackOverflowError in Java](https://www.baeldung.com/java-stack-overflow-error) - [Checked and Unchecked Exceptions in Java](https://www.baeldung.com/java-checked-unchecked-exceptions) -- [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources) -- [Java Global Exception Handler](https://www.baeldung.com/java-global-exception-handler) - [Common Java Exceptions](https://www.baeldung.com/java-common-exceptions) -- [How to Find an Exception’s Root Cause in Java](https://www.baeldung.com/java-exception-root-cause) -- [Is It a Bad Practice to Catch Throwable?](https://www.baeldung.com/java-catch-throwable-bad-practice) - [[Next -->]](/core-java-modules/core-java-exceptions-2) \ No newline at end of file From c2637f15094888501070d52d4e535fa00e54c033 Mon Sep 17 00:00:00 2001 From: mikr Date: Sat, 9 May 2020 14:56:21 +0200 Subject: [PATCH 037/150] BAEL-1524 Split spring-boot-persistence module --- .../spring-boot-persistence-2/README.md | 4 + .../spring-boot-persistence-2/pom.xml | 17 +++ .../application/Application.java | 24 ++-- .../controllers/CustomerController.java | 65 +++++----- .../application/entities/Customer.java | 110 ++++++++-------- .../repositories/CustomerRepository.java | 16 +-- .../SpringBootConsoleApplication.java | 0 .../application/entities/Customer.java | 0 .../repositories/CustomerRepository.java | 0 .../runners/CommandLineCrudRunner.java | 0 .../resources/persistence-derby.properties | 8 ++ .../persistence-generic-entity.properties | 8 ++ .../resources/persistence-hsqldb.properties | 8 ++ .../resources/persistence-sqlite.properties | 7 + .../tests/CustomerControllerUnitTest.java | 122 +++++++++--------- ...otTomcatConnectionPoolIntegrationTest.java | 0 .../spring-boot-persistence/README.MD | 6 +- 17 files changed, 222 insertions(+), 173 deletions(-) rename persistence-modules/{spring-boot-persistence => spring-boot-persistence-2}/src/main/java/com/baeldung/springboothsqldb/application/Application.java (96%) rename persistence-modules/{spring-boot-persistence => spring-boot-persistence-2}/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java (92%) rename persistence-modules/{spring-boot-persistence => spring-boot-persistence-2}/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java (95%) rename persistence-modules/{spring-boot-persistence => spring-boot-persistence-2}/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java (97%) rename persistence-modules/{spring-boot-persistence => spring-boot-persistence-2}/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java (100%) rename persistence-modules/{spring-boot-persistence => spring-boot-persistence-2}/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java (100%) rename persistence-modules/{spring-boot-persistence => spring-boot-persistence-2}/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java (100%) rename persistence-modules/{spring-boot-persistence => spring-boot-persistence-2}/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java (100%) create mode 100644 persistence-modules/spring-boot-persistence-2/src/main/resources/persistence-derby.properties create mode 100644 persistence-modules/spring-boot-persistence-2/src/main/resources/persistence-generic-entity.properties create mode 100644 persistence-modules/spring-boot-persistence-2/src/main/resources/persistence-hsqldb.properties create mode 100644 persistence-modules/spring-boot-persistence-2/src/main/resources/persistence-sqlite.properties rename persistence-modules/{spring-boot-persistence => spring-boot-persistence-2}/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerUnitTest.java (97%) rename persistence-modules/{spring-boot-persistence => spring-boot-persistence-2}/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java (100%) diff --git a/persistence-modules/spring-boot-persistence-2/README.md b/persistence-modules/spring-boot-persistence-2/README.md index 5d171fb2ca..8bf9381093 100644 --- a/persistence-modules/spring-boot-persistence-2/README.md +++ b/persistence-modules/spring-boot-persistence-2/README.md @@ -1,3 +1,7 @@ ### Relevant Articles: - [Using JDBI with Spring Boot](https://www.baeldung.com/spring-boot-jdbi) +- [Configuring a Tomcat Connection Pool in Spring Boot](https://www.baeldung.com/spring-boot-tomcat-connection-pool) +- [Integrating Spring Boot with HSQLDB](https://www.baeldung.com/spring-boot-hsqldb) +- [List of In-Memory Databases](http://www.baeldung.com/java-in-memory-databases) +- More articles: [[<-- prev]](../spring-boot-persistence) \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-2/pom.xml b/persistence-modules/spring-boot-persistence-2/pom.xml index 9f456fa8af..58432a5c9c 100644 --- a/persistence-modules/spring-boot-persistence-2/pom.xml +++ b/persistence-modules/spring-boot-persistence-2/pom.xml @@ -104,6 +104,23 @@ tomcat-jdbc + + mysql + mysql-connector-java + + + org.xerial + sqlite-jdbc + + + org.apache.derby + derby + + + org.hsqldb + hsqldb + + diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/Application.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/Application.java similarity index 96% rename from persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/Application.java rename to persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/Application.java index c5a5c291c6..bde8346482 100644 --- a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/Application.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/Application.java @@ -1,12 +1,12 @@ -package com.baeldung.springboothsqldb.application; - -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); - } -} +package com.baeldung.springboothsqldb.application; + +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/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java similarity index 92% rename from persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java rename to persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java index 8229a1d1c0..045612a86f 100644 --- a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/controllers/CustomerController.java @@ -1,33 +1,32 @@ -package com.baeldung.springboothsqldb.application.controllers; - -import com.baeldung.springboothsqldb.application.entities.Customer; -import com.baeldung.springboothsqldb.application.repositories.CustomerRepository; -import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class CustomerController { - - private final CustomerRepository customerRepository; - - @Autowired - public CustomerController(CustomerRepository customerRepository) { - this.customerRepository = customerRepository; - } - - @PostMapping("/customers") - public Customer addCustomer(@RequestBody Customer customer) { - customerRepository.save(customer); - return customer; - } - - @GetMapping("/customers") - public List getCustomers() { - return (List) customerRepository.findAll(); - } -} +package com.baeldung.springboothsqldb.application.controllers; + +import com.baeldung.springboothsqldb.application.entities.Customer; +import com.baeldung.springboothsqldb.application.repositories.CustomerRepository; +import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class CustomerController { + + private final CustomerRepository customerRepository; + + @Autowired + public CustomerController(CustomerRepository customerRepository) { + this.customerRepository = customerRepository; + } + + @PostMapping("/customers") + public Customer addCustomer(@RequestBody Customer customer) { + customerRepository.save(customer); + return customer; + } + + @GetMapping("/customers") + public List getCustomers() { + return (List) customerRepository.findAll(); + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java similarity index 95% rename from persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java rename to persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java index 636a80e272..ee2735abb8 100644 --- a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java @@ -1,55 +1,55 @@ -package com.baeldung.springboothsqldb.application.entities; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "customers") -public class Customer { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - private String name; - private String email; - - public Customer() {} - - public Customer(String name, String email) { - this.name = name; - this.email = email; - } - - public void setId(long id) { - this.id = id; - } - - public long getId() { - return id; - } - - public void setName(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getEmail() { - return email; - } - - @Override - public String toString() { - return "Customer{" + "id=" + id + ", name=" + name + ", email=" + email + '}'; - } -} +package com.baeldung.springboothsqldb.application.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "customers") +public class Customer { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + private String name; + private String email; + + public Customer() {} + + public Customer(String name, String email) { + this.name = name; + this.email = email; + } + + public void setId(long id) { + this.id = id; + } + + public long getId() { + return id; + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getEmail() { + return email; + } + + @Override + public String toString() { + return "Customer{" + "id=" + id + ", name=" + name + ", email=" + email + '}'; + } +} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java similarity index 97% rename from persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java rename to persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java index a81aa62c43..cc8a045e83 100644 --- a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/repositories/CustomerRepository.java @@ -1,8 +1,8 @@ -package com.baeldung.springboothsqldb.application.repositories; - -import com.baeldung.springboothsqldb.application.entities.Customer; -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface CustomerRepository extends CrudRepository {} +package com.baeldung.springboothsqldb.application.repositories; + +import com.baeldung.springboothsqldb.application.entities.Customer; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CustomerRepository extends CrudRepository {} diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java similarity index 100% rename from persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java rename to persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/SpringBootConsoleApplication.java diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java similarity index 100% rename from persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java rename to persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java similarity index 100% rename from persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java rename to persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/repositories/CustomerRepository.java diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java similarity index 100% rename from persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java rename to persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/runners/CommandLineCrudRunner.java diff --git a/persistence-modules/spring-boot-persistence-2/src/main/resources/persistence-derby.properties b/persistence-modules/spring-boot-persistence-2/src/main/resources/persistence-derby.properties new file mode 100644 index 0000000000..5b5ff05236 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/resources/persistence-derby.properties @@ -0,0 +1,8 @@ +jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver +jdbc.url=jdbc:derby:memory:myD;create=true +jdbc.user=sa +jdbc.pass= + +hibernate.dialect=org.hibernate.dialect.DerbyDialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-2/src/main/resources/persistence-generic-entity.properties b/persistence-modules/spring-boot-persistence-2/src/main/resources/persistence-generic-entity.properties new file mode 100644 index 0000000000..b19304cb1f --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/resources/persistence-generic-entity.properties @@ -0,0 +1,8 @@ +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +jdbc.user=sa +jdbc.pass=sa + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop diff --git a/persistence-modules/spring-boot-persistence-2/src/main/resources/persistence-hsqldb.properties b/persistence-modules/spring-boot-persistence-2/src/main/resources/persistence-hsqldb.properties new file mode 100644 index 0000000000..d045a8b7e5 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/resources/persistence-hsqldb.properties @@ -0,0 +1,8 @@ +jdbc.driverClassName=org.hsqldb.jdbc.JDBCDriver +jdbc.url=jdbc:hsqldb:mem:myDb +jdbc.user=sa +jdbc.pass= + +hibernate.dialect=org.hibernate.dialect.HSQLDialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-2/src/main/resources/persistence-sqlite.properties b/persistence-modules/spring-boot-persistence-2/src/main/resources/persistence-sqlite.properties new file mode 100644 index 0000000000..ee16081603 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/resources/persistence-sqlite.properties @@ -0,0 +1,7 @@ +jdbc.driverClassName=org.sqlite.JDBC +jdbc.url=jdbc:sqlite:memory:myDb?cache=shared +jdbc.user=sa +jdbc.pass=sa +hibernate.dialect=com.baeldung.dialect.SQLiteDialect +hibernate.hbm2ddl.auto=create-drop +hibernate.show_sql=true diff --git a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerUnitTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerUnitTest.java similarity index 97% rename from persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerUnitTest.java rename to persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerUnitTest.java index 33891e3d43..be16f8f563 100644 --- a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerUnitTest.java +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerUnitTest.java @@ -1,61 +1,61 @@ -package com.baeldung.springboothsqldb.application.tests; - -import com.baeldung.springboothsqldb.application.entities.Customer; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; -import com.fasterxml.jackson.databind.SerializationFeature; -import java.nio.charset.Charset; -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.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.MediaType; -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; - -@RunWith(SpringRunner.class) -@SpringBootTest -@AutoConfigureMockMvc -public class CustomerControllerUnitTest { - - private static MediaType MEDIA_TYPE_JSON; - - @Autowired - private MockMvc mockMvc; - - @Before - public void setUpJsonMediaType() { - MEDIA_TYPE_JSON = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - - } - - @Test - public void whenPostHttpRequesttoCustomers_thenStatusOK() throws Exception { - Customer customer = new Customer("John", "john@domain.com"); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); - ObjectWriter objectWriter = mapper.writer().withDefaultPrettyPrinter(); - String requestJson = objectWriter.writeValueAsString(customer); - - this.mockMvc - .perform(MockMvcRequestBuilders.post("/customers") - .contentType(MEDIA_TYPE_JSON) - .content(requestJson) - ) - - .andExpect(MockMvcResultMatchers.status().isOk()); - } - - @Test - public void whenGetHttpRequesttoCustomers_thenStatusOK() throws Exception { - this.mockMvc - .perform(MockMvcRequestBuilders.get("/customers")) - - .andExpect(MockMvcResultMatchers.content().contentType(MEDIA_TYPE_JSON)) - .andExpect(MockMvcResultMatchers.status().isOk()); - } -} +package com.baeldung.springboothsqldb.application.tests; + +import com.baeldung.springboothsqldb.application.entities.Customer; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.SerializationFeature; +import java.nio.charset.Charset; +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.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +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; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +public class CustomerControllerUnitTest { + + private static MediaType MEDIA_TYPE_JSON; + + @Autowired + private MockMvc mockMvc; + + @Before + public void setUpJsonMediaType() { + MEDIA_TYPE_JSON = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); + + } + + @Test + public void whenPostHttpRequesttoCustomers_thenStatusOK() throws Exception { + Customer customer = new Customer("John", "john@domain.com"); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); + ObjectWriter objectWriter = mapper.writer().withDefaultPrettyPrinter(); + String requestJson = objectWriter.writeValueAsString(customer); + + this.mockMvc + .perform(MockMvcRequestBuilders.post("/customers") + .contentType(MEDIA_TYPE_JSON) + .content(requestJson) + ) + + .andExpect(MockMvcResultMatchers.status().isOk()); + } + + @Test + public void whenGetHttpRequesttoCustomers_thenStatusOK() throws Exception { + this.mockMvc + .perform(MockMvcRequestBuilders.get("/customers")) + + .andExpect(MockMvcResultMatchers.content().contentType(MEDIA_TYPE_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()); + } +} diff --git a/persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java similarity index 100% rename from persistence-modules/spring-boot-persistence/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java rename to persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/tomcatconnectionpool/test/application/SpringBootTomcatConnectionPoolIntegrationTest.java diff --git a/persistence-modules/spring-boot-persistence/README.MD b/persistence-modules/spring-boot-persistence/README.MD index 96eb326cbe..d6ef239448 100644 --- a/persistence-modules/spring-boot-persistence/README.MD +++ b/persistence-modules/spring-boot-persistence/README.MD @@ -3,10 +3,8 @@ - [Spring Boot with Multiple SQL Import Files](http://www.baeldung.com/spring-boot-sql-import-files) - [Configuring Separate Spring DataSource for Tests](http://www.baeldung.com/spring-testing-separate-data-source) - [Quick Guide on Loading Initial Data with Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql) -- [Configuring a Tomcat Connection Pool in Spring Boot](https://www.baeldung.com/spring-boot-tomcat-connection-pool) -- [Hibernate Field Naming with Spring Boot](https://www.baeldung.com/hibernate-field-naming-spring-boot) -- [Integrating Spring Boot with HSQLDB](https://www.baeldung.com/spring-boot-hsqldb) - [Configuring a DataSource Programmatically in Spring Boot](https://www.baeldung.com/spring-boot-configure-data-source-programmatic) - [Resolving “Failed to Configure a DataSource” Error](https://www.baeldung.com/spring-boot-failed-to-configure-data-source) +- [Hibernate Field Naming with Spring Boot](https://www.baeldung.com/hibernate-field-naming-spring-boot) - [Spring Boot with Hibernate](https://www.baeldung.com/spring-boot-hibernate) -- [List of In-Memory Databases](http://www.baeldung.com/java-in-memory-databases) \ No newline at end of file +- More articles: [[more -->]](../spring-boot-persistence-2) \ No newline at end of file From ab3336e9b0f6f0f8b37b2c7f6302de3a04e718ef Mon Sep 17 00:00:00 2001 From: CHANDRAKANT Kumar Date: Sat, 9 May 2020 18:59:56 +0530 Subject: [PATCH 038/150] Updated pom descriptor and formatting. --- java-es-cqrs/.gitignore | 29 ---------------------- java-es-cqrs/pom.xml | 53 ++++++++++++++++++++++------------------- pom.xml | 2 ++ 3 files changed, 30 insertions(+), 54 deletions(-) delete mode 100644 java-es-cqrs/.gitignore diff --git a/java-es-cqrs/.gitignore b/java-es-cqrs/.gitignore deleted file mode 100644 index 153c9335eb..0000000000 --- a/java-es-cqrs/.gitignore +++ /dev/null @@ -1,29 +0,0 @@ -HELP.md -/target/ -!.mvn/wrapper/maven-wrapper.jar - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -/build/ - -### VS Code ### -.vscode/ diff --git a/java-es-cqrs/pom.xml b/java-es-cqrs/pom.xml index b1ebbf1d57..8760a38262 100644 --- a/java-es-cqrs/pom.xml +++ b/java-es-cqrs/pom.xml @@ -1,27 +1,30 @@ - 4.0.0 - com.sapient.learning - java-es-cqrs - 0.0.1-SNAPSHOT - java-es-cqrs - - 1.8 - 1.8 - - - - org.projectlombok - lombok - 1.18.12 - - - junit - junit - 4.13 - test - - - + 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 + java-es-cqrs + 1.0-SNAPSHOT + java-es-cqrs + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + 1.8 + 1.8 + + + + org.projectlombok + lombok + 1.18.12 + + + junit + junit + 4.13 + test + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 2f4579c999..9a4b40b950 100644 --- a/pom.xml +++ b/pom.xml @@ -568,6 +568,7 @@ rxjava-operators atomikos + java-es-cqrs @@ -1083,6 +1084,7 @@ rxjava-operators atomikos + java-es-cqrs From 70379f1010d57e044a2f604495ded490154c7ec7 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 10 May 2020 18:07:39 +0300 Subject: [PATCH 039/150] Update README.md --- persistence-modules/spring-jpa/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/persistence-modules/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md index 599a667a13..5db88cd5ee 100644 --- a/persistence-modules/spring-jpa/README.md +++ b/persistence-modules/spring-jpa/README.md @@ -13,7 +13,6 @@ - [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring) - [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries) - [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many) -- [Spring Persistence (Hibernate and JPA) with a JNDI datasource](https://www.baeldung.com/spring-persistence-hibernate-and-jpa-with-a-jndi-datasource/) ### Eclipse Config From 714034ccf0b2fdd09d32401b46576f309fd4e1b2 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Sun, 10 May 2020 22:31:27 +0200 Subject: [PATCH 040/150] JAVA-1653: Remove spring-boot.version property --- cas/cas-secured-app/pom.xml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/cas/cas-secured-app/pom.xml b/cas/cas-secured-app/pom.xml index 426d65c32b..bcce82c94c 100644 --- a/cas/cas-secured-app/pom.xml +++ b/cas/cas-secured-app/pom.xml @@ -16,10 +16,6 @@ ../../parent-boot-2 - - 2.2.6.RELEASE - - org.springframework.boot From bd588e7321e8e50b712cd2dd4252e1fef48738e0 Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Mon, 11 May 2020 18:23:14 +0200 Subject: [PATCH 041/150] [BAEL-2749] Refactoring and cleanup --- .../baeldung/dbunit/DataSourceDBUnitTest.java | 90 ++++++++++--------- .../baeldung/dbunit/OldSchoolDbUnitTest.java | 89 +++++++++--------- 2 files changed, 98 insertions(+), 81 deletions(-) diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java index 93c7e9a456..ab3e9f3dbd 100644 --- a/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/DataSourceDBUnitTest.java @@ -24,6 +24,8 @@ import java.sql.ResultSet; import java.sql.SQLException; import static com.baeldung.dbunit.ConnectionSettings.JDBC_URL; +import static com.baeldung.dbunit.ConnectionSettings.PASSWORD; +import static com.baeldung.dbunit.ConnectionSettings.USER; import static java.util.stream.Collectors.joining; import static org.assertj.core.api.Assertions.assertThat; import static org.dbunit.Assertion.assertEqualsIgnoreCols; @@ -33,12 +35,14 @@ public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { private static final Logger logger = LoggerFactory.getLogger(DataSourceDBUnitTest.class); + private Connection connection; + @Override protected DataSource getDataSource() { JdbcDataSource dataSource = new JdbcDataSource(); dataSource.setURL(JDBC_URL); - dataSource.setUser("sa"); - dataSource.setPassword(""); + dataSource.setUser(USER); + dataSource.setPassword(PASSWORD); return dataSource; } @@ -62,6 +66,7 @@ public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { @Before public void setUp() throws Exception { super.setUp(); + connection = getConnection().getConnection(); } @After @@ -71,9 +76,7 @@ public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { @Test public void givenDataSet_whenSelect_thenFirstTitleIsGreyTShirt() throws SQLException { - final Connection connection = getDataSource().getConnection(); - - final ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); + ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); assertThat(rs.next()).isTrue(); assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); @@ -81,58 +84,59 @@ public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { @Test public void givenDataSetEmptySchema_whenDataSetCreated_thenTablesAreEqual() throws Exception { - final IDataSet expectedDataSet = getDataSet(); - final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); - final IDataSet databaseDataSet = getConnection().createDataSet(); - final ITable actualTable = databaseDataSet.getTable("CLIENTS"); + IDataSet expectedDataSet = getDataSet(); + ITable expectedTable = expectedDataSet.getTable("CLIENTS"); + IDataSet databaseDataSet = getConnection().createDataSet(); + ITable actualTable = databaseDataSet.getTable("CLIENTS"); Assertion.assertEquals(expectedTable, actualTable); } @Test public void givenDataSet_whenInsert_thenTableHasNewClient() throws Exception { - try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-user.xml")) { - final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); - final ITable expectedTable = expectedDataSet.getTable("CLIENTS"); - final Connection conn = getDataSource().getConnection(); + try (InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-user.xml")) { + // given + IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + ITable expectedTable = expectedDataSet.getTable("CLIENTS"); + Connection conn = getDataSource().getConnection(); + // when conn.createStatement() - .executeUpdate( - "INSERT INTO CLIENTS (first_name, last_name) VALUES ('John', 'Jansen')"); - final ITable actualData = getConnection() - .createQueryTable( - "result_name", - "SELECT * FROM CLIENTS WHERE last_name='Jansen'"); + .executeUpdate("INSERT INTO CLIENTS (first_name, last_name) VALUES ('John', 'Jansen')"); + ITable actualData = getConnection() + .createQueryTable("result_name", "SELECT * FROM CLIENTS WHERE last_name='Jansen'"); + // then assertEqualsIgnoreCols(expectedTable, actualData, new String[] { "id" }); } } @Test public void givenDataSet_whenDelete_thenItemIsDeleted() throws Exception { - final Connection connection = getConnection().getConnection(); - - try (final InputStream is = DataSourceDBUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete.xml")) { + try (InputStream is = DataSourceDBUnitTest.class.getClassLoader() + .getResourceAsStream("dbunit/items_exp_delete.xml")) { + // given ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS"); + // when connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); - final IDataSet databaseDataSet = getConnection().createDataSet(); + // then + IDataSet databaseDataSet = getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("ITEMS"); - Assertion.assertEquals(expectedTable, actualTable); } } @Test public void givenDataSet_whenUpdate_thenItemHasNewName() throws Exception { - final Connection connection = getConnection().getConnection(); - - try (final InputStream is = DataSourceDBUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename.xml")) { + try (InputStream is = DataSourceDBUnitTest.class.getClassLoader() + .getResourceAsStream("dbunit/items_exp_rename.xml")) { + // given ITable expectedTable = (new FlatXmlDataSetBuilder().build(is)).getTable("ITEMS"); connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); - final IDataSet databaseDataSet = getConnection().createDataSet(); + IDataSet databaseDataSet = getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("ITEMS"); Assertion.assertEquals(expectedTable, actualTable); @@ -140,22 +144,24 @@ public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { } @Test - public void givenDataSet_whenInsertUnexpectedData_thenFailOnAllUnexpectedValues() throws Exception { - try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-multiple-failures.xml")) { - final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); - final ITable expectedTable = expectedDataSet.getTable("ITEMS"); - final Connection conn = getDataSource().getConnection(); - final DiffCollectingFailureHandler collectingHandler = new DiffCollectingFailureHandler(); + public void givenDataSet_whenInsertUnexpectedData_thenFail() throws Exception { + try (InputStream is = getClass().getClassLoader() + .getResourceAsStream("dbunit/expected-multiple-failures.xml")) { - conn.createStatement().executeUpdate( - "INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')"); - final ITable actualData = getConnection().createDataSet().getTable("ITEMS"); + // given + IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + ITable expectedTable = expectedDataSet.getTable("ITEMS"); + Connection conn = getDataSource().getConnection(); + DiffCollectingFailureHandler collectingHandler = new DiffCollectingFailureHandler(); + // when + conn.createStatement().executeUpdate("INSERT INTO ITEMS (title, price) VALUES ('Battery', '1000000')"); + ITable actualData = getConnection().createDataSet().getTable("ITEMS"); + + // then Assertion.assertEquals(expectedTable, actualData, collectingHandler); if (!collectingHandler.getDiffList().isEmpty()) { - String message = (String) collectingHandler - .getDiffList() - .stream() + String message = (String) collectingHandler.getDiffList().stream() .map(d -> formatDifference((Difference) d)).collect(joining("\n")); logger.error(() -> message); } @@ -163,6 +169,8 @@ public class DataSourceDBUnitTest extends DataSourceBasedDBTestCase { } private static String formatDifference(Difference diff) { - return "expected value in " + diff.getExpectedTable().getTableMetaData().getTableName() + "." + diff.getColumnName() + " row " + diff.getRowIndex() + ":" + diff.getExpectedValue() + ", but was: " + diff.getActualValue(); + return "expected value in " + diff.getExpectedTable().getTableMetaData().getTableName() + "." + diff + .getColumnName() + " row " + diff.getRowIndex() + ":" + diff.getExpectedValue() + ", but was: " + diff + .getActualValue(); } } diff --git a/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java b/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java index 6243af9676..e2db31283f 100644 --- a/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java +++ b/libraries-testing/src/test/java/com/baeldung/dbunit/OldSchoolDbUnitTest.java @@ -31,13 +31,15 @@ public class OldSchoolDbUnitTest { private static IDatabaseTester tester = null; + private Connection connection; + @BeforeClass public static void setUp() throws Exception { tester = initDatabaseTester(); } private static IDatabaseTester initDatabaseTester() throws Exception { - final JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); + JdbcDatabaseTester tester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD); tester.setDataSet(initDataSet()); tester.setSetUpOperation(DatabaseOperation.REFRESH); tester.setTearDownOperation(DatabaseOperation.DELETE_ALL); @@ -45,7 +47,7 @@ public class OldSchoolDbUnitTest { } private static IDataSet initDataSet() throws Exception { - try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/data.xml")) { + try (InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/data.xml")) { return new FlatXmlDataSetBuilder().build(is); } } @@ -53,6 +55,7 @@ public class OldSchoolDbUnitTest { @Before public void setup() throws Exception { tester.onSetup(); + connection = tester.getConnection().getConnection(); } @After @@ -62,94 +65,100 @@ public class OldSchoolDbUnitTest { @Test public void givenDataSet_whenSelect_thenFirstTitleIsGreyTShirt() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - - final ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); + ResultSet rs = connection.createStatement().executeQuery("select * from ITEMS where id = 1"); assertThat(rs.next()).isTrue(); assertThat(rs.getString("title")).isEqualTo("Grey T-Shirt"); } @Test - public void givenDataSet_whenInsert_thenGetResultsAreStillEqualIfIgnoringColumnsWithDifferentProduced() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - final String[] excludedColumns = { "id", "produced" }; - try (final InputStream is = getClass().getClassLoader().getResourceAsStream("dbunit/expected-ignoring-registered_at.xml")) { - final IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); - final ITable expectedTable = DefaultColumnFilter.excludedColumnsTable( - expectedDataSet.getTable("ITEMS"), excludedColumns); + public void givenDataSet_whenInsert_thenGetResultsAreStillEqualIfIgnoringColumnsWithDifferentProduced() + throws Exception { + String[] excludedColumns = { "id", "produced" }; + try (InputStream is = getClass().getClassLoader() + .getResourceAsStream("dbunit/expected-ignoring-registered_at.xml")) { + // given + IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(is); + ITable expectedTable = DefaultColumnFilter + .excludedColumnsTable(expectedDataSet.getTable("ITEMS"), excludedColumns); - connection.createStatement().executeUpdate( - "INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())"); - - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); - final ITable actualTable = DefaultColumnFilter.excludedColumnsTable( - databaseDataSet.getTable("ITEMS"), excludedColumns); + // when + connection.createStatement() + .executeUpdate("INSERT INTO ITEMS (title, price, produced) VALUES('Necklace', 199.99, now())"); + // then + IDataSet databaseDataSet = tester.getConnection().createDataSet(); + ITable actualTable = DefaultColumnFilter + .excludedColumnsTable(databaseDataSet.getTable("ITEMS"), excludedColumns); Assertion.assertEquals(expectedTable, actualTable); } } @Test public void givenDataSet_whenDelete_thenItemIsRemoved() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - - try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete.xml")) { + try (InputStream is = OldSchoolDbUnitTest.class.getClassLoader() + .getResourceAsStream("dbunit/items_exp_delete.xml")) { + // given ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + // when connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + // then + IDataSet databaseDataSet = tester.getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("ITEMS"); - assertEquals(expectedTable, actualTable); } } @Test - public void givenDataSet_whenDelete_thenItemIsRemovedAndResultsEqualIfProducedIsIgnored() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - - try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_delete_no_produced.xml")) { - final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + public void givenDataSet_whenProductIgnoredAndDelete_thenItemIsRemoved() throws Exception { + try (InputStream is = OldSchoolDbUnitTest.class.getClassLoader() + .getResourceAsStream("dbunit/items_exp_delete_no_produced.xml")) { + // given + ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + // when connection.createStatement().executeUpdate("delete from ITEMS where id = 2"); - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + // then + IDataSet databaseDataSet = tester.getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("ITEMS"); actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[] { "produced" }); - assertEquals(expectedTable, actualTable); } } @Test public void givenDataSet_whenUpdate_thenItemHasNewName() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - - try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename.xml")) { - final ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + try (InputStream is = OldSchoolDbUnitTest.class.getClassLoader() + .getResourceAsStream("dbunit/items_exp_rename.xml")) { + // given + ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); + // when connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + // then + IDataSet databaseDataSet = tester.getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("ITEMS"); - assertEquals(expectedTable, actualTable); } } @Test public void givenDataSet_whenUpdateWithNoProduced_thenItemHasNewName() throws Exception { - final Connection connection = tester.getConnection().getConnection(); - - try (final InputStream is = OldSchoolDbUnitTest.class.getClassLoader().getResourceAsStream("dbunit/items_exp_rename_no_produced.xml")) { + try (InputStream is = OldSchoolDbUnitTest.class.getClassLoader() + .getResourceAsStream("dbunit/items_exp_rename_no_produced.xml")) { + // given ITable expectedTable = new FlatXmlDataSetBuilder().build(is).getTable("ITEMS"); expectedTable = DefaultColumnFilter.excludedColumnsTable(expectedTable, new String[] { "produced" }); + // when connection.createStatement().executeUpdate("update ITEMS set title='new name' where id = 1"); - final IDataSet databaseDataSet = tester.getConnection().createDataSet(); + // then + IDataSet databaseDataSet = tester.getConnection().createDataSet(); ITable actualTable = databaseDataSet.getTable("ITEMS"); actualTable = DefaultColumnFilter.excludedColumnsTable(actualTable, new String[] { "produced" }); assertEquals(expectedTable, actualTable); From 58d39140021958d0404fd2d8824ceee5c0aa78bf Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 14:57:01 +0800 Subject: [PATCH 042/150] Update README.md --- spring-boot-modules/spring-boot-logging-log4j2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot-modules/spring-boot-logging-log4j2/README.md b/spring-boot-modules/spring-boot-logging-log4j2/README.md index 76029caef8..aa6bb9b6e1 100644 --- a/spring-boot-modules/spring-boot-logging-log4j2/README.md +++ b/spring-boot-modules/spring-boot-logging-log4j2/README.md @@ -5,4 +5,4 @@ This module contains articles about logging in Spring Boot projects with Log4j 2 ### Relevant Articles: - [Logging in Spring Boot](https://www.baeldung.com/spring-boot-logging) - [Logging to Graylog with Spring Boot](https://www.baeldung.com/graylog-with-spring-boot) - +- [Log Groups in Spring Boot 2.1](https://www.baeldung.com/spring-boot-log-groups) From 22f622521ff1c0565438f5ef0cb61d400c9cb0ba Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Tue, 12 May 2020 12:34:28 +0530 Subject: [PATCH 043/150] JAVA-945: Migrate spring-rest-hal-browser to parent-boot-2 --- spring-rest-hal-browser/pom.xml | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/spring-rest-hal-browser/pom.xml b/spring-rest-hal-browser/pom.xml index adef8bf2b0..32a0b52875 100644 --- a/spring-rest-hal-browser/pom.xml +++ b/spring-rest-hal-browser/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -19,25 +19,26 @@ org.springframework.boot spring-boot-starter-web - ${spring-boot.version} org.springframework.boot spring-boot-starter-data-jpa - ${spring-boot.version} org.springframework.data spring-data-rest-hal-browser - ${spring-data.version} com.h2database h2 - ${h2.version} + + + net.bytebuddy + byte-buddy-dep + ${bytebuddy.version} @@ -55,9 +56,7 @@ - 2.0.3.RELEASE - 3.0.8.RELEASE - 1.4.197 + 1.10.10 1.8 1.8 From 77ebd0332e41dbf8eaba8ba23f13fc35f6ea0af1 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 15:08:21 +0800 Subject: [PATCH 044/150] Update README.md --- persistence-modules/spring-persistence-simple-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-persistence-simple-2/README.md b/persistence-modules/spring-persistence-simple-2/README.md index a6408df8f2..70eab26d45 100644 --- a/persistence-modules/spring-persistence-simple-2/README.md +++ b/persistence-modules/spring-persistence-simple-2/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Spring JdbcTemplate Unit Testing](https://www.baeldung.com/spring-jdbctemplate-testing) +- [Using a List of Values in a JdbcTemplate IN Clause](https://www.baeldung.com/spring-jdbctemplate-in-list) From 2d71bb462eac2eadb93627213d58038f07c21bfc Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 15:11:57 +0800 Subject: [PATCH 045/150] Update README.md --- core-groovy-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-groovy-2/README.md b/core-groovy-2/README.md index 95a00a1f5b..9f81ac6c16 100644 --- a/core-groovy-2/README.md +++ b/core-groovy-2/README.md @@ -13,4 +13,5 @@ This module contains articles about core Groovy concepts - [Metaprogramming in Groovy](https://www.baeldung.com/groovy-metaprogramming) - [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) From 4cd668aa49d616a68e3e97638cffb6ad75cbd55a Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 15:15:53 +0800 Subject: [PATCH 046/150] Update README.md --- core-java-modules/core-java-concurrency-advanced-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-concurrency-advanced-3/README.md b/core-java-modules/core-java-concurrency-advanced-3/README.md index b11cde5158..dfd264116c 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/README.md +++ b/core-java-modules/core-java-concurrency-advanced-3/README.md @@ -11,4 +11,5 @@ This module contains articles about advanced topics about multithreading with co - [Guide to Work Stealing in Java](https://www.baeldung.com/java-work-stealing) - [Asynchronous Programming in Java](https://www.baeldung.com/java-asynchronous-programming) - [Java Thread Deadlock and Livelock](https://www.baeldung.com/java-deadlock-livelock) +- [Guide to AtomicStampedReference in Java](https://www.baeldung.com/java-atomicstampedreference) - [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2) From f5a8cdc17f1f4f6729581970d65d2d9cd0948698 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 15:24:15 +0800 Subject: [PATCH 047/150] Update README.md --- spring-core-4/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-core-4/README.md b/spring-core-4/README.md index f882c77179..35d2711ad8 100644 --- a/spring-core-4/README.md +++ b/spring-core-4/README.md @@ -4,4 +4,5 @@ This module contains articles about core Spring functionality ## Relevant Articles: +- [Creating Spring Beans Through Factory Methods](https://www.baeldung.com/spring-beans-factory-methods) - More articles: [[<-- prev]](/spring-core-3) From 3cc4203f145505735f4c54154ad894f20ff0bf89 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 15:27:32 +0800 Subject: [PATCH 048/150] Create README.md --- spring-boot-groovy/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 spring-boot-groovy/README.md diff --git a/spring-boot-groovy/README.md b/spring-boot-groovy/README.md new file mode 100644 index 0000000000..d2472a11d0 --- /dev/null +++ b/spring-boot-groovy/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Building a Simple Web Application with Spring Boot and Groovy](https://www.baeldung.com/spring-boot-groovy-web-app) From 52d6f8c19a21be4aa0bef3ab3fe2cb602adfd17b Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 15:29:06 +0800 Subject: [PATCH 049/150] Create README.md --- kaniko/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 kaniko/README.md diff --git a/kaniko/README.md b/kaniko/README.md new file mode 100644 index 0000000000..a69a3cb683 --- /dev/null +++ b/kaniko/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [An Introduction to Kaniko](https://www.baeldung.com/ops/kaniko) From c6a47576997e94ca582b91cc4fbc88ce8eae323b Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 15:32:03 +0800 Subject: [PATCH 050/150] Update README.md --- spring-security-modules/spring-security-mvc-boot-2/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-security-modules/spring-security-mvc-boot-2/README.md b/spring-security-modules/spring-security-mvc-boot-2/README.md index 3c95086d21..7c53d03698 100644 --- a/spring-security-modules/spring-security-mvc-boot-2/README.md +++ b/spring-security-modules/spring-security-mvc-boot-2/README.md @@ -10,4 +10,5 @@ The "REST With Spring" Classes: http://github.learnspringsecurity.com - [Multiple Authentication Providers in Spring Security](https://www.baeldung.com/spring-security-multiple-auth-providers) - [Two Login Pages with Spring Security](https://www.baeldung.com/spring-security-two-login-pages) - [HTTPS using Self-Signed Certificate in Spring Boot](https://www.baeldung.com/spring-boot-https-self-signed-certificate) -- [Spring Security: Exploring JDBC Authentication](https://www.baeldung.com/spring-security-jdbc-authentication) \ No newline at end of file +- [Spring Security: Exploring JDBC Authentication](https://www.baeldung.com/spring-security-jdbc-authentication) +- [Spring Security Custom Logout Handler](https://www.baeldung.com/spring-security-custom-logout-handler) From 47cbf77ccd60b8e8049e0912ee29ad17072e6ed6 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 15:34:16 +0800 Subject: [PATCH 051/150] Update README.md --- libraries-data-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries-data-2/README.md b/libraries-data-2/README.md index f992186bd9..5e85cd9ab9 100644 --- a/libraries-data-2/README.md +++ b/libraries-data-2/README.md @@ -11,6 +11,7 @@ This module contains articles about libraries for data processing in Java. - [Guide to JMapper](https://www.baeldung.com/jmapper) - [An Introduction to SuanShu](https://www.baeldung.com/suanshu) - [Intro to Derive4J](https://www.baeldung.com/derive4j) +- [Java-R Integration](https://www.baeldung.com/java-r-integration) More articles: [[<-- prev]](/../libraries-data) ##### Building the project From 5021857d060a904e2ba9983ad36793df0fd5c6ab Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 15:34:53 +0800 Subject: [PATCH 052/150] Update README.md --- libraries-data-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries-data-2/README.md b/libraries-data-2/README.md index 5e85cd9ab9..71db902877 100644 --- a/libraries-data-2/README.md +++ b/libraries-data-2/README.md @@ -12,6 +12,7 @@ This module contains articles about libraries for data processing in Java. - [An Introduction to SuanShu](https://www.baeldung.com/suanshu) - [Intro to Derive4J](https://www.baeldung.com/derive4j) - [Java-R Integration](https://www.baeldung.com/java-r-integration) + More articles: [[<-- prev]](/../libraries-data) ##### Building the project From 8c11a0825880462821a28f59a4d23efc209fbfba Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 15:36:47 +0800 Subject: [PATCH 053/150] Update README.md --- persistence-modules/java-jpa-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/java-jpa-2/README.md b/persistence-modules/java-jpa-2/README.md index 9d46c0d814..4b822c4782 100644 --- a/persistence-modules/java-jpa-2/README.md +++ b/persistence-modules/java-jpa-2/README.md @@ -12,4 +12,5 @@ This module contains articles about the Java Persistence API (JPA) in Java. - [Combining JPA And/Or Criteria Predicates](https://www.baeldung.com/jpa-and-or-criteria-predicates) - [JPA Annotation for the PostgreSQL TEXT Type](https://www.baeldung.com/jpa-annotation-postgresql-text-type) - [Mapping a Single Entity to Multiple Tables in JPA](https://www.baeldung.com/jpa-mapping-single-entity-to-multiple-tables) +- [Constructing a JPA Query Between Unrelated Entities](https://www.baeldung.com/jpa-query-unrelated-entities) - More articles: [[<-- prev]](/java-jpa) From d880f58ea29a4ba6cffb12d7a85f380bd8b68bdf Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 15:37:25 +0800 Subject: [PATCH 054/150] Update README.md --- libraries-data-2/README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/libraries-data-2/README.md b/libraries-data-2/README.md index 71db902877..ce7a1680d1 100644 --- a/libraries-data-2/README.md +++ b/libraries-data-2/README.md @@ -12,8 +12,7 @@ This module contains articles about libraries for data processing in Java. - [An Introduction to SuanShu](https://www.baeldung.com/suanshu) - [Intro to Derive4J](https://www.baeldung.com/derive4j) - [Java-R Integration](https://www.baeldung.com/java-r-integration) - -More articles: [[<-- prev]](/../libraries-data) +- More articles: [[<-- prev]](/../libraries-data) ##### Building the project You can build the project from the command line using: *mvn clean install*, or in an IDE. If you have issues with the derive4j imports in your IDE, you have to add the folder: *target/generated-sources/annotations* to the project build path in your IDE. From 6eb847707df933fe482b109aec3d0378fa244bdd Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 15:39:16 +0800 Subject: [PATCH 055/150] Update README.md --- jee-7/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jee-7/README.md b/jee-7/README.md index adaee67d74..88359a81ec 100644 --- a/jee-7/README.md +++ b/jee-7/README.md @@ -11,3 +11,4 @@ This module contains articles about JEE 7. - [Introduction to Testing with Arquillian](https://www.baeldung.com/arquillian) - [Java EE 7 Batch Processing](https://www.baeldung.com/java-ee-7-batch-processing) - [The Difference Between CDI and EJB Singleton](https://www.baeldung.com/jee-cdi-vs-ejb-singleton) +- [Invoking a SOAP Web Service in Java](https://www.baeldung.com/java-soap-web-service) From b13fdd3291f635f37560be2e5a656e3ca1c56edb Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 15:41:00 +0800 Subject: [PATCH 056/150] Update README.md --- spring-caching/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-caching/README.md b/spring-caching/README.md index 3efbfe3eaa..52ddc4f3eb 100644 --- a/spring-caching/README.md +++ b/spring-caching/README.md @@ -3,3 +3,4 @@ - [A Guide To Caching in Spring](http://www.baeldung.com/spring-cache-tutorial) - [Spring Cache – Creating a Custom KeyGenerator](http://www.baeldung.com/spring-cache-custom-keygenerator) - [Cache Eviction in Spring Boot](https://www.baeldung.com/spring-boot-evict-cache) +- [Using Multiple Cache Managers in Spring](https://www.baeldung.com/spring-multiple-cache-managers) From b8523162b16b4600e0213e849f9cf28d90f45639 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 15:47:23 +0800 Subject: [PATCH 057/150] Update README.md --- spring-soap/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-soap/README.md b/spring-soap/README.md index c23f0bc6f0..ca5f58c67e 100644 --- a/spring-soap/README.md +++ b/spring-soap/README.md @@ -5,3 +5,4 @@ This module contains articles about SOAP APIs with Spring ### Relevant articles: - [Creating a SOAP Web Service with Spring](https://www.baeldung.com/spring-boot-soap-web-service) +- [Invoking a SOAP Web Service in Spring](https://www.baeldung.com/spring-soap-web-service) From b87db9d91fcc347391102f9a689fe8a66bfcb4d1 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 15:51:53 +0800 Subject: [PATCH 058/150] Update README.md --- java-collections-conversions-2/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/java-collections-conversions-2/README.md b/java-collections-conversions-2/README.md index 761e56253e..11dddadc5c 100644 --- a/java-collections-conversions-2/README.md +++ b/java-collections-conversions-2/README.md @@ -4,4 +4,5 @@ This module contains articles about conversions among Collection types and array ### Relevant Articles: - [Array to String Conversions](https://www.baeldung.com/java-array-to-string) -- More articles: [[<-- prev]](../java-collections-conversions) \ No newline at end of file +- [Mapping Lists with ModelMapper](https://www.baeldung.com/java-modelmapper-lists) +- More articles: [[<-- prev]](../java-collections-conversions) From fa06216e3463319eb0e975b1d5e9858bd9a22141 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 16:09:08 +0800 Subject: [PATCH 059/150] Update README.md --- core-kotlin-modules/core-kotlin-collections/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-kotlin-modules/core-kotlin-collections/README.md b/core-kotlin-modules/core-kotlin-collections/README.md index f0da2b4cfd..66f15e7419 100644 --- a/core-kotlin-modules/core-kotlin-collections/README.md +++ b/core-kotlin-modules/core-kotlin-collections/README.md @@ -9,3 +9,4 @@ This module contains articles about core Kotlin collections. - [Converting a List to Map in Kotlin](https://www.baeldung.com/kotlin-list-to-map) - [Filtering Kotlin Collections](https://www.baeldung.com/kotlin-filter-collection) - [Collection Transformations in Kotlin](https://www.baeldung.com/kotlin-collection-transformations) +- [Difference between fold and reduce in Kotlin](https://www.baeldung.com/kotlin/fold-vs-reduce) From b9cecfca592d2efde6b75f4861ee1d16ce7435c2 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 16:34:14 +0800 Subject: [PATCH 060/150] Update README.md --- terraform/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/terraform/README.md b/terraform/README.md index 19abd2ff20..b2a9539727 100644 --- a/terraform/README.md +++ b/terraform/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Introduction to Terraform](https://www.baeldung.com/ops/terraform-intro) +- [Best Practices When Using Terraform](https://www.baeldung.com/ops/terraform-best-practices) From 24a5b887170fc94172bf276d3802baffd323eda3 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 16:36:44 +0800 Subject: [PATCH 061/150] Update README.md --- spring-5-security/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-5-security/README.md b/spring-5-security/README.md index 07f2d48b7f..5a6d2d73de 100644 --- a/spring-5-security/README.md +++ b/spring-5-security/README.md @@ -9,3 +9,4 @@ This module contains articles about Spring Security 5 - [New Password Storage In Spring Security 5](https://www.baeldung.com/spring-security-5-password-storage) - [Default Password Encoder in Spring Security 5](https://www.baeldung.com/spring-security-5-default-password-encoder) - [Guide to the AuthenticationManagerResolver in Spring Security](https://www.baeldung.com/spring-security-authenticationmanagerresolver) +- [Disable Security for a Profile in Spring Boot](https://www.baeldung.com/spring-security-disable-profile) From 8fd50aea174ef1e5911b6a5ea41dc82fb8638e31 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 16:38:58 +0800 Subject: [PATCH 062/150] Update README.md --- patterns/solid/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/patterns/solid/README.md b/patterns/solid/README.md index ddd2f78b7e..cae346e3c9 100644 --- a/patterns/solid/README.md +++ b/patterns/solid/README.md @@ -1,5 +1,5 @@ ### Relevant Articles: - [A Solid Guide to Solid Principles](https://www.baeldung.com/solid-principles) - +- [Single Responsibility Principle in Java](https://www.baeldung.com/java-single-responsibility-principle) From 73a35a047ee87088d451f5a0d8bc2a7a0936600b Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 16:41:18 +0800 Subject: [PATCH 063/150] Create README.md --- gradle/gradle-employee-app/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 gradle/gradle-employee-app/README.md diff --git a/gradle/gradle-employee-app/README.md b/gradle/gradle-employee-app/README.md new file mode 100644 index 0000000000..1bf7c5e8dd --- /dev/null +++ b/gradle/gradle-employee-app/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Building a Java Application With Gradle](https://www.baeldung.com/gradle-building-a-java-app) From 7eab1879e31ced15352e90ae91e7d099951c75e5 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 16:42:44 +0800 Subject: [PATCH 064/150] Update README.md --- testing-modules/assertion-libraries/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing-modules/assertion-libraries/README.md b/testing-modules/assertion-libraries/README.md index d69457fdeb..ca4cc86f7e 100644 --- a/testing-modules/assertion-libraries/README.md +++ b/testing-modules/assertion-libraries/README.md @@ -10,4 +10,4 @@ - [Custom Assertions with AssertJ](http://www.baeldung.com/assertj-custom-assertion) - [Using Conditions with AssertJ Assertions](http://www.baeldung.com/assertj-conditions) - [AssertJ Exception Assertions](http://www.baeldung.com/assertj-exception-assertion) - +- [Asserting Log Messages With JUnit](https://www.baeldung.com/junit-asserting-logs) From ef9bd53b98c2739b6a842137551a5c808949d7bd Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 16:43:58 +0800 Subject: [PATCH 065/150] Update README.md --- jsoup/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jsoup/README.md b/jsoup/README.md index 271d04194d..690afe3099 100644 --- a/jsoup/README.md +++ b/jsoup/README.md @@ -4,6 +4,7 @@ This module contains articles about jsoup. ### Relevant Articles: - [Parsing HTML in Java with Jsoup](https://www.baeldung.com/java-with-jsoup) +- [How to add proxy support to Jsoup?](https://www.baeldung.com/java-jsoup-proxy) ### Build the Project From 8f0a779211007c2d60124417bdefe62637aa2985 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 16:46:29 +0800 Subject: [PATCH 066/150] Update README.md --- persistence-modules/spring-data-jpa-5/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-data-jpa-5/README.md b/persistence-modules/spring-data-jpa-5/README.md index e8f83654df..656e2e5e6b 100644 --- a/persistence-modules/spring-data-jpa-5/README.md +++ b/persistence-modules/spring-data-jpa-5/README.md @@ -1,6 +1,6 @@ ### Relevant Articles: -- [Spring JPA @Embedded and @EmbeddedId](TBD) +- [Spring JPA @Embedded and @EmbeddedId](https://www.baeldung.com/spring-jpa-embedded-method-parameters) ### Eclipse Config After importing the project into Eclipse, you may see the following error: From 1409c871c6114f99fb86a60042ded756ef8bde92 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 16:50:35 +0800 Subject: [PATCH 067/150] Update README.md --- persistence-modules/spring-data-jpa-5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-data-jpa-5/README.md b/persistence-modules/spring-data-jpa-5/README.md index 656e2e5e6b..fa29c82bac 100644 --- a/persistence-modules/spring-data-jpa-5/README.md +++ b/persistence-modules/spring-data-jpa-5/README.md @@ -1,6 +1,7 @@ ### Relevant Articles: - [Spring JPA @Embedded and @EmbeddedId](https://www.baeldung.com/spring-jpa-embedded-method-parameters) +- [Generate Database Schema with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-generate-db-schema) ### Eclipse Config After importing the project into Eclipse, you may see the following error: From 6db54f0321535a7166cc2e2c6d305e46e68d55aa Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 16:53:32 +0800 Subject: [PATCH 068/150] Update README.md --- spring-5-security/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-5-security/README.md b/spring-5-security/README.md index 5a6d2d73de..764d726ff8 100644 --- a/spring-5-security/README.md +++ b/spring-5-security/README.md @@ -10,3 +10,4 @@ This module contains articles about Spring Security 5 - [Default Password Encoder in Spring Security 5](https://www.baeldung.com/spring-security-5-default-password-encoder) - [Guide to the AuthenticationManagerResolver in Spring Security](https://www.baeldung.com/spring-security-authenticationmanagerresolver) - [Disable Security for a Profile in Spring Boot](https://www.baeldung.com/spring-security-disable-profile) +- [Manual Logout With Spring Security](https://www.baeldung.com/spring-security-manual-logout) From 26a7295fc22fb76e2c9a257592601806f7eafc88 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 16:54:56 +0800 Subject: [PATCH 069/150] Update README.md --- maven-all/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/maven-all/README.md b/maven-all/README.md index b20d944b14..b448be2cd0 100644 --- a/maven-all/README.md +++ b/maven-all/README.md @@ -5,3 +5,4 @@ This module contains articles about Apache Maven. Please refer to its submodules ### Relevant Articles - [Apache Maven Tutorial](https://www.baeldung.com/maven) +- [Find Unused Maven Dependencies](https://www.baeldung.com/maven-unused-dependencies) From 6786c93bc0f97efc20b546e48c48256e55538683 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 16:56:57 +0800 Subject: [PATCH 070/150] Update README.md --- persistence-modules/redis/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/redis/README.md b/persistence-modules/redis/README.md index 668b8d33f8..71d009241a 100644 --- a/persistence-modules/redis/README.md +++ b/persistence-modules/redis/README.md @@ -3,3 +3,4 @@ - [A Guide to Redis with Redisson](http://www.baeldung.com/redis-redisson) - [Introduction to Lettuce – the Java Redis Client](https://www.baeldung.com/java-redis-lettuce) - [List All Available Redis Keys](https://www.baeldung.com/redis-list-available-keys) +- [Spring Data Redis’s Property-Based Configuration](https://www.baeldung.com/spring-data-redis-properties) From 376046bacf3d3b957cc0a7f20d1aa59c3812f891 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 16:58:13 +0800 Subject: [PATCH 071/150] Update README.md --- spring-cloud/spring-cloud-gateway/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-cloud/spring-cloud-gateway/README.md b/spring-cloud/spring-cloud-gateway/README.md index 9c8e0d443a..90e81fe9a2 100644 --- a/spring-cloud/spring-cloud-gateway/README.md +++ b/spring-cloud/spring-cloud-gateway/README.md @@ -6,3 +6,4 @@ This module contains articles about Spring Cloud Gateway - [Exploring the new Spring Cloud Gateway](http://www.baeldung.com/spring-cloud-gateway) - [Writing Custom Spring Cloud Gateway Filters](https://www.baeldung.com/spring-cloud-custom-gateway-filters) - [Spring Cloud Gateway Routing Predicate Factories](https://www.baeldung.com/spring-cloud-gateway-routing-predicate-factories) +- [Spring Cloud Gateway WebFilter Factories](https://www.baeldung.com/spring-cloud-gateway-webfilter-factories) From 2d9867bc3b752c6c2568f1103a49c6d2770452a2 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 16:59:31 +0800 Subject: [PATCH 072/150] Update README.md --- spring-core-4/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-core-4/README.md b/spring-core-4/README.md index 35d2711ad8..592f4cd011 100644 --- a/spring-core-4/README.md +++ b/spring-core-4/README.md @@ -5,4 +5,5 @@ This module contains articles about core Spring functionality ## Relevant Articles: - [Creating Spring Beans Through Factory Methods](https://www.baeldung.com/spring-beans-factory-methods) +- [How to dynamically Autowire a Bean in Spring](https://www.baeldung.com/spring-dynamic-autowire) - More articles: [[<-- prev]](/spring-core-3) From e6dd93f4d14a71fb6b1eeb19e2af65363a8ccae8 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 17:02:06 +0800 Subject: [PATCH 073/150] Create README.md --- spring-security-modules/spring-security-okta/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 spring-security-modules/spring-security-okta/README.md diff --git a/spring-security-modules/spring-security-okta/README.md b/spring-security-modules/spring-security-okta/README.md new file mode 100644 index 0000000000..6ea4817e19 --- /dev/null +++ b/spring-security-modules/spring-security-okta/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Spring Security With Okta](https://www.baeldung.com/spring-security-okta) From 32925d61c368877f40ff89ad1a3678489c3ac29a Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 17:06:47 +0800 Subject: [PATCH 074/150] Update README.md --- core-java-modules/core-java-regex/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-regex/README.md b/core-java-modules/core-java-regex/README.md index 6fdea9f2ca..8830af2c2d 100644 --- a/core-java-modules/core-java-regex/README.md +++ b/core-java-modules/core-java-regex/README.md @@ -10,3 +10,4 @@ - [Difference Between Java Matcher find() and matches()](https://www.baeldung.com/java-matcher-find-vs-matches) - [How to Use Regular Expressions to Replace Tokens in Strings](https://www.baeldung.com/java-regex-token-replacement) - [Regular Expressions \s and \s+ in Java](https://www.baeldung.com/java-regex-s-splus) +- [Validate Phone Numbers With Java Regex](https://www.baeldung.com/java-regex-validate-phone-numbers) From 3a1fa055d22ae33414587f3b11746d88b517f0e2 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 12 May 2020 17:10:13 +0800 Subject: [PATCH 075/150] Update README.md --- core-java-modules/core-java-14/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-14/README.md b/core-java-modules/core-java-14/README.md index 13bb468b30..dc80800054 100644 --- a/core-java-modules/core-java-14/README.md +++ b/core-java-modules/core-java-14/README.md @@ -8,3 +8,4 @@ This module contains articles about Java 14. - [Java Text Blocks](https://www.baeldung.com/java-text-blocks) - [Pattern Matching for instanceof in Java 14](https://www.baeldung.com/java-pattern-matching-instanceof) - [Helpful NullPointerExceptions in Java 14](https://www.baeldung.com/java-14-nullpointerexception) +- [Foreign Memory Access API in Java 14](https://www.baeldung.com/java-foreign-memory-access) From 5ae337e1e25d047f5dd117c8804c05784cffb1f5 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Tue, 12 May 2020 23:03:58 +0530 Subject: [PATCH 076/150] JAVA-1595: Restore code for Jetty ReactiveStreams HTTP Client article --- libraries-http-2/pom.xml | 37 ++++++++++ .../jetty/httpclient/BlockingSubscriber.java | 35 ++++++++++ .../jetty/httpclient/RequestHandler.java | 21 ++++++ .../jetty/httpclient/AbstractUnitTest.java | 54 +++++++++++++++ .../httpclient/ProjectReactorUnitTest.java | 30 +++++++++ .../httpclient/ReactiveStreamsUnitTest.java | 28 ++++++++ .../jetty/httpclient/RxJava2UnitTest.java | 67 +++++++++++++++++++ .../httpclient/SpringWebFluxUnitTest.java | 36 ++++++++++ 8 files changed, 308 insertions(+) create mode 100644 libraries-http-2/src/main/java/com/baeldung/jetty/httpclient/BlockingSubscriber.java create mode 100644 libraries-http-2/src/main/java/com/baeldung/jetty/httpclient/RequestHandler.java create mode 100644 libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/AbstractUnitTest.java create mode 100644 libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/ProjectReactorUnitTest.java create mode 100644 libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/ReactiveStreamsUnitTest.java create mode 100644 libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/RxJava2UnitTest.java create mode 100644 libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/SpringWebFluxUnitTest.java diff --git a/libraries-http-2/pom.xml b/libraries-http-2/pom.xml index c0a4f6455d..73fe6c66bd 100644 --- a/libraries-http-2/pom.xml +++ b/libraries-http-2/pom.xml @@ -35,6 +35,37 @@ ${mockwebserver.version} test + + + org.eclipse.jetty + jetty-reactive-httpclient + ${jetty.httpclient.version} + + + org.eclipse.jetty + jetty-server + ${jetty.server.version} + + + io.reactivex.rxjava2 + rxjava + ${rxjava2.version} + + + org.springframework + spring-webflux + ${spring.webflux.version} + + + io.projectreactor + reactor-core + ${reactor.version} + + + org.reactivestreams + reactive-streams + ${reactive.stream.version} + @@ -42,6 +73,12 @@ 2.8.5 3.14.2 2.9.8 + 1.0.3 + 9.4.19.v20190610 + 2.2.11 + 5.1.9.RELEASE + 1.0.3 + 3.2.12.RELEASE diff --git a/libraries-http-2/src/main/java/com/baeldung/jetty/httpclient/BlockingSubscriber.java b/libraries-http-2/src/main/java/com/baeldung/jetty/httpclient/BlockingSubscriber.java new file mode 100644 index 0000000000..6986172cd3 --- /dev/null +++ b/libraries-http-2/src/main/java/com/baeldung/jetty/httpclient/BlockingSubscriber.java @@ -0,0 +1,35 @@ +package com.baeldung.jetty.httpclient; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +import org.eclipse.jetty.reactive.client.ReactiveResponse; +import org.reactivestreams.Subscriber; +import org.reactivestreams.Subscription; + +public class BlockingSubscriber implements Subscriber { + BlockingQueue sink = new LinkedBlockingQueue<>(1); + + @Override + public void onSubscribe(Subscription subscription) { + subscription.request(1); + } + + @Override + public void onNext(ReactiveResponse response) { + sink.offer(response); + } + + @Override + public void onError(Throwable failure) { + } + + @Override + public void onComplete() { + } + + public ReactiveResponse block() throws InterruptedException { + return sink.poll(5, TimeUnit.SECONDS); + } +} \ No newline at end of file diff --git a/libraries-http-2/src/main/java/com/baeldung/jetty/httpclient/RequestHandler.java b/libraries-http-2/src/main/java/com/baeldung/jetty/httpclient/RequestHandler.java new file mode 100644 index 0000000000..c3dbff9b11 --- /dev/null +++ b/libraries-http-2/src/main/java/com/baeldung/jetty/httpclient/RequestHandler.java @@ -0,0 +1,21 @@ +package com.baeldung.jetty.httpclient; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.handler.AbstractHandler; +import org.eclipse.jetty.util.IO; + +public class RequestHandler extends AbstractHandler { + + @Override + public void handle(String target, Request jettyRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { + jettyRequest.setHandled(true); + response.setContentType(request.getContentType()); + IO.copy(request.getInputStream(), response.getOutputStream()); + } +} \ No newline at end of file diff --git a/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/AbstractUnitTest.java b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/AbstractUnitTest.java new file mode 100644 index 0000000000..4a3e67a7c5 --- /dev/null +++ b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/AbstractUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.jetty.httpclient; + +import org.eclipse.jetty.client.HttpClient; +import org.eclipse.jetty.server.Handler; +import org.eclipse.jetty.server.Server; +import org.junit.After; +import org.junit.Before; + +public abstract class AbstractUnitTest { + + protected HttpClient httpClient; + protected Server server; + protected static final String CONTENT = "Hello World!"; + protected final int port = 9080; + + @Before + public void init() { + startServer(new RequestHandler()); + startClient(); + } + + private void startClient() { + httpClient = new HttpClient(); + try { + httpClient.start(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void startServer(Handler handler) { + server = new Server(port); + server.setHandler(handler); + try { + server.start(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @After + public void dispose() throws Exception { + if (httpClient != null) { + httpClient.stop(); + } + if (server != null) { + server.stop(); + } + } + + protected String uri() { + return "http://localhost:" + port; + } +} \ No newline at end of file diff --git a/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/ProjectReactorUnitTest.java b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/ProjectReactorUnitTest.java new file mode 100644 index 0000000000..6d79773609 --- /dev/null +++ b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/ProjectReactorUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.jetty.httpclient; + +import org.eclipse.jetty.client.api.Request; +import org.eclipse.jetty.http.HttpStatus; +import org.eclipse.jetty.reactive.client.ReactiveRequest; +import org.eclipse.jetty.reactive.client.ReactiveResponse; +import org.junit.Assert; +import org.junit.Test; +import org.reactivestreams.Publisher; + +import reactor.core.publisher.Mono; + +public class ProjectReactorUnitTest extends AbstractUnitTest { + + @Test + public void givenReactiveClient_whenRequested_shouldReturn200() throws Exception { + + Request request = httpClient.newRequest(uri()); + ReactiveRequest reactiveRequest = ReactiveRequest.newBuilder(request) + .build(); + Publisher publisher = reactiveRequest.response(); + + ReactiveResponse response = Mono.from(publisher) + .block(); + + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), HttpStatus.OK_200); + + } +} diff --git a/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/ReactiveStreamsUnitTest.java b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/ReactiveStreamsUnitTest.java new file mode 100644 index 0000000000..3db4553c86 --- /dev/null +++ b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/ReactiveStreamsUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.jetty.httpclient; + +import org.eclipse.jetty.client.api.Request; +import org.eclipse.jetty.http.HttpStatus; +import org.eclipse.jetty.reactive.client.ReactiveRequest; +import org.eclipse.jetty.reactive.client.ReactiveResponse; +import org.junit.Assert; +import org.junit.Test; +import org.reactivestreams.Publisher; + +public class ReactiveStreamsUnitTest extends AbstractUnitTest { + + @Test + public void givenReactiveClient_whenRequested_shouldReturn200() throws Exception { + + Request request = httpClient.newRequest(uri()); + ReactiveRequest reactiveRequest = ReactiveRequest.newBuilder(request) + .build(); + Publisher publisher = reactiveRequest.response(); + + BlockingSubscriber subscriber = new BlockingSubscriber(); + publisher.subscribe(subscriber); + ReactiveResponse response = subscriber.block(); + Assert.assertNotNull(response); + Assert.assertEquals(response.getStatus(), HttpStatus.OK_200); + } + +} diff --git a/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/RxJava2UnitTest.java b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/RxJava2UnitTest.java new file mode 100644 index 0000000000..dabd768702 --- /dev/null +++ b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/RxJava2UnitTest.java @@ -0,0 +1,67 @@ +package com.baeldung.jetty.httpclient; + +import static java.nio.charset.StandardCharsets.UTF_8; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.jetty.client.api.Request; +import org.eclipse.jetty.http.HttpStatus; +import org.eclipse.jetty.reactive.client.ReactiveRequest; +import org.eclipse.jetty.reactive.client.ReactiveRequest.Event.Type; +import org.eclipse.jetty.reactive.client.ReactiveResponse; +import org.junit.Assert; +import org.junit.Test; +import org.reactivestreams.Publisher; +import org.springframework.http.MediaType; + +import io.reactivex.Flowable; +import io.reactivex.Single; + +public class RxJava2UnitTest extends AbstractUnitTest { + + @Test + public void givenReactiveClient_whenRequestedWithBody_ShouldReturnBody() throws Exception { + + Request request = httpClient.newRequest(uri()); + ReactiveRequest reactiveRequest = ReactiveRequest.newBuilder(request) + .content(ReactiveRequest.Content.fromString(CONTENT, MediaType.TEXT_PLAIN_VALUE, UTF_8)) + .build(); + Publisher publisher = reactiveRequest.response(ReactiveResponse.Content.asString()); + + String responseContent = Single.fromPublisher(publisher) + .blockingGet(); + + Assert.assertEquals(CONTENT, responseContent); + } + + @Test + public void givenReactiveClient_whenRequested_ShouldPrintEvents() throws Exception { + ReactiveRequest request = ReactiveRequest.newBuilder(httpClient, uri()) + .content(ReactiveRequest.Content.fromString(CONTENT, MediaType.TEXT_PLAIN_VALUE, UTF_8)) + .build(); + Publisher requestEvents = request.requestEvents(); + Publisher responseEvents = request.responseEvents(); + + List requestEventTypes = new ArrayList<>(); + List responseEventTypes = new ArrayList<>(); + + Flowable.fromPublisher(requestEvents) + .map(ReactiveRequest.Event::getType) + .subscribe(requestEventTypes::add); + + Flowable.fromPublisher(responseEvents) + .map(ReactiveResponse.Event::getType) + .subscribe(responseEventTypes::add); + + Single response = Single.fromPublisher(request.response()); + int actualStatus = response.blockingGet() + .getStatus(); + + Assert.assertEquals(6, requestEventTypes.size()); + Assert.assertEquals(5, responseEventTypes.size()); + + Assert.assertEquals(actualStatus, HttpStatus.OK_200); + } + +} \ No newline at end of file diff --git a/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/SpringWebFluxUnitTest.java b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/SpringWebFluxUnitTest.java new file mode 100644 index 0000000000..4a1a9bb2b5 --- /dev/null +++ b/libraries-http-2/src/test/java/com/baeldung/jetty/httpclient/SpringWebFluxUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.jetty.httpclient; + +import org.eclipse.jetty.client.HttpClient; +import org.junit.Assert; +import org.junit.Test; +import org.springframework.http.MediaType; +import org.springframework.http.client.reactive.ClientHttpConnector; +import org.springframework.http.client.reactive.JettyClientHttpConnector; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.WebClient; + +import reactor.core.publisher.Mono; + +public class SpringWebFluxUnitTest extends AbstractUnitTest { + + @Test + public void givenReactiveClient_whenRequested_shouldReturnResponse() throws Exception { + + HttpClient httpClient = new HttpClient(); + httpClient.start(); + + ClientHttpConnector clientConnector = new JettyClientHttpConnector(httpClient); + WebClient client = WebClient.builder() + .clientConnector(clientConnector) + .build(); + String responseContent = client.post() + .uri(uri()) + .contentType(MediaType.TEXT_PLAIN) + .body(BodyInserters.fromPublisher(Mono.just(CONTENT), String.class)) + .retrieve() + .bodyToMono(String.class) + .block(); + Assert.assertNotNull(responseContent); + Assert.assertEquals(CONTENT, responseContent); + } +} \ No newline at end of file From 7a6eb5d217c1d3fc418d68e2a7645f78f6a6ad5a Mon Sep 17 00:00:00 2001 From: Kyle Doyle Date: Wed, 13 May 2020 16:33:31 -0400 Subject: [PATCH 077/150] Bael-3893 - Fixed tests causing build to fail --- .../java/com/baeldung/awsappsync/AppSyncClientHelper.java | 4 ++-- .../com/baeldung/awsappsync/AwsAppSyncApplicationTests.java | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/aws-app-sync/src/main/java/com/baeldung/awsappsync/AppSyncClientHelper.java b/aws-app-sync/src/main/java/com/baeldung/awsappsync/AppSyncClientHelper.java index b310e60748..f66ac1841b 100644 --- a/aws-app-sync/src/main/java/com/baeldung/awsappsync/AppSyncClientHelper.java +++ b/aws-app-sync/src/main/java/com/baeldung/awsappsync/AppSyncClientHelper.java @@ -10,8 +10,8 @@ import java.util.Map; public class AppSyncClientHelper { - static String apiUrl = "https://m4i3b6icrrb7livfbypfspiifi.appsync-api.us-east-2.amazonaws.com"; - static String apiKey = "da2-bm4rpatkkrc5jfyhvvq7itjeke"; + static String apiUrl = ""; + static String apiKey = ""; static String API_KEY_HEADER = "x-api-key"; public static WebClient.ResponseSpec getResponseBodySpec(Map requestBody) { diff --git a/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java b/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java index 22d99959b3..2338cc29a1 100644 --- a/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java +++ b/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java @@ -1,5 +1,6 @@ package com.baeldung.awsappsync; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.web.reactive.function.client.WebClient; @@ -10,6 +11,7 @@ import java.util.Map; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest +@Disabled class AwsAppSyncApplicationTests { @Test From f58c322ae2c2500f14033f88eda10e7c20aaa3d9 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Thu, 14 May 2020 12:13:53 +0530 Subject: [PATCH 078/150] JAVA-943: Migrate spring-mobile to parent-boot-2 --- spring-mobile/pom.xml | 19 ++++++++-- .../src/main/java/com/baeldung/AppConfig.java | 36 +++++++++++++++++++ .../baeldung/controller/IndexController.java | 5 ++- .../src/main/resources/application.properties | 4 ++- 4 files changed, 59 insertions(+), 5 deletions(-) create mode 100644 spring-mobile/src/main/java/com/baeldung/AppConfig.java diff --git a/spring-mobile/pom.xml b/spring-mobile/pom.xml index ff90ac6ecb..465458ba49 100644 --- a/spring-mobile/pom.xml +++ b/spring-mobile/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -23,11 +23,24 @@ org.springframework.mobile spring-mobile-device + ${spring-mobile-device.version} org.springframework.boot spring-boot-starter-freemarker - + + + spring-milestones + Spring Milestones + https://repo.spring.io/libs-milestone + + false + + + + + 2.0.0.M3 + diff --git a/spring-mobile/src/main/java/com/baeldung/AppConfig.java b/spring-mobile/src/main/java/com/baeldung/AppConfig.java new file mode 100644 index 0000000000..efa073ae11 --- /dev/null +++ b/spring-mobile/src/main/java/com/baeldung/AppConfig.java @@ -0,0 +1,36 @@ +package com.baeldung; + +import java.util.List; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.mobile.device.DeviceHandlerMethodArgumentResolver; +import org.springframework.mobile.device.DeviceResolverHandlerInterceptor; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class AppConfig implements WebMvcConfigurer { + + @Bean + public DeviceResolverHandlerInterceptor deviceResolverHandlerInterceptor() { + return new DeviceResolverHandlerInterceptor(); + } + + @Bean + public DeviceHandlerMethodArgumentResolver deviceHandlerMethodArgumentResolver() { + return new DeviceHandlerMethodArgumentResolver(); + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(deviceResolverHandlerInterceptor()); + } + + @Override + public void addArgumentResolvers(List argumentResolvers) { + argumentResolvers.add(deviceHandlerMethodArgumentResolver()); + } + +} diff --git a/spring-mobile/src/main/java/com/baeldung/controller/IndexController.java b/spring-mobile/src/main/java/com/baeldung/controller/IndexController.java index 196fb680e7..49880f355a 100644 --- a/spring-mobile/src/main/java/com/baeldung/controller/IndexController.java +++ b/spring-mobile/src/main/java/com/baeldung/controller/IndexController.java @@ -16,13 +16,16 @@ public class IndexController { String deviceType = "browser"; String platform = "browser"; + String viewName = "index"; if (device.isNormal()) { deviceType = "browser"; } else if (device.isMobile()) { deviceType = "mobile"; + viewName = "mobile/index"; } else if (device.isTablet()) { deviceType = "tablet"; + viewName = "tablet/index"; } platform = device.getDevicePlatform().name(); @@ -33,7 +36,7 @@ public class IndexController { LOGGER.info("Client Device Type: " + deviceType + ", Platform: " + platform); - return "index"; + return viewName; } } diff --git a/spring-mobile/src/main/resources/application.properties b/spring-mobile/src/main/resources/application.properties index c0bc91f9ac..7d964f48fb 100644 --- a/spring-mobile/src/main/resources/application.properties +++ b/spring-mobile/src/main/resources/application.properties @@ -1 +1,3 @@ -spring.mobile.devicedelegatingviewresolver.enabled: true \ No newline at end of file +spring.mobile.devicedelegatingviewresolver.enabled: true +spring.freemarker.template-loader-path: classpath:/templates +spring.freemarker.suffix: .ftl \ No newline at end of file From 3c9b335ed5d48c0ae19557732ce46470350c58bf Mon Sep 17 00:00:00 2001 From: Roque Santos Date: Thu, 14 May 2020 13:56:35 -0300 Subject: [PATCH 079/150] BAEL-3942 : Correct failing build (#9289) Changed IntegrationTest to LiveTest --- .../jsonproxy/JsoupProxyLiveTest.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 jsoup/src/test/java/com/baeldung/jsonproxy/JsoupProxyLiveTest.java diff --git a/jsoup/src/test/java/com/baeldung/jsonproxy/JsoupProxyLiveTest.java b/jsoup/src/test/java/com/baeldung/jsonproxy/JsoupProxyLiveTest.java new file mode 100644 index 0000000000..931464c4db --- /dev/null +++ b/jsoup/src/test/java/com/baeldung/jsonproxy/JsoupProxyLiveTest.java @@ -0,0 +1,27 @@ +package com.baeldung.jsonproxy; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Proxy; + +import org.jsoup.Jsoup; +import org.junit.Test; + +public class JsoupProxyLiveTest { + + @Test + public void whenUsingHostAndPort_thenConnect() throws IOException { + Jsoup.connect("https://spring.io/blog") + .proxy("200.216.227.141", 53281) + .get(); + } + + @Test + public void whenUsingProxyClass_thenConnect() throws IOException { + Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("200.216.227.141", 53281)); + + Jsoup.connect("https://spring.io/blog") + .proxy(proxy) + .get(); + } +} From b2ce70b8fb9509ef7e24678e0939b167e067525b Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 15 May 2020 23:06:26 +0800 Subject: [PATCH 080/150] Create README.md --- libraries-concurrency/coroutines-with-quasar/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 libraries-concurrency/coroutines-with-quasar/README.md diff --git a/libraries-concurrency/coroutines-with-quasar/README.md b/libraries-concurrency/coroutines-with-quasar/README.md new file mode 100644 index 0000000000..d1ffe81fa8 --- /dev/null +++ b/libraries-concurrency/coroutines-with-quasar/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Intro to Coroutines with Quasar](https://www.baeldung.com/java-quasar-coroutines) From f139085a1de085cee528b95ee95d2747f5e2f891 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 15 May 2020 23:07:50 +0800 Subject: [PATCH 081/150] Create README.md --- apache-cxf/cxf-aegis/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 apache-cxf/cxf-aegis/README.md diff --git a/apache-cxf/cxf-aegis/README.md b/apache-cxf/cxf-aegis/README.md new file mode 100644 index 0000000000..1cdb6efbb5 --- /dev/null +++ b/apache-cxf/cxf-aegis/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to Apache CXF Aegis Data Binding](https://www.baeldung.com/aegis-data-binding-in-apache-cxf) From 536feb6fae354937276faa89a3d5fbfed0e39ade Mon Sep 17 00:00:00 2001 From: Sam Millington Date: Fri, 15 May 2020 16:32:16 +0100 Subject: [PATCH 082/150] Deleted JsoupProxyIntegrationTest.java (#9294) --- .../jsonproxy/JsoupProxyIntegrationTest.java | 27 ------------------- 1 file changed, 27 deletions(-) delete mode 100644 jsoup/src/test/java/com/baeldung/jsonproxy/JsoupProxyIntegrationTest.java diff --git a/jsoup/src/test/java/com/baeldung/jsonproxy/JsoupProxyIntegrationTest.java b/jsoup/src/test/java/com/baeldung/jsonproxy/JsoupProxyIntegrationTest.java deleted file mode 100644 index 8e854ead6a..0000000000 --- a/jsoup/src/test/java/com/baeldung/jsonproxy/JsoupProxyIntegrationTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.jsonproxy; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Proxy; - -import org.jsoup.Jsoup; -import org.junit.Test; - -public class JsoupProxyIntegrationTest { - - @Test - public void whenUsingHostAndPort_thenConnect() throws IOException { - Jsoup.connect("https://spring.io/blog") - .proxy("200.216.227.141", 53281) - .get(); - } - - @Test - public void whenUsingProxyClass_thenConnect() throws IOException { - Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("200.216.227.141", 53281)); - - Jsoup.connect("https://spring.io/blog") - .proxy(proxy) - .get(); - } -} From b20271ef347e3458b13a9845c6a14a809ebd53e3 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sat, 16 May 2020 02:57:46 +0800 Subject: [PATCH 083/150] Update README.md --- libraries-concurrency/README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/libraries-concurrency/README.md b/libraries-concurrency/README.md index d1ffe81fa8..8b13789179 100644 --- a/libraries-concurrency/README.md +++ b/libraries-concurrency/README.md @@ -1,3 +1 @@ -### Relevant Articles: -- [Intro to Coroutines with Quasar](https://www.baeldung.com/java-quasar-coroutines) From b660f1cefa61caa3967941fba7fb119466730eec Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sat, 16 May 2020 02:57:55 +0800 Subject: [PATCH 084/150] Delete README.md --- libraries-concurrency/README.md | 1 - 1 file changed, 1 deletion(-) delete mode 100644 libraries-concurrency/README.md diff --git a/libraries-concurrency/README.md b/libraries-concurrency/README.md deleted file mode 100644 index 8b13789179..0000000000 --- a/libraries-concurrency/README.md +++ /dev/null @@ -1 +0,0 @@ - From afeeba6ef5749d571f860d934acb7f6a8d593d77 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Sat, 16 May 2020 02:58:46 +0800 Subject: [PATCH 085/150] Update README.md --- apache-cxf/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-cxf/README.md b/apache-cxf/README.md index f825b85bb3..bedd19a91a 100644 --- a/apache-cxf/README.md +++ b/apache-cxf/README.md @@ -3,7 +3,7 @@ This module contains articles about Apache CXF ## Relevant Articles: -- [Introduction to Apache CXF Aegis Data Binding](https://www.baeldung.com/aegis-data-binding-in-apache-cxf) + - [Apache CXF Support for RESTful Web Services](https://www.baeldung.com/apache-cxf-rest-api) - [A Guide to Apache CXF with Spring](https://www.baeldung.com/apache-cxf-with-spring) - [Introduction to Apache CXF](https://www.baeldung.com/introduction-to-apache-cxf) From f7c396df274ffd374bf12ff2aa5e6b8aca81f58d Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Fri, 15 May 2020 22:14:25 +0200 Subject: [PATCH 086/150] Update build.gradle --- gradle/gradle-employee-app/build.gradle | 1 - 1 file changed, 1 deletion(-) diff --git a/gradle/gradle-employee-app/build.gradle b/gradle/gradle-employee-app/build.gradle index 19b80c0c4a..b343d2b210 100644 --- a/gradle/gradle-employee-app/build.gradle +++ b/gradle/gradle-employee-app/build.gradle @@ -1,6 +1,5 @@ plugins { - id 'java-library' id 'application' } From 3977ef96c681bcf1731763ac3fe07898c0efabcb Mon Sep 17 00:00:00 2001 From: CHANDRAKANT Kumar Date: Sat, 16 May 2020 01:46:02 +0530 Subject: [PATCH 087/150] Incorporated review comments from editor. --- {java-es-cqrs => patterns/cqrs-es}/pom.xml | 6 +++--- .../baeldung/patterns/cqrs/aggregates/UserAggregate.java | 0 .../baeldung/patterns/cqrs/commands/CreateUserCommand.java | 0 .../baeldung/patterns/cqrs/commands/UpdateUserCommand.java | 0 .../baeldung/patterns/cqrs/projections/UserProjection.java | 0 .../baeldung/patterns/cqrs/projectors/UserProjector.java | 0 .../patterns/cqrs/queries/AddressByRegionQuery.java | 0 .../baeldung/patterns/cqrs/queries/ContactByTypeQuery.java | 0 .../patterns/cqrs/repository/UserReadRepository.java | 0 .../patterns/cqrs/repository/UserWriteRepository.java | 0 .../baeldung/patterns/crud/repository/UserRepository.java | 0 .../com/baeldung/patterns/crud/service/UserService.java | 0 .../src/main/java/com/baeldung/patterns/domain/Address.java | 0 .../src/main/java/com/baeldung/patterns/domain/Contact.java | 0 .../src/main/java/com/baeldung/patterns/domain/User.java | 0 .../main/java/com/baeldung/patterns/domain/UserAddress.java | 0 .../main/java/com/baeldung/patterns/domain/UserContact.java | 0 .../main/java/com/baeldung/patterns/es/events/Event.java | 0 .../baeldung/patterns/es/events/UserAddressAddedEvent.java | 0 .../patterns/es/events/UserAddressRemovedEvent.java | 0 .../baeldung/patterns/es/events/UserContactAddedEvent.java | 0 .../patterns/es/events/UserContactRemovedEvent.java | 0 .../com/baeldung/patterns/es/events/UserCreatedEvent.java | 0 .../com/baeldung/patterns/es/repository/EventStore.java | 0 .../java/com/baeldung/patterns/es/service/UserService.java | 0 .../java/com/baeldung/patterns/es/service/UserUtility.java | 0 .../baeldung/patterns/escqrs/aggregates/UserAggregate.java | 0 .../baeldung/patterns/escqrs/projectors/UserProjector.java | 0 .../com/baeldung/patterns/cqrs/ApplicationUnitTest.java | 2 +- .../com/baeldung/patterns/crud/ApplicationUnitTest.java | 2 +- .../java/com/baeldung/patterns/es/ApplicationUnitTest.java | 2 +- .../com/baeldung/patterns/escqrs/ApplicationUnitTest.java | 2 +- patterns/pom.xml | 1 + pom.xml | 2 -- 34 files changed, 8 insertions(+), 9 deletions(-) rename {java-es-cqrs => patterns/cqrs-es}/pom.xml (88%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/cqrs/aggregates/UserAggregate.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/cqrs/commands/CreateUserCommand.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/cqrs/commands/UpdateUserCommand.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/cqrs/projections/UserProjection.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/cqrs/projectors/UserProjector.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/cqrs/queries/AddressByRegionQuery.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/cqrs/queries/ContactByTypeQuery.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/cqrs/repository/UserReadRepository.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/cqrs/repository/UserWriteRepository.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/crud/repository/UserRepository.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/crud/service/UserService.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/domain/Address.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/domain/Contact.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/domain/User.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/domain/UserAddress.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/domain/UserContact.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/es/events/Event.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/es/events/UserAddressAddedEvent.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/es/events/UserAddressRemovedEvent.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/es/events/UserContactAddedEvent.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/es/events/UserContactRemovedEvent.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/es/events/UserCreatedEvent.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/es/repository/EventStore.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/es/service/UserService.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/es/service/UserUtility.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/escqrs/aggregates/UserAggregate.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/main/java/com/baeldung/patterns/escqrs/projectors/UserProjector.java (100%) rename {java-es-cqrs => patterns/cqrs-es}/src/test/java/com/baeldung/patterns/cqrs/ApplicationUnitTest.java (96%) rename {java-es-cqrs => patterns/cqrs-es}/src/test/java/com/baeldung/patterns/crud/ApplicationUnitTest.java (95%) rename {java-es-cqrs => patterns/cqrs-es}/src/test/java/com/baeldung/patterns/es/ApplicationUnitTest.java (95%) rename {java-es-cqrs => patterns/cqrs-es}/src/test/java/com/baeldung/patterns/escqrs/ApplicationUnitTest.java (97%) diff --git a/java-es-cqrs/pom.xml b/patterns/cqrs-es/pom.xml similarity index 88% rename from java-es-cqrs/pom.xml rename to patterns/cqrs-es/pom.xml index 8760a38262..3c54038837 100644 --- a/java-es-cqrs/pom.xml +++ b/patterns/cqrs-es/pom.xml @@ -2,12 +2,12 @@ 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 - java-es-cqrs + cqrs-es 1.0-SNAPSHOT - java-es-cqrs + cqrs-es com.baeldung - parent-modules + patterns 1.0.0-SNAPSHOT diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/aggregates/UserAggregate.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/aggregates/UserAggregate.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/aggregates/UserAggregate.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/aggregates/UserAggregate.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/commands/CreateUserCommand.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/commands/CreateUserCommand.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/commands/CreateUserCommand.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/commands/CreateUserCommand.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/commands/UpdateUserCommand.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/commands/UpdateUserCommand.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/commands/UpdateUserCommand.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/commands/UpdateUserCommand.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/projections/UserProjection.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/projections/UserProjection.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/projections/UserProjection.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/projections/UserProjection.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/projectors/UserProjector.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/projectors/UserProjector.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/projectors/UserProjector.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/projectors/UserProjector.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/queries/AddressByRegionQuery.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/queries/AddressByRegionQuery.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/queries/AddressByRegionQuery.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/queries/AddressByRegionQuery.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/queries/ContactByTypeQuery.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/queries/ContactByTypeQuery.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/queries/ContactByTypeQuery.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/queries/ContactByTypeQuery.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/repository/UserReadRepository.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/repository/UserReadRepository.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/repository/UserReadRepository.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/repository/UserReadRepository.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/repository/UserWriteRepository.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/repository/UserWriteRepository.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/cqrs/repository/UserWriteRepository.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/repository/UserWriteRepository.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/crud/repository/UserRepository.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/crud/repository/UserRepository.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/crud/repository/UserRepository.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/crud/repository/UserRepository.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/crud/service/UserService.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/crud/service/UserService.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/crud/service/UserService.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/crud/service/UserService.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/Address.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/domain/Address.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/domain/Address.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/domain/Address.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/Contact.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/domain/Contact.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/domain/Contact.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/domain/Contact.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/User.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/domain/User.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/domain/User.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/domain/User.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserAddress.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/domain/UserAddress.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserAddress.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/domain/UserAddress.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserContact.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/domain/UserContact.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/domain/UserContact.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/domain/UserContact.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/Event.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/es/events/Event.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/Event.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/es/events/Event.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserAddressAddedEvent.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/es/events/UserAddressAddedEvent.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserAddressAddedEvent.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/es/events/UserAddressAddedEvent.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserAddressRemovedEvent.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/es/events/UserAddressRemovedEvent.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserAddressRemovedEvent.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/es/events/UserAddressRemovedEvent.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserContactAddedEvent.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/es/events/UserContactAddedEvent.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserContactAddedEvent.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/es/events/UserContactAddedEvent.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserContactRemovedEvent.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/es/events/UserContactRemovedEvent.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserContactRemovedEvent.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/es/events/UserContactRemovedEvent.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserCreatedEvent.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/es/events/UserCreatedEvent.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/es/events/UserCreatedEvent.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/es/events/UserCreatedEvent.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/repository/EventStore.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/es/repository/EventStore.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/es/repository/EventStore.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/es/repository/EventStore.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserService.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/es/service/UserService.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserService.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/es/service/UserService.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserUtility.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/es/service/UserUtility.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/es/service/UserUtility.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/es/service/UserUtility.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/aggregates/UserAggregate.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/escqrs/aggregates/UserAggregate.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/aggregates/UserAggregate.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/escqrs/aggregates/UserAggregate.java diff --git a/java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/projectors/UserProjector.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/escqrs/projectors/UserProjector.java similarity index 100% rename from java-es-cqrs/src/main/java/com/baeldung/patterns/escqrs/projectors/UserProjector.java rename to patterns/cqrs-es/src/main/java/com/baeldung/patterns/escqrs/projectors/UserProjector.java diff --git a/java-es-cqrs/src/test/java/com/baeldung/patterns/cqrs/ApplicationUnitTest.java b/patterns/cqrs-es/src/test/java/com/baeldung/patterns/cqrs/ApplicationUnitTest.java similarity index 96% rename from java-es-cqrs/src/test/java/com/baeldung/patterns/cqrs/ApplicationUnitTest.java rename to patterns/cqrs-es/src/test/java/com/baeldung/patterns/cqrs/ApplicationUnitTest.java index 4a324e72f6..7f68a64274 100644 --- a/java-es-cqrs/src/test/java/com/baeldung/patterns/cqrs/ApplicationUnitTest.java +++ b/patterns/cqrs-es/src/test/java/com/baeldung/patterns/cqrs/ApplicationUnitTest.java @@ -40,7 +40,7 @@ public class ApplicationUnitTest { } @Test - public void testApplication() throws Exception { + public void givenCQRSApplication_whenCommandRun_thenQueryShouldReturnResult() throws Exception { String userId = UUID.randomUUID() .toString(); User user = null; diff --git a/java-es-cqrs/src/test/java/com/baeldung/patterns/crud/ApplicationUnitTest.java b/patterns/cqrs-es/src/test/java/com/baeldung/patterns/crud/ApplicationUnitTest.java similarity index 95% rename from java-es-cqrs/src/test/java/com/baeldung/patterns/crud/ApplicationUnitTest.java rename to patterns/cqrs-es/src/test/java/com/baeldung/patterns/crud/ApplicationUnitTest.java index 28c113bf46..3fabfe405d 100644 --- a/java-es-cqrs/src/test/java/com/baeldung/patterns/crud/ApplicationUnitTest.java +++ b/patterns/cqrs-es/src/test/java/com/baeldung/patterns/crud/ApplicationUnitTest.java @@ -24,7 +24,7 @@ public class ApplicationUnitTest { } @Test - public void testApplication() throws Exception { + public void givenCRUDApplication_whenDataCreated_thenDataCanBeFetched() throws Exception { UserService service = new UserService(repository); String userId = UUID.randomUUID() .toString(); diff --git a/java-es-cqrs/src/test/java/com/baeldung/patterns/es/ApplicationUnitTest.java b/patterns/cqrs-es/src/test/java/com/baeldung/patterns/es/ApplicationUnitTest.java similarity index 95% rename from java-es-cqrs/src/test/java/com/baeldung/patterns/es/ApplicationUnitTest.java rename to patterns/cqrs-es/src/test/java/com/baeldung/patterns/es/ApplicationUnitTest.java index 52bdde449f..61e7b4c05a 100644 --- a/java-es-cqrs/src/test/java/com/baeldung/patterns/es/ApplicationUnitTest.java +++ b/patterns/cqrs-es/src/test/java/com/baeldung/patterns/es/ApplicationUnitTest.java @@ -26,7 +26,7 @@ public class ApplicationUnitTest { } @Test - public void testApplication() throws Exception { + public void givenCRUDApplication_whenDataCreated_thenDataCanBeFetched() throws Exception { String userId = UUID.randomUUID() .toString(); diff --git a/java-es-cqrs/src/test/java/com/baeldung/patterns/escqrs/ApplicationUnitTest.java b/patterns/cqrs-es/src/test/java/com/baeldung/patterns/escqrs/ApplicationUnitTest.java similarity index 97% rename from java-es-cqrs/src/test/java/com/baeldung/patterns/escqrs/ApplicationUnitTest.java rename to patterns/cqrs-es/src/test/java/com/baeldung/patterns/escqrs/ApplicationUnitTest.java index 22cb5235d1..e0460b2f12 100644 --- a/java-es-cqrs/src/test/java/com/baeldung/patterns/escqrs/ApplicationUnitTest.java +++ b/patterns/cqrs-es/src/test/java/com/baeldung/patterns/escqrs/ApplicationUnitTest.java @@ -41,7 +41,7 @@ public class ApplicationUnitTest { } @Test - public void testApplication() throws Exception { + public void givenCQRSApplication_whenCommandRun_thenQueryShouldReturnResult() throws Exception { String userId = UUID.randomUUID() .toString(); List events = null; diff --git a/patterns/pom.xml b/patterns/pom.xml index 4c17055231..fa46a79f5a 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -21,6 +21,7 @@ design-patterns-functional design-patterns-structural dip + cqrs-es front-controller intercepting-filter solid diff --git a/pom.xml b/pom.xml index 9a4b40b950..2f4579c999 100644 --- a/pom.xml +++ b/pom.xml @@ -568,7 +568,6 @@ rxjava-operators atomikos - java-es-cqrs @@ -1084,7 +1083,6 @@ rxjava-operators atomikos - java-es-cqrs From bccc9c836e87bf20a6662c9c9d206949bed7bd04 Mon Sep 17 00:00:00 2001 From: Dhrubajyoti Bhattacharjee Date: Fri, 15 May 2020 22:17:08 +0200 Subject: [PATCH 088/150] BAEL-3858 Java Exchanger introduction (#9000) --- .../ExchangerPipeLineManualTest.java | 83 +++++++++++++++++++ .../baeldung/exchanger/ExchangerUnitTest.java | 63 ++++++++++++++ 2 files changed, 146 insertions(+) create mode 100644 core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerPipeLineManualTest.java create mode 100644 core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerUnitTest.java diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerPipeLineManualTest.java b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerPipeLineManualTest.java new file mode 100644 index 0000000000..093580654b --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerPipeLineManualTest.java @@ -0,0 +1,83 @@ +package com.baeldung.exchanger; + +import java.util.Queue; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.Exchanger; +import java.util.concurrent.ExecutionException; +import org.junit.Test; + +import static java.util.concurrent.CompletableFuture.runAsync; + + + +public class ExchangerPipeLineManualTest { + + private static final int BUFFER_SIZE = 100; + + @Test + public void givenData_whenPassedThrough_thenCorrect() throws InterruptedException, ExecutionException { + + Exchanger> readerExchanger = new Exchanger<>(); + Exchanger> writerExchanger = new Exchanger<>(); + int counter = 0; + + Runnable reader = () -> { + Queue readerBuffer = new ConcurrentLinkedQueue<>(); + while (true) { + readerBuffer.add(UUID.randomUUID().toString()); + if (readerBuffer.size() >= BUFFER_SIZE) { + try { + readerBuffer = readerExchanger.exchange(readerBuffer); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + } + } + }; + + Runnable processor = () -> { + Queue processorBuffer = new ConcurrentLinkedQueue<>(); + Queue writterBuffer = new ConcurrentLinkedQueue<>(); + try { + processorBuffer = readerExchanger.exchange(processorBuffer); + while (true) { + writterBuffer.add(processorBuffer.poll()); + if (processorBuffer.isEmpty()) { + try { + processorBuffer = readerExchanger.exchange(processorBuffer); + writterBuffer = writerExchanger.exchange(writterBuffer); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + } + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + }; + + Runnable writer = () -> { + Queue writterBuffer = new ConcurrentLinkedQueue<>(); + try { + writterBuffer = writerExchanger.exchange(writterBuffer); + while (true) { + System.out.println(writterBuffer.poll()); + if (writterBuffer.isEmpty()) { + writterBuffer = writerExchanger.exchange(writterBuffer); + } + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + }; + + CompletableFuture.allOf(runAsync(reader), runAsync(processor), runAsync(writer)).get(); + } + +} diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerUnitTest.java b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerUnitTest.java new file mode 100644 index 0000000000..ec567a3563 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.exchanger; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Exchanger; + +import java.util.concurrent.ExecutionException; +import org.junit.Test; + +import static java.util.concurrent.CompletableFuture.runAsync; + +public class ExchangerUnitTest { + + + @Test + public void givenThreads_whenMessageExchanged_thenCorrect() { + Exchanger exchanger = new Exchanger<>(); + + Runnable taskA = () -> { + try { + String message = exchanger.exchange("from A"); + assertEquals("from B", message); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + }; + + Runnable taskB = () -> { + try { + String message = exchanger.exchange("from B"); + assertEquals("from A", message); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + }; + + CompletableFuture.allOf(runAsync(taskA), runAsync(taskB)).join(); + } + + @Test + public void givenThread_WhenExchangedMessage_thenCorrect() throws InterruptedException, ExecutionException { + Exchanger exchanger = new Exchanger<>(); + + Runnable runner = () -> { + try { + String message = exchanger.exchange("from runner"); + assertEquals("to runner", message); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + }; + + CompletableFuture result = CompletableFuture.runAsync(runner); + String msg = exchanger.exchange("to runner"); + assertEquals("from runner", msg); + result.join(); + } + +} From b707c20297ac4857f314b50efb7d3758aac5e0f7 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Fri, 15 May 2020 22:26:41 +0200 Subject: [PATCH 089/150] BAEL-4042: Add new test case using BufferedReader.lines method (#9288) --- .../JavaInputStreamToXUnitTest.java | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java index eb8c39f2d9..c8c711e328 100644 --- a/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java +++ b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java @@ -11,13 +11,26 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.*; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.Scanner; import java.util.UUID; +import java.util.stream.Collectors; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.hamcrest.Matchers.equalTo; @@ -46,6 +59,18 @@ public class JavaInputStreamToXUnitTest { assertEquals(textBuilder.toString(), originalString); } + @Test + public void givenUsingJava8_whenConvertingAnInputStreamToAString_thenCorrect() { + final String originalString = randomAlphabetic(DEFAULT_SIZE); + final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes()); + + final String text = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name()))) + .lines() + .collect(Collectors.joining("\n")); + + assertThat(text, equalTo(originalString)); + } + @Test public final void givenUsingJava7_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException { final String originalString = randomAlphabetic(DEFAULT_SIZE); From 708e85ce38e7bfaaea423e5ea3995fb7abf4aacb Mon Sep 17 00:00:00 2001 From: Sampada <46674082+sampada07@users.noreply.github.com> Date: Sat, 16 May 2020 02:07:36 +0530 Subject: [PATCH 090/150] BAEL-3493: Spring REST Docs vs OpenAPI (#9295) --- .../spring-boot-springdoc/pom.xml | 50 +++++- .../baeldung/restdocopenapi/Application.java | 28 ++++ .../java/com/baeldung/restdocopenapi/Foo.java | 93 +++++++++++ .../restdocopenapi/FooController.java | 83 ++++++++++ .../restdocopenapi/FooRepository.java | 9 ++ .../springdoc/FooBarController.java | 121 ++++++++++++++ .../src/main/resources/application.properties | 5 +- .../src/main/resources/asciidocs/fooapi.adoc | 153 ++++++++++++++++++ .../src/main/resources/data.sql | 4 + .../src/main/resources/schema.sql | 8 + .../restdoc/SpringRestDocsUnitTest.java | 120 ++++++++++++++ 11 files changed, 672 insertions(+), 2 deletions(-) create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Application.java create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Foo.java create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooController.java create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooRepository.java create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/springdoc/FooBarController.java create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/resources/asciidocs/fooapi.adoc create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/resources/data.sql create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/resources/schema.sql create mode 100644 spring-boot-modules/spring-boot-springdoc/src/test/java/com/baeldung/restdocopenapi/restdoc/SpringRestDocsUnitTest.java diff --git a/spring-boot-modules/spring-boot-springdoc/pom.xml b/spring-boot-modules/spring-boot-springdoc/pom.xml index 375cf06c2c..1c1f27b5a5 100644 --- a/spring-boot-modules/spring-boot-springdoc/pom.xml +++ b/spring-boot-modules/spring-boot-springdoc/pom.xml @@ -37,7 +37,7 @@ test - + org.hibernate hibernate-core ${hibernate.version} @@ -53,7 +53,19 @@ org.springdoc springdoc-openapi-data-rest ${springdoc.version} + + + + + org.springframework.restdocs + spring-restdocs-mockmvc + test + + org.springframework.restdocs + spring-restdocs-restassured + test + @@ -62,13 +74,49 @@ org.springframework.boot spring-boot-maven-plugin + + org.asciidoctor + asciidoctor-maven-plugin + ${asciidoctor-plugin.version} + + + generate-docs + package + + process-asciidoc + + + html + book + + ${snippetsDirectory} + + src/main/resources/asciidocs + target/generated-docs + + + + + + + true + src/main/resources + + application.properties + data.sql + schema.sql + + + 1.8 5.2.10.Final 1.2.32 + 1.5.6 + ${project.build.directory}/generated-snippets diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Application.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Application.java new file mode 100644 index 0000000000..93a28a2b49 --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Application.java @@ -0,0 +1,28 @@ +package com.baeldung.restdocopenapi; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.info.License; + +@SpringBootApplication() +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @Bean + public OpenAPI customOpenAPI(@Value("${springdoc.version}") String appVersion) { + return new OpenAPI().info(new Info().title("Foobar API") + .version(appVersion) + .description("This is a sample Foobar server created using springdocs - a library for OpenAPI 3 with spring boot.") + .termsOfService("http://swagger.io/terms/") + .license(new License().name("Apache 2.0") + .url("http://springdoc.org"))); + } +} diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Foo.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Foo.java new file mode 100644 index 0000000000..99d63581be --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Foo.java @@ -0,0 +1,93 @@ +package com.baeldung.restdocopenapi; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Foo { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(nullable = false) + private String title; + + @Column() + private String body; + + + protected Foo() { + } + + public Foo(long id, String title, String body) { + this.id = id; + this.title = title; + this.body = body; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((title == null) ? 0 : title.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Foo other = (Foo) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (title == null) { + if (other.title != null) + return false; + } else if (!title.equals(other.title)) + return false; + return true; + } + + @Override + public String toString() { + return "Foo [id=" + id + ", title=" + title + "]"; + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooController.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooController.java new file mode 100644 index 0000000000..55c2cccb3c --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooController.java @@ -0,0 +1,83 @@ +package com.baeldung.restdocopenapi; + +import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; + +import java.util.List; +import java.util.Optional; + +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/foo") +public class FooController { + + @Autowired + FooRepository repository; + + @GetMapping + public ResponseEntity> getAllFoos() { + List fooList = (List) repository.findAll(); + if (fooList.isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + return new ResponseEntity<>(fooList, HttpStatus.OK); + } + + @GetMapping(value = "{id}") + public ResponseEntity getFooById(@PathVariable("id") Long id) { + + Optional foo = repository.findById(id); + return foo.isPresent() ? new ResponseEntity<>(foo.get(), HttpStatus.OK) : new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + + @PostMapping + public ResponseEntity addFoo(@RequestBody @Valid Foo foo) { + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.setLocation(linkTo(FooController.class).slash(foo.getId()) + .toUri()); + Foo savedFoo; + try { + savedFoo = repository.save(foo); + } catch (Exception e) { + return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + } + + return new ResponseEntity<>(savedFoo, httpHeaders, HttpStatus.CREATED); + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteFoo(@PathVariable("id") long id) { + try { + repository.deleteById(id); + } catch (Exception e) { + return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + } + return new ResponseEntity<>(HttpStatus.NO_CONTENT); + } + + @PutMapping("/{id}") + public ResponseEntity updateFoo(@PathVariable("id") long id, @RequestBody Foo foo) { + boolean isFooPresent = repository.existsById(Long.valueOf(id)); + + if (!isFooPresent) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + + Foo updatedFoo = repository.save(foo); + + return new ResponseEntity<>(updatedFoo, HttpStatus.OK); + } +} diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooRepository.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooRepository.java new file mode 100644 index 0000000000..105b57b2ef --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.restdocopenapi; + +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface FooRepository extends PagingAndSortingRepository{ + +} diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/springdoc/FooBarController.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/springdoc/FooBarController.java new file mode 100644 index 0000000000..8af414c8fd --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/springdoc/FooBarController.java @@ -0,0 +1,121 @@ +package com.baeldung.restdocopenapi.springdoc; + +import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; + +import java.util.List; +import java.util.Optional; + +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.restdocopenapi.Foo; +import com.baeldung.restdocopenapi.FooRepository; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import io.swagger.v3.oas.annotations.tags.Tag; + +@RestController +@RequestMapping("/foobar") +@Tag(name = "foobar", description = "the foobar API with documentation annotations") +public class FooBarController { + + @Autowired + FooRepository repository; + + @Operation(summary = "Get all foos") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "found foos", content = { + @Content(mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = Foo.class)))}), + @ApiResponse(responseCode = "404", description = "No Foos found", content = @Content) }) + @GetMapping + public ResponseEntity> getAllFoos() { + List fooList = (List) repository.findAll(); + if (fooList.isEmpty()) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + return new ResponseEntity<>(fooList, HttpStatus.OK); + } + + @Operation(summary = "Get a foo by foo id") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "found the foo", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Foo.class))}), + @ApiResponse(responseCode = "400", description = "Invalid id supplied", content = @Content), + @ApiResponse(responseCode = "404", description = "Foo not found", content = @Content) }) + @GetMapping(value = "{id}") + public ResponseEntity getFooById(@Parameter(description = "id of foo to be searched") @PathVariable("id") String id) { + + Optional foo = repository.findById(Long.valueOf(id)); + return foo.isPresent() ? new ResponseEntity<>(foo.get(), HttpStatus.OK) : new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + + @Operation(summary = "Create a foo") + @ApiResponses(value = { + @ApiResponse(responseCode = "201", description = "foo created", content = { @ + Content(mediaType = "application/json", schema = @Schema(implementation = Foo.class))}), + @ApiResponse(responseCode = "404", description = "Bad request", content = @Content) }) + @PostMapping + public ResponseEntity addFoo(@Parameter(description = "foo object to be created") @RequestBody @Valid Foo foo) { + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.setLocation(linkTo(FooBarController.class).slash(foo.getId()).toUri()); + Foo savedFoo; + try { + savedFoo = repository.save(foo); + } catch (Exception e) { + return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + } + + return new ResponseEntity<>(savedFoo, httpHeaders, HttpStatus.CREATED); + } + + @Operation(summary = "Delete a foo") + @ApiResponses(value = { + @ApiResponse(responseCode = "204", description = "foo deleted"), + @ApiResponse(responseCode = "404", description = "Bad request", content = @Content) }) + @DeleteMapping("/{id}") + public ResponseEntity deleteFoo(@Parameter(description = "id of foo to be deleted") @PathVariable("id") long id) { + try { + repository.deleteById(id); + } catch (Exception e) { + return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + } + return new ResponseEntity<>(HttpStatus.NO_CONTENT); + } + + @Operation(summary = "Update a foo") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "foo updated successfully", content = { + @Content(mediaType = "application/json", schema = @Schema(implementation = Foo.class))}), + @ApiResponse(responseCode = "404", description = "No Foo exists with given id", content = @Content) }) + @PutMapping("/{id}") + public ResponseEntity updateFoo(@Parameter(description = "id of foo to be updated") @PathVariable("id") long id, @RequestBody Foo foo) { + + boolean isFooPresent = repository.existsById(Long.valueOf(id)); + + if (!isFooPresent) { + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + + Foo updatedFoo = repository.save(foo); + + return new ResponseEntity<>(updatedFoo, HttpStatus.OK); + } +} diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties b/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties index 45378e610b..4191d8ba25 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties @@ -5,4 +5,7 @@ springdoc.swagger-ui.path=/swagger-ui-custom.html springdoc.api-docs.path=/api-docs # H2 Related Configurations -spring.datasource.url=jdbc:h2:mem:springdoc \ No newline at end of file +spring.datasource.url=jdbc:h2:mem:springdoc + +springdoc.version=@springdoc.version@ +spring.jpa.hibernate.ddl-auto=none \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/resources/asciidocs/fooapi.adoc b/spring-boot-modules/spring-boot-springdoc/src/main/resources/asciidocs/fooapi.adoc new file mode 100644 index 0000000000..90791cbbcf --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/resources/asciidocs/fooapi.adoc @@ -0,0 +1,153 @@ += RESTful Notes API Guide +Baeldung; +:doctype: book +:icons: font +:source-highlighter: highlightjs +:toc: left +:toclevels: 4 +:sectlinks: + +[[overview]] += Overview + +[[overview-http-verbs]] +== HTTP verbs + +RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its +use of HTTP verbs. + +|=== +| Verb | Usage + +| `GET` +| Used to retrieve a resource + +| `POST` +| Used to create a new resource + +| `PUT` +| Used to update an existing resource + +| `DELETE` +| Used to delete an existing resource +|=== + +RESTful notes tries to adhere as closely as possible to standard HTTP and REST conventions in its +use of HTTP status codes. + +|=== +| Status code | Usage + +| `200 OK` +| The request completed successfully + +| `201 Created` +| A new resource has been created successfully. The resource's URI is available from the response's +`Location` header + +| `204 No Content` +| An update to an existing resource has been applied successfully + +| `400 Bad Request` +| The request was malformed. The response body will include an error providing further information + +| `404 Not Found` +| The requested resource did not exist +|=== + +[[overview-hypermedia]] +== Hypermedia + +RESTful Notes uses hypermedia and resources include links to other resources in their +responses. Responses are in http://stateless.co/hal_specification.html[Hypertext Application +from resource to resource. +Language (HAL)] format. Links can be found beneath the `_links` key. Users of the API should +not create URIs themselves, instead they should use the above-described links to navigate + +[[resources]] += Resources + +[[resources-FOO]] +== FOO REST Service + +The FOO provides the entry point into the service. + +[[resources-foo-get]] +=== Accessing the foo GET + +A `GET` request is used to access the foo read. + +==== Request structure + +include::{snippets}/getAFoo/http-request.adoc[] + +==== Path Parameters +include::{snippets}/getAFoo/path-parameters.adoc[] + +==== Example response + +include::{snippets}/getAFoo/http-response.adoc[] + +==== CURL request + +include::{snippets}/getAFoo/curl-request.adoc[] + +[[resources-foo-post]] +=== Accessing the foo POST + +A `POST` request is used to access the foo create. + +==== Request structure + +include::{snippets}/createFoo/http-request.adoc[] + +==== Example response + +include::{snippets}/createFoo/http-response.adoc[] + +==== CURL request + +include::{snippets}/createFoo/curl-request.adoc[] + +[[resources-foo-delete]] +=== Accessing the foo DELETE + +A `DELETE` request is used to access the foo delete. + +==== Request structure + +include::{snippets}/deleteFoo/http-request.adoc[] + +==== Path Parameters +include::{snippets}/deleteFoo/path-parameters.adoc[] + +==== Example response + +include::{snippets}/deleteFoo/http-response.adoc[] + +==== CURL request + +include::{snippets}/deleteFoo/curl-request.adoc[] + +[[resources-foo-put]] +=== Accessing the foo PUT + +A `PUT` request is used to access the foo update. + +==== Request structure + +include::{snippets}/updateFoo/http-request.adoc[] + +==== Path Parameters +include::{snippets}/updateFoo/path-parameters.adoc[] + +==== Example response + +include::{snippets}/updateFoo/http-response.adoc[] + +==== CURL request + +include::{snippets}/updateFoo/curl-request.adoc[] + + + diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/resources/data.sql b/spring-boot-modules/spring-boot-springdoc/src/main/resources/data.sql new file mode 100644 index 0000000000..f80e53b717 --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/resources/data.sql @@ -0,0 +1,4 @@ +INSERT INTO Foo(id, title, body) VALUES (1, 'Foo 1', 'Foo body 1'); +INSERT INTO Foo(id, title, body) VALUES (2, 'Foo 2', 'Foo body 2'); +INSERT INTO Foo(id, title, body) VALUES (3, 'Foo 3', 'Foo body 3'); + diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/resources/schema.sql b/spring-boot-modules/spring-boot-springdoc/src/main/resources/schema.sql new file mode 100644 index 0000000000..e5d33da019 --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/resources/schema.sql @@ -0,0 +1,8 @@ +DROP TABLE IF EXISTS foo; + +CREATE TABLE foo ( + id INTEGER NOT NULL AUTO_INCREMENT, + title VARCHAR(250) NOT NULL, + body VARCHAR(250), + PRIMARY KEY (id) +); \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-springdoc/src/test/java/com/baeldung/restdocopenapi/restdoc/SpringRestDocsUnitTest.java b/spring-boot-modules/spring-boot-springdoc/src/test/java/com/baeldung/restdocopenapi/restdoc/SpringRestDocsUnitTest.java new file mode 100644 index 0000000000..4d37abf78a --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/test/java/com/baeldung/restdocopenapi/restdoc/SpringRestDocsUnitTest.java @@ -0,0 +1,120 @@ +package com.baeldung.restdocopenapi.restdoc; + +import static org.hamcrest.Matchers.containsString; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; +import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.put; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; +import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; +import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; +import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; +import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; +import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; +import static org.springframework.restdocs.request.RequestDocumentation.pathParameters; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.util.StringUtils.collectionToDelimitedString; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.hateoas.MediaTypes; +import org.springframework.restdocs.RestDocumentationContextProvider; +import org.springframework.restdocs.RestDocumentationExtension; +import org.springframework.restdocs.constraints.ConstraintDescriptions; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.restdocopenapi.Application; +import com.baeldung.restdocopenapi.Foo; +import com.fasterxml.jackson.databind.ObjectMapper; + +@ExtendWith({ RestDocumentationExtension.class, SpringExtension.class }) +@SpringBootTest(classes = Application.class) +public class SpringRestDocsUnitTest { + + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @BeforeEach + public void setup(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) { + this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) + .apply(documentationConfiguration(restDocumentation)) + .build(); + } + + @Test + public void whenGetFoo_thenSuccessful() throws Exception { + this.mockMvc.perform(get("/foo")) + .andDo(print()) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("Foo 1"))) + .andDo(document("getAllFoos")); + } + + @Test + public void whenGetFooById_thenSuccessful() throws Exception { + ConstraintDescriptions desc = new ConstraintDescriptions(Foo.class); + + this.mockMvc.perform(get("/foo/{id}", 1)) + .andExpect(status().isOk()) + .andDo(document("getAFoo", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), + pathParameters(parameterWithName("id").description("id of foo to be searched")), + responseFields(fieldWithPath("id").description("The id of the foo" + collectionToDelimitedString(desc.descriptionsForProperty("id"), ". ")), + fieldWithPath("title").description("The title of the foo"), fieldWithPath("body").description("The body of the foo")))); + } + + @Test + public void whenPostFoo_thenSuccessful() throws Exception { + Map foo = new HashMap<>(); + foo.put("id", 4L); + foo.put("title", "New Foo"); + foo.put("body", "Body of New Foo"); + + this.mockMvc.perform(post("/foo").contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(foo))) + .andExpect(status().isCreated()) + .andDo(document("createFoo", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), requestFields(fieldWithPath("id").description("The id of the foo"), fieldWithPath("title").description("The title of the foo"), + fieldWithPath("body").description("The body of the foo")))); + } + + @Test + public void whenDeleteFoo_thenSuccessful() throws Exception { + this.mockMvc.perform(delete("/foo/{id}", 2)) + .andExpect(status().isNoContent()) + .andDo(document("deleteFoo", pathParameters(parameterWithName("id").description("The id of the foo to delete")))); + } + + @Test + public void whenUpdateFoo_thenSuccessful() throws Exception { + + ConstraintDescriptions desc = new ConstraintDescriptions(Foo.class); + + Map foo = new HashMap<>(); + foo.put("title", "Updated Foo"); + foo.put("body", "Body of Updated Foo"); + + this.mockMvc.perform(put("/foo/{id}", 3).contentType(MediaTypes.HAL_JSON) + .content(this.objectMapper.writeValueAsString(foo))) + .andExpect(status().isOk()) + .andDo(document("updateFoo", pathParameters(parameterWithName("id").description("The id of the foo to update")), + responseFields(fieldWithPath("id").description("The id of the updated foo" + collectionToDelimitedString(desc.descriptionsForProperty("id"), ". ")), + fieldWithPath("title").description("The title of the updated foo"), fieldWithPath("body").description("The body of the updated foo")))); + } + + +} From e264ffd4bc99e7bba12b692a5e27d2749fc17ffa Mon Sep 17 00:00:00 2001 From: Anirban Date: Sat, 16 May 2020 09:43:14 +0200 Subject: [PATCH 091/150] Added if-else expression examples in kotlin (#9296) --- .../IfElseExpressionExample.kt | 86 +++++++++++++++++++ .../IfElseExpressionExampleTest.kt | 43 ++++++++++ 2 files changed, 129 insertions(+) create mode 100644 core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExample.kt create mode 100644 core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExampleTest.kt diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExample.kt b/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExample.kt new file mode 100644 index 0000000000..f4e42a4f4f --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExample.kt @@ -0,0 +1,86 @@ +package com.baeldung.ifelseexpression + +fun ifStatementUsage(): String { + val number = 15 + + if (number > 0) { + return "Positive number" + } + return "Positive number not found" +} + +fun ifElseStatementUsage(): String { + val number = -50 + + if (number > 0) { + return "Positive number" + } else { + return "Negative number" + } +} + +fun ifElseExpressionUsage(): String { + val number = -50 + + val result = if (number > 0) { + "Positive number" + } else { + "Negative number" + } + return result +} + +fun ifElseExpressionSingleLineUsage(): String { + val number = -50 + val result = if (number > 0) "Positive number" else "Negative number" + + return result +} + +fun ifElseMultipleExpressionUsage(): Int { + val x = 24 + val y = 73 + + val result = if (x > y) { + println("$x is greater than $y") + x + } else { + println("$x is less than or equal to $y") + y + } + return result +} + +fun ifElseLadderExpressionUsage(): String { + val number = 60 + + val result = if (number < 0) { + "Negative number" + } else if (number in 0..9) { + "Single digit number" + } else if (number in 10..99) { + "Double digit number" + } else { + "Number has more digits" + } + return result +} + +fun ifElseNestedExpressionUsage(): Int { + val x = 37 + val y = 89 + val z = 6 + + val result = if (x > y) { + if (x > z) + x + else + z + } else { + if (y > z) + y + else + z + } + return result +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExampleTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExampleTest.kt new file mode 100644 index 0000000000..266e41e07b --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/ifelseexpression/IfElseExpressionExampleTest.kt @@ -0,0 +1,43 @@ +package com.baeldung.ifelseexpression + +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotEquals + +class IfElseExpressionExampleTest { + + @Test + fun givenNumber_whenIfStatementCalled_thenReturnsString() { + assertEquals("Positive number", ifStatementUsage()) + } + + @Test + fun givenNumber_whenIfElseStatementCalled_thenReturnsString() { + assertEquals("Negative number", ifElseStatementUsage()) + } + + @Test + fun givenNumber_whenIfElseExpressionCalled_thenReturnsString() { + assertEquals("Negative number", ifElseExpressionUsage()) + } + + @Test + fun givenNumber_whenIfElseExpressionSingleLineCalled_thenReturnsString() { + assertEquals("Negative number", ifElseExpressionSingleLineUsage()) + } + + @Test + fun givenNumber_whenIfElseMultipleExpressionCalled_thenReturnsNumber() { + assertEquals(73, ifElseMultipleExpressionUsage()) + } + + @Test + fun givenNumber_whenIfElseLadderExpressionCalled_thenReturnsString() { + assertEquals("Double digit number", ifElseLadderExpressionUsage()) + } + + @Test + fun givenNumber_whenIfElseNestedExpressionCalled_thenReturnsNumber() { + assertEquals(89, ifElseNestedExpressionUsage()) + } +} \ No newline at end of file From c72b2846d5e8b65868a1196f2cc11fb520d791d2 Mon Sep 17 00:00:00 2001 From: sasam0320 <63002713+sasam0320@users.noreply.github.com> Date: Sat, 16 May 2020 10:03:47 +0200 Subject: [PATCH 092/150] BAEL 3234 - Add missing code snippets (#9285) --- .../ConfigPropertiesDemoApplication.java | 2 +- .../com/baeldung/properties/Database.java | 33 ------------------- .../main/resources/configForProperties.xml | 4 --- .../src/main/resources/database.properties | 1 - .../src/main/resources/database.yml | 3 +- .../ConfigPropertiesIntegrationTest.java | 14 ++------ .../DatabasePropertiesIntegrationTest.java | 10 +++--- .../src/test/resources/application.properties | 3 -- 8 files changed, 11 insertions(+), 59 deletions(-) delete mode 100644 spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/Database.java diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java index e54f28837d..e280bbd79f 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java @@ -7,7 +7,7 @@ import org.springframework.context.annotation.ComponentScan; import com.baeldung.configurationproperties.ConfigProperties; @SpringBootApplication -@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class, Database.class }) +@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class}) public class ConfigPropertiesDemoApplication { public static void main(String[] args) { new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer()) diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/Database.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/Database.java deleted file mode 100644 index 6e798672e7..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/Database.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.properties; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ConfigurationProperties(prefix = "database") -public class Database { - - private String url; - private String username; - private String password; - - public String getUrl() { - return url; - } - public void setUrl(String url) { - this.url = url; - } - public String getUsername() { - return username; - } - public void setUsername(String username) { - this.username = username; - } - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - -} diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml b/spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml index bf4452da4a..16db00ace3 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml @@ -14,8 +14,4 @@ - - - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties index eb5703ca72..24bfdf2096 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties @@ -1,4 +1,3 @@ - jdbc.url=jdbc:postgresql:/localhost:5432 database.username=foo database.password=bar diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/database.yml b/spring-boot-modules/spring-boot-properties/src/main/resources/database.yml index 8404d9411a..83432f65bc 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/resources/database.yml +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/database.yml @@ -1,5 +1,6 @@ database: - url: jdbc:postresql:/localhost:5432/instance + jdbc: + url: jdbc:postresql:/localhost:5432 username: foo password: bar secret: foo \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ConfigPropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ConfigPropertiesIntegrationTest.java index 2b0833c387..3b80fa66fe 100644 --- a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ConfigPropertiesIntegrationTest.java +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ConfigPropertiesIntegrationTest.java @@ -14,17 +14,13 @@ import com.baeldung.properties.AdditionalProperties; import com.baeldung.properties.ConfigPropertiesDemoApplication; @RunWith(SpringRunner.class) -@SpringBootTest(classes = {ConfigPropertiesDemoApplication.class, DatabaseConfigPropertiesApp.class}) -@TestPropertySource(locations = {"classpath:configprops-test.properties", "classpath:database-test.properties"}) +@SpringBootTest(classes = {ConfigPropertiesDemoApplication.class}) +@TestPropertySource(locations = {"classpath:configprops-test.properties"}) public class ConfigPropertiesIntegrationTest { @Autowired private ConfigProperties properties; - @Autowired - @Qualifier("dataSource") - private Database databaseProperties; - @Autowired private AdditionalProperties additionalProperties; @@ -59,10 +55,4 @@ public class ConfigPropertiesIntegrationTest { Assert.assertTrue(additionalProperties.getMax() == 100); } - @Test - public void whenDatabasePropertyQueriedthenReturnsProperty() { - Assert.assertTrue(databaseProperties.getUrl().equals("jdbc:postgresql:/localhost:5432")); - Assert.assertTrue(databaseProperties.getUsername().equals("foo")); - Assert.assertTrue(databaseProperties.getPassword().equals("bar")); - } } diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/DatabasePropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/DatabasePropertiesIntegrationTest.java index 0b9bd797ae..50a129916f 100644 --- a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/DatabasePropertiesIntegrationTest.java +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/DatabasePropertiesIntegrationTest.java @@ -4,26 +4,28 @@ import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.properties.ConfigPropertiesDemoApplication; -import com.baeldung.properties.Database; +import com.baeldung.configurationproperties.Database; @RunWith(SpringRunner.class) -@SpringBootTest(classes = ConfigPropertiesDemoApplication.class) -@TestPropertySource("classpath:application.properties") +@SpringBootTest(classes = DatabaseConfigPropertiesApp.class) +@TestPropertySource("classpath:database-test.properties") public class DatabasePropertiesIntegrationTest { @Autowired + @Qualifier("dataSource") private Database database; @Test public void testDatabaseProperties() { Assert.assertNotNull(database); - Assert.assertEquals("jdbc:postgresql:/localhost:5432/instance", database.getUrl()); + Assert.assertEquals("jdbc:postgresql:/localhost:5432", database.getUrl()); Assert.assertEquals("foo", database.getUsername()); Assert.assertEquals("bar", database.getPassword()); } diff --git a/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties b/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties index d4d1df7abc..af38556f81 100644 --- a/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties +++ b/spring-boot-modules/spring-boot-properties/src/test/resources/application.properties @@ -3,6 +3,3 @@ spring.properties.refreshDelay=1000 spring.config.location=file:extra.properties spring.main.allow-bean-definition-overriding=true -database.url=jdbc:postgresql:/localhost:5432/instance -database.username=foo -database.password=bar \ No newline at end of file From ab9d1cd461e80a3a263096f3263d122f960b8e93 Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sat, 16 May 2020 15:24:23 +0530 Subject: [PATCH 093/150] updated java comment --- .../CollectionToArrayListUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java index 15960c300d..b8134de08a 100644 --- a/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java @@ -88,7 +88,7 @@ public class CollectionToArrayListUnitTest { Iterator iterA = a.iterator(); Iterator iterB = b.iterator(); while (iterA.hasNext()) { - // use '==' to test instance identity + // test instance identity assertSame("Foo instances differ!", iterA.next(), iterB.next()); } } From 7d1e22b44f158bad2f59fa6b3506e09839d87823 Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sat, 16 May 2020 16:29:39 +0530 Subject: [PATCH 094/150] modified MvcVoterConfig controller path --- .../src/main/java/com/baeldung/roles/voter/VoterMvcConfig.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterMvcConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterMvcConfig.java index f11a4ae06c..402065129f 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterMvcConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterMvcConfig.java @@ -12,6 +12,6 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; public class VoterMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { - registry.addViewController("/").setViewName("private"); + registry.addViewController("/private").setViewName("private"); } } From 29dde3b4855c49ddba924a035099d752fa10c46a Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sat, 16 May 2020 17:06:29 +0530 Subject: [PATCH 095/150] updated spring kafka version --- spring-kafka/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index d60a2ee506..2b4a0914e6 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -33,7 +33,7 @@ - 2.2.7.RELEASE + 2.3.7.RELEASE \ No newline at end of file From 958435e0b3ab23725010544c8ad2c307c490f6fb Mon Sep 17 00:00:00 2001 From: mikr Date: Sat, 16 May 2020 17:04:21 +0200 Subject: [PATCH 096/150] BAEL-1524 Add HikariCP exclusion to Spring Boot Data JPA dependency --- persistence-modules/spring-boot-persistence-2/pom.xml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/persistence-modules/spring-boot-persistence-2/pom.xml b/persistence-modules/spring-boot-persistence-2/pom.xml index 58432a5c9c..b5cdfbafc9 100644 --- a/persistence-modules/spring-boot-persistence-2/pom.xml +++ b/persistence-modules/spring-boot-persistence-2/pom.xml @@ -49,6 +49,12 @@ org.springframework.boot spring-boot-starter-data-jpa + + + com.zaxxer + HikariCP + + @@ -120,7 +126,6 @@ org.hsqldb hsqldb - From 3d9c2403ab8a6d5ab2d6c0b1ecfee173469a890b Mon Sep 17 00:00:00 2001 From: mikr Date: Sat, 16 May 2020 17:17:21 +0200 Subject: [PATCH 097/150] BAEL-1524 Put back HikariCP --- persistence-modules/spring-boot-persistence/pom.xml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/persistence-modules/spring-boot-persistence/pom.xml b/persistence-modules/spring-boot-persistence/pom.xml index c58e8dbf86..99c00f6784 100644 --- a/persistence-modules/spring-boot-persistence/pom.xml +++ b/persistence-modules/spring-boot-persistence/pom.xml @@ -26,12 +26,6 @@ org.springframework.boot spring-boot-starter-data-jpa - - - com.zaxxer - HikariCP - - org.springframework.boot From 94ed56e4f5410c7c478e23150ed858f89803e8f8 Mon Sep 17 00:00:00 2001 From: mikr Date: Sat, 16 May 2020 17:21:28 +0200 Subject: [PATCH 098/150] BAEL-1524 Put back HikariCP --- persistence-modules/spring-boot-persistence-2/pom.xml | 6 ------ persistence-modules/spring-boot-persistence/pom.xml | 6 ++++++ 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/persistence-modules/spring-boot-persistence-2/pom.xml b/persistence-modules/spring-boot-persistence-2/pom.xml index b5cdfbafc9..33b33d7160 100644 --- a/persistence-modules/spring-boot-persistence-2/pom.xml +++ b/persistence-modules/spring-boot-persistence-2/pom.xml @@ -49,12 +49,6 @@ org.springframework.boot spring-boot-starter-data-jpa - - - com.zaxxer - HikariCP - - diff --git a/persistence-modules/spring-boot-persistence/pom.xml b/persistence-modules/spring-boot-persistence/pom.xml index 99c00f6784..c58e8dbf86 100644 --- a/persistence-modules/spring-boot-persistence/pom.xml +++ b/persistence-modules/spring-boot-persistence/pom.xml @@ -26,6 +26,12 @@ org.springframework.boot spring-boot-starter-data-jpa + + + com.zaxxer + HikariCP + + org.springframework.boot From dca1a9fb3f644731d5b41b13d0c55f08a00beed4 Mon Sep 17 00:00:00 2001 From: mikr Date: Sat, 16 May 2020 18:20:33 +0200 Subject: [PATCH 099/150] BAEL-1524 Fix test --- .../spring-boot-persistence-2/src/test/resources/schema.sql | 3 +++ 1 file changed, 3 insertions(+) diff --git a/persistence-modules/spring-boot-persistence-2/src/test/resources/schema.sql b/persistence-modules/spring-boot-persistence-2/src/test/resources/schema.sql index a0d0eaf62e..8d7db6c9f3 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/resources/schema.sql +++ b/persistence-modules/spring-boot-persistence-2/src/test/resources/schema.sql @@ -1,3 +1,6 @@ +drop table if exists car_maker; +drop table if exists car_model; + -- -- Car makers table -- From 44a1ec0195c5e92200f60fea26f1eb39ec73f716 Mon Sep 17 00:00:00 2001 From: ajay74984 <51405689+ajay74984@users.noreply.github.com> Date: Sun, 17 May 2020 05:27:15 +0200 Subject: [PATCH 100/150] OCP change (#9266) * OCP change * calculator unit test --- .../main/java/com/baeldung/o/Addition.java | 41 +++++++++++++++++ .../main/java/com/baeldung/o/Calculator.java | 14 ++++++ .../com/baeldung/o/CalculatorOperation.java | 7 +++ .../main/java/com/baeldung/o/Division.java | 43 ++++++++++++++++++ .../main/java/com/baeldung/o/Subtraction.java | 41 +++++++++++++++++ .../com/baeldung/o/CalculatorUnitTest.java | 44 +++++++++++++++++++ 6 files changed, 190 insertions(+) create mode 100644 patterns/solid/src/main/java/com/baeldung/o/Addition.java create mode 100644 patterns/solid/src/main/java/com/baeldung/o/Calculator.java create mode 100644 patterns/solid/src/main/java/com/baeldung/o/CalculatorOperation.java create mode 100644 patterns/solid/src/main/java/com/baeldung/o/Division.java create mode 100644 patterns/solid/src/main/java/com/baeldung/o/Subtraction.java create mode 100644 patterns/solid/src/main/test/com/baeldung/o/CalculatorUnitTest.java diff --git a/patterns/solid/src/main/java/com/baeldung/o/Addition.java b/patterns/solid/src/main/java/com/baeldung/o/Addition.java new file mode 100644 index 0000000000..6145b386d9 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/o/Addition.java @@ -0,0 +1,41 @@ +package com.baeldung.o; + +public class Addition implements CalculatorOperation { + private double number1; + private double number2; + private double result = 0.0; + + public Addition(double number1, double number2) { + this.number1 = number1; + this.number2 = number2; + } + + public double getNumber1() { + return number1; + } + + public void setNumber1(double number1) { + this.number1 = number1; + } + + public double getNumber2() { + return number2; + } + + public void setNumber2(double number2) { + this.number2 = number2; + } + + public double getResult() { + return result; + } + + public void setResult(double result) { + this.result = result; + } + + @Override + public void perform() { + result = number1 + number2; + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/o/Calculator.java b/patterns/solid/src/main/java/com/baeldung/o/Calculator.java new file mode 100644 index 0000000000..11ace8eb20 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/o/Calculator.java @@ -0,0 +1,14 @@ +package com.baeldung.o; + +import java.security.InvalidParameterException; + +public class Calculator { + + public void calculate(CalculatorOperation operation) { + if (operation == null) { + throw new InvalidParameterException("Can not perform operation"); + } + + operation.perform(); + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/o/CalculatorOperation.java b/patterns/solid/src/main/java/com/baeldung/o/CalculatorOperation.java new file mode 100644 index 0000000000..46648e25d8 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/o/CalculatorOperation.java @@ -0,0 +1,7 @@ +package com.baeldung.o; + +public interface CalculatorOperation { + + void perform(); + +} diff --git a/patterns/solid/src/main/java/com/baeldung/o/Division.java b/patterns/solid/src/main/java/com/baeldung/o/Division.java new file mode 100644 index 0000000000..24ab4355c2 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/o/Division.java @@ -0,0 +1,43 @@ +package com.baeldung.o; + +public class Division implements CalculatorOperation { + private double number1; + private double number2; + private double result = 0.0; + + public Division(double number1, double number2) { + this.number1 = number1; + this.number2 = number2; + } + + public double getNumber1() { + return number1; + } + + public void setNumber1(double number1) { + this.number1 = number1; + } + + public double getNumber2() { + return number2; + } + + public void setNumber2(double number2) { + this.number2 = number2; + } + + public double getResult() { + return result; + } + + public void setResult(double result) { + this.result = result; + } + + @Override + public void perform() { + if (number2 != 0) { + result = number1 / number2; + } + } +} diff --git a/patterns/solid/src/main/java/com/baeldung/o/Subtraction.java b/patterns/solid/src/main/java/com/baeldung/o/Subtraction.java new file mode 100644 index 0000000000..b74e0c5f73 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/o/Subtraction.java @@ -0,0 +1,41 @@ +package com.baeldung.o; + +public class Subtraction implements CalculatorOperation { + private double number1; + private double number2; + private double result = 0.0; + + public Subtraction(double number1, double number2) { + this.number1 = number1; + this.number2 = number2; + } + + public double getNumber1() { + return number1; + } + + public void setNumber1(double number1) { + this.number1 = number1; + } + + public double getNumber2() { + return number2; + } + + public void setNumber2(double number2) { + this.number2 = number2; + } + + public double getResult() { + return result; + } + + public void setResult(double result) { + this.result = result; + } + + @Override + public void perform() { + result = number1 - number2; + } +} diff --git a/patterns/solid/src/main/test/com/baeldung/o/CalculatorUnitTest.java b/patterns/solid/src/main/test/com/baeldung/o/CalculatorUnitTest.java new file mode 100644 index 0000000000..f372d450a7 --- /dev/null +++ b/patterns/solid/src/main/test/com/baeldung/o/CalculatorUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.o; + +import static org.junit.Assert.assertEquals; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class CalculatorUnitTest { + + private static final double NUMBER_1 = 10.0; + private static final double NUMBER_2 = 20.0; + private static final double SUM = 30.0; + private static final double SUBTRACTION_RESULT = 10.0; + private static final double DIVISION_RESULT = 2.0; + + private Calculator calculator; + + @BeforeEach + public void setUp() { + calculator = new Calculator(); + } + + @Test + public void whenAddTwoNumber_returnSum() { + Addition addition = new Addition(NUMBER_1, NUMBER_2); + calculator.calculate(addition); + assertEquals(SUM, addition.getResult(), 0.0); + } + + @Test + public void whenSutractTwoNumber_returnCorrectResult() { + Subtraction subtraction = new Subtraction(NUMBER_2, NUMBER_1); + calculator.calculate(subtraction); + assertEquals(SUBTRACTION_RESULT, subtraction.getResult(), 0.0); + } + + @Test + public void whenDivideTwoNumber_returnCorrectResult() { + Division division = new Division(NUMBER_2, NUMBER_1); + calculator.calculate(division); + assertEquals(DIVISION_RESULT, division.getResult(), 0.0); + } + +} From ef5ea0f77c228e0fb5d6862e99a553f8c55ab765 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 17 May 2020 11:31:38 +0530 Subject: [PATCH 101/150] JAVA-941: Migrate spring-jinq to parent-boot-2 --- spring-jinq/pom.xml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/spring-jinq/pom.xml b/spring-jinq/pom.xml index 29fc3605d7..96cff4b886 100644 --- a/spring-jinq/pom.xml +++ b/spring-jinq/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -31,6 +31,11 @@ org.hibernate hibernate-entitymanager + + + org.springframework.boot + spring-boot-starter-data-jpa + From 832b32210c2843ac0c1168005c5e5e07dcfbe461 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Sun, 17 May 2020 12:59:16 +0200 Subject: [PATCH 102/150] BAEL-3745: Implement PropertySourceFactory to load YAML files (new module) (#9307) --- .../spring-boot-properties-2/README.md | 5 +++ .../spring-boot-properties-2/pom.xml | 25 +++++++++++ .../properties/yaml/YamlApplication.java | 22 ++++++++++ .../properties/yaml/YamlFooProperties.java | 42 +++++++++++++++++++ .../factory/YamlPropertySourceFactory.java | 24 +++++++++++ .../src/main/resources/foo.yml | 5 +++ .../YamlFooPropertiesIntegrationTest.java | 23 ++++++++++ 7 files changed, 146 insertions(+) create mode 100644 spring-boot-modules/spring-boot-properties-2/README.md create mode 100644 spring-boot-modules/spring-boot-properties-2/pom.xml create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/YamlApplication.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/YamlFooProperties.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/factory/YamlPropertySourceFactory.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/resources/foo.yml create mode 100644 spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/yaml/YamlFooPropertiesIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-properties-2/README.md b/spring-boot-modules/spring-boot-properties-2/README.md new file mode 100644 index 0000000000..01e2970e89 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/README.md @@ -0,0 +1,5 @@ +## Spring Boot Properties + +This module contains articles about Properties in Spring Boot. + +### Relevant Articles: diff --git a/spring-boot-modules/spring-boot-properties-2/pom.xml b/spring-boot-modules/spring-boot-properties-2/pom.xml new file mode 100644 index 0000000000..c3c3e57251 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + spring-boot-properties-2 + spring-boot-properties-2 + jar + Spring Boot Properties Module + 0.0.1-SNAPSHOT + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter + + + + diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/YamlApplication.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/YamlApplication.java new file mode 100644 index 0000000000..f1244925f1 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/YamlApplication.java @@ -0,0 +1,22 @@ +package com.baeldung.properties.yaml; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class YamlApplication implements CommandLineRunner { + + @Autowired + private YamlFooProperties yamlFooProperties; + + public static void main(String[] args) { + SpringApplication.run(YamlApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + System.out.println("YAML Properties " + yamlFooProperties); + } +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/YamlFooProperties.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/YamlFooProperties.java new file mode 100644 index 0000000000..264fc865ad --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/YamlFooProperties.java @@ -0,0 +1,42 @@ +package com.baeldung.properties.yaml; + +import com.baeldung.properties.yaml.factory.YamlPropertySourceFactory; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; + +import java.util.List; + +@Configuration +@ConfigurationProperties(prefix = "yaml") +@PropertySource(value = "classpath:foo.yml", factory = YamlPropertySourceFactory.class) +public class YamlFooProperties { + + private String name; + + private List aliases; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getAliases() { + return aliases; + } + + public void setAliases(List aliases) { + this.aliases = aliases; + } + + @Override + public String toString() { + return "YamlFooProperties{" + + "name='" + name + '\'' + + ", aliases=" + aliases + + '}'; + } +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/factory/YamlPropertySourceFactory.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/factory/YamlPropertySourceFactory.java new file mode 100644 index 0000000000..50201f9377 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/yaml/factory/YamlPropertySourceFactory.java @@ -0,0 +1,24 @@ +package com.baeldung.properties.yaml.factory; + +import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; +import org.springframework.core.env.PropertiesPropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.support.EncodedResource; +import org.springframework.core.io.support.PropertySourceFactory; + +import java.io.IOException; +import java.util.Properties; + +public class YamlPropertySourceFactory implements PropertySourceFactory { + + @Override + public PropertySource createPropertySource(String name, EncodedResource encodedResource) throws IOException { + YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); + factory.setResources(encodedResource.getResource()); + + Properties properties = factory.getObject(); + + return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties); + } + +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/resources/foo.yml b/spring-boot-modules/spring-boot-properties-2/src/main/resources/foo.yml new file mode 100644 index 0000000000..6320510a94 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/resources/foo.yml @@ -0,0 +1,5 @@ +yaml: + name: foo + aliases: + - abc + - xyz \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/yaml/YamlFooPropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/yaml/YamlFooPropertiesIntegrationTest.java new file mode 100644 index 0000000000..dfe1c830b4 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/yaml/YamlFooPropertiesIntegrationTest.java @@ -0,0 +1,23 @@ +package com.baeldung.properties.yaml; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class YamlFooPropertiesIntegrationTest { + + @Autowired + private YamlFooProperties yamlFooProperties; + + @Test + public void whenFactoryProvidedThenYamlPropertiesInjected() { + assertThat(yamlFooProperties.getName()).isEqualTo("foo"); + assertThat(yamlFooProperties.getAliases()).containsExactly("abc", "xyz"); + } +} \ No newline at end of file From 34bdc3f6cd10ac614da6b43101bb914d509996df Mon Sep 17 00:00:00 2001 From: Lukasz Rys Date: Sun, 17 May 2020 13:10:44 +0200 Subject: [PATCH 103/150] [BAEL-3751]: Move spring-boot-ci-cd module under spring-boot-modules --- pom.xml | 2 -- spring-boot-modules/pom.xml | 1 + .../spring-boot-ci-cd}/.mvn/wrapper/MavenWrapperDownloader.java | 0 .../spring-boot-ci-cd}/.mvn/wrapper/maven-wrapper.properties | 0 .../spring-boot-ci-cd}/.travis.yml | 0 .../spring-boot-ci-cd}/README.md | 0 .../spring-boot-ci-cd}/mvnw | 0 .../spring-boot-ci-cd}/mvnw.cmd | 0 .../spring-boot-ci-cd}/pom.xml | 2 +- .../src/main/java/com/baeldung/cicd/CiCdApplication.java | 0 .../src/main/resources/introduction-config.yml | 0 .../java/com/baeldung/cicd/CiCdApplicationIntegrationTest.java | 0 12 files changed, 2 insertions(+), 3 deletions(-) rename {spring-boot-ci-cd => spring-boot-modules/spring-boot-ci-cd}/.mvn/wrapper/MavenWrapperDownloader.java (100%) rename {spring-boot-ci-cd => spring-boot-modules/spring-boot-ci-cd}/.mvn/wrapper/maven-wrapper.properties (100%) rename {spring-boot-ci-cd => spring-boot-modules/spring-boot-ci-cd}/.travis.yml (100%) rename {spring-boot-ci-cd => spring-boot-modules/spring-boot-ci-cd}/README.md (100%) rename {spring-boot-ci-cd => spring-boot-modules/spring-boot-ci-cd}/mvnw (100%) rename {spring-boot-ci-cd => spring-boot-modules/spring-boot-ci-cd}/mvnw.cmd (100%) rename {spring-boot-ci-cd => spring-boot-modules/spring-boot-ci-cd}/pom.xml (98%) rename {spring-boot-ci-cd => spring-boot-modules/spring-boot-ci-cd}/src/main/java/com/baeldung/cicd/CiCdApplication.java (100%) rename {spring-boot-ci-cd => spring-boot-modules/spring-boot-ci-cd}/src/main/resources/introduction-config.yml (100%) rename {spring-boot-ci-cd => spring-boot-modules/spring-boot-ci-cd}/src/test/java/com/baeldung/cicd/CiCdApplicationIntegrationTest.java (100%) diff --git a/pom.xml b/pom.xml index 9cf1aa2e92..15331d8c95 100644 --- a/pom.xml +++ b/pom.xml @@ -638,7 +638,6 @@ spring-batch spring-bom - spring-boot-ci-cd spring-boot-modules spring-boot-rest @@ -1142,7 +1141,6 @@ spring-batch spring-bom - spring-boot-ci-cd spring-boot-modules spring-boot-rest diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 228e7ce481..5acaa30328 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -28,6 +28,7 @@ spring-boot-deployment spring-boot-di spring-boot-camel + spring-boot-ci-cd spring-boot-custom-starter spring-boot-crud diff --git a/spring-boot-ci-cd/.mvn/wrapper/MavenWrapperDownloader.java b/spring-boot-modules/spring-boot-ci-cd/.mvn/wrapper/MavenWrapperDownloader.java similarity index 100% rename from spring-boot-ci-cd/.mvn/wrapper/MavenWrapperDownloader.java rename to spring-boot-modules/spring-boot-ci-cd/.mvn/wrapper/MavenWrapperDownloader.java diff --git a/spring-boot-ci-cd/.mvn/wrapper/maven-wrapper.properties b/spring-boot-modules/spring-boot-ci-cd/.mvn/wrapper/maven-wrapper.properties similarity index 100% rename from spring-boot-ci-cd/.mvn/wrapper/maven-wrapper.properties rename to spring-boot-modules/spring-boot-ci-cd/.mvn/wrapper/maven-wrapper.properties diff --git a/spring-boot-ci-cd/.travis.yml b/spring-boot-modules/spring-boot-ci-cd/.travis.yml similarity index 100% rename from spring-boot-ci-cd/.travis.yml rename to spring-boot-modules/spring-boot-ci-cd/.travis.yml diff --git a/spring-boot-ci-cd/README.md b/spring-boot-modules/spring-boot-ci-cd/README.md similarity index 100% rename from spring-boot-ci-cd/README.md rename to spring-boot-modules/spring-boot-ci-cd/README.md diff --git a/spring-boot-ci-cd/mvnw b/spring-boot-modules/spring-boot-ci-cd/mvnw similarity index 100% rename from spring-boot-ci-cd/mvnw rename to spring-boot-modules/spring-boot-ci-cd/mvnw diff --git a/spring-boot-ci-cd/mvnw.cmd b/spring-boot-modules/spring-boot-ci-cd/mvnw.cmd similarity index 100% rename from spring-boot-ci-cd/mvnw.cmd rename to spring-boot-modules/spring-boot-ci-cd/mvnw.cmd diff --git a/spring-boot-ci-cd/pom.xml b/spring-boot-modules/spring-boot-ci-cd/pom.xml similarity index 98% rename from spring-boot-ci-cd/pom.xml rename to spring-boot-modules/spring-boot-ci-cd/pom.xml index e5204d53fd..25e45d56f3 100644 --- a/spring-boot-ci-cd/pom.xml +++ b/spring-boot-modules/spring-boot-ci-cd/pom.xml @@ -12,7 +12,7 @@ com.baeldung parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2 + ../../parent-boot-2 diff --git a/spring-boot-ci-cd/src/main/java/com/baeldung/cicd/CiCdApplication.java b/spring-boot-modules/spring-boot-ci-cd/src/main/java/com/baeldung/cicd/CiCdApplication.java similarity index 100% rename from spring-boot-ci-cd/src/main/java/com/baeldung/cicd/CiCdApplication.java rename to spring-boot-modules/spring-boot-ci-cd/src/main/java/com/baeldung/cicd/CiCdApplication.java diff --git a/spring-boot-ci-cd/src/main/resources/introduction-config.yml b/spring-boot-modules/spring-boot-ci-cd/src/main/resources/introduction-config.yml similarity index 100% rename from spring-boot-ci-cd/src/main/resources/introduction-config.yml rename to spring-boot-modules/spring-boot-ci-cd/src/main/resources/introduction-config.yml diff --git a/spring-boot-ci-cd/src/test/java/com/baeldung/cicd/CiCdApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-ci-cd/src/test/java/com/baeldung/cicd/CiCdApplicationIntegrationTest.java similarity index 100% rename from spring-boot-ci-cd/src/test/java/com/baeldung/cicd/CiCdApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot-ci-cd/src/test/java/com/baeldung/cicd/CiCdApplicationIntegrationTest.java From d44a7f3d1c02f30cf4b375d28a6840584d3c99a1 Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Sun, 17 May 2020 08:46:23 -0400 Subject: [PATCH 104/150] Rename to hibernate-libraries --- .../.mvn/wrapper/MavenWrapperDownloader.java | 117 +++++++ .../.mvn/wrapper/maven-wrapper.properties | 2 + .../docker-compose.yml | 0 .../docker-entrypoint-initdb.d/init-db.sql | 0 .../docker/etc/mysql/conf.d/utf8.cnf | 0 persistence-modules/hibernate-libraries/mvnw | 310 ++++++++++++++++++ .../hibernate-libraries/mvnw.cmd | 182 ++++++++++ .../pom.xml | 0 .../com/baeldung/hibernate/types/Album.java | 0 .../hibernate/types/AlbumRepository.java | 0 .../com/baeldung/hibernate/types/Artist.java | 0 .../baeldung/hibernate/types/BaseEntity.java | 0 .../baeldung/hibernate/types/CoverArt.java | 0 .../types/HibernateTypesApplication.java | 0 .../com/baeldung/hibernate/types/Song.java | 0 .../hibernate/types/SongRepository.java | 0 .../src/main/resources/application.properties | 0 .../main/resources/hibernate-types.properties | 0 .../types/HibernateTypesIntegrationTest.java | 0 .../hibernate-types/.gitignore | 33 -- persistence-modules/hibernate-types/README.md | 7 - 21 files changed, 611 insertions(+), 40 deletions(-) create mode 100644 persistence-modules/hibernate-libraries/.mvn/wrapper/MavenWrapperDownloader.java create mode 100644 persistence-modules/hibernate-libraries/.mvn/wrapper/maven-wrapper.properties rename persistence-modules/{hibernate-types => hibernate-libraries}/docker-compose.yml (100%) rename persistence-modules/{hibernate-types => hibernate-libraries}/docker/docker-entrypoint-initdb.d/init-db.sql (100%) rename persistence-modules/{hibernate-types => hibernate-libraries}/docker/etc/mysql/conf.d/utf8.cnf (100%) create mode 100755 persistence-modules/hibernate-libraries/mvnw create mode 100644 persistence-modules/hibernate-libraries/mvnw.cmd rename persistence-modules/{hibernate-types => hibernate-libraries}/pom.xml (100%) rename persistence-modules/{hibernate-types => hibernate-libraries}/src/main/java/com/baeldung/hibernate/types/Album.java (100%) rename persistence-modules/{hibernate-types => hibernate-libraries}/src/main/java/com/baeldung/hibernate/types/AlbumRepository.java (100%) rename persistence-modules/{hibernate-types => hibernate-libraries}/src/main/java/com/baeldung/hibernate/types/Artist.java (100%) rename persistence-modules/{hibernate-types => hibernate-libraries}/src/main/java/com/baeldung/hibernate/types/BaseEntity.java (100%) rename persistence-modules/{hibernate-types => hibernate-libraries}/src/main/java/com/baeldung/hibernate/types/CoverArt.java (100%) rename persistence-modules/{hibernate-types => hibernate-libraries}/src/main/java/com/baeldung/hibernate/types/HibernateTypesApplication.java (100%) rename persistence-modules/{hibernate-types => hibernate-libraries}/src/main/java/com/baeldung/hibernate/types/Song.java (100%) rename persistence-modules/{hibernate-types => hibernate-libraries}/src/main/java/com/baeldung/hibernate/types/SongRepository.java (100%) rename persistence-modules/{hibernate-types => hibernate-libraries}/src/main/resources/application.properties (100%) rename persistence-modules/{hibernate-types => hibernate-libraries}/src/main/resources/hibernate-types.properties (100%) rename persistence-modules/{hibernate-types => hibernate-libraries}/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java (100%) delete mode 100644 persistence-modules/hibernate-types/.gitignore delete mode 100644 persistence-modules/hibernate-types/README.md diff --git a/persistence-modules/hibernate-libraries/.mvn/wrapper/MavenWrapperDownloader.java b/persistence-modules/hibernate-libraries/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000000..b901097f2d --- /dev/null +++ b/persistence-modules/hibernate-libraries/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/persistence-modules/hibernate-libraries/.mvn/wrapper/maven-wrapper.properties b/persistence-modules/hibernate-libraries/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..642d572ce9 --- /dev/null +++ b/persistence-modules/hibernate-libraries/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/persistence-modules/hibernate-types/docker-compose.yml b/persistence-modules/hibernate-libraries/docker-compose.yml similarity index 100% rename from persistence-modules/hibernate-types/docker-compose.yml rename to persistence-modules/hibernate-libraries/docker-compose.yml diff --git a/persistence-modules/hibernate-types/docker/docker-entrypoint-initdb.d/init-db.sql b/persistence-modules/hibernate-libraries/docker/docker-entrypoint-initdb.d/init-db.sql similarity index 100% rename from persistence-modules/hibernate-types/docker/docker-entrypoint-initdb.d/init-db.sql rename to persistence-modules/hibernate-libraries/docker/docker-entrypoint-initdb.d/init-db.sql diff --git a/persistence-modules/hibernate-types/docker/etc/mysql/conf.d/utf8.cnf b/persistence-modules/hibernate-libraries/docker/etc/mysql/conf.d/utf8.cnf similarity index 100% rename from persistence-modules/hibernate-types/docker/etc/mysql/conf.d/utf8.cnf rename to persistence-modules/hibernate-libraries/docker/etc/mysql/conf.d/utf8.cnf diff --git a/persistence-modules/hibernate-libraries/mvnw b/persistence-modules/hibernate-libraries/mvnw new file mode 100755 index 0000000000..41c0f0c23d --- /dev/null +++ b/persistence-modules/hibernate-libraries/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/persistence-modules/hibernate-libraries/mvnw.cmd b/persistence-modules/hibernate-libraries/mvnw.cmd new file mode 100644 index 0000000000..86115719e5 --- /dev/null +++ b/persistence-modules/hibernate-libraries/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/persistence-modules/hibernate-types/pom.xml b/persistence-modules/hibernate-libraries/pom.xml similarity index 100% rename from persistence-modules/hibernate-types/pom.xml rename to persistence-modules/hibernate-libraries/pom.xml diff --git a/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/Album.java b/persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/Album.java similarity index 100% rename from persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/Album.java rename to persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/Album.java diff --git a/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/AlbumRepository.java b/persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/AlbumRepository.java similarity index 100% rename from persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/AlbumRepository.java rename to persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/AlbumRepository.java diff --git a/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/Artist.java b/persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/Artist.java similarity index 100% rename from persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/Artist.java rename to persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/Artist.java diff --git a/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/BaseEntity.java b/persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/BaseEntity.java similarity index 100% rename from persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/BaseEntity.java rename to persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/BaseEntity.java diff --git a/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/CoverArt.java b/persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/CoverArt.java similarity index 100% rename from persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/CoverArt.java rename to persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/CoverArt.java diff --git a/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/HibernateTypesApplication.java b/persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/HibernateTypesApplication.java similarity index 100% rename from persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/HibernateTypesApplication.java rename to persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/HibernateTypesApplication.java diff --git a/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/Song.java b/persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/Song.java similarity index 100% rename from persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/Song.java rename to persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/Song.java diff --git a/persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/SongRepository.java b/persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/SongRepository.java similarity index 100% rename from persistence-modules/hibernate-types/src/main/java/com/baeldung/hibernate/types/SongRepository.java rename to persistence-modules/hibernate-libraries/src/main/java/com/baeldung/hibernate/types/SongRepository.java diff --git a/persistence-modules/hibernate-types/src/main/resources/application.properties b/persistence-modules/hibernate-libraries/src/main/resources/application.properties similarity index 100% rename from persistence-modules/hibernate-types/src/main/resources/application.properties rename to persistence-modules/hibernate-libraries/src/main/resources/application.properties diff --git a/persistence-modules/hibernate-types/src/main/resources/hibernate-types.properties b/persistence-modules/hibernate-libraries/src/main/resources/hibernate-types.properties similarity index 100% rename from persistence-modules/hibernate-types/src/main/resources/hibernate-types.properties rename to persistence-modules/hibernate-libraries/src/main/resources/hibernate-types.properties diff --git a/persistence-modules/hibernate-types/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java b/persistence-modules/hibernate-libraries/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java similarity index 100% rename from persistence-modules/hibernate-types/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java rename to persistence-modules/hibernate-libraries/src/test/java/com/baeldung/hibernate/types/HibernateTypesIntegrationTest.java diff --git a/persistence-modules/hibernate-types/.gitignore b/persistence-modules/hibernate-types/.gitignore deleted file mode 100644 index 94b9c48616..0000000000 --- a/persistence-modules/hibernate-types/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -.classpath -.project -HELP.md -target/ -!.mvn/wrapper/maven-wrapper.jar -!**/src/main/** -!**/src/test/** - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -build/ - -### VS Code ### -.vscode/ diff --git a/persistence-modules/hibernate-types/README.md b/persistence-modules/hibernate-types/README.md deleted file mode 100644 index 9d02d8c8f2..0000000000 --- a/persistence-modules/hibernate-types/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Hibernate Types - -This module contains articles specific to use of Hibernate Types. - -### Relevant articles: - -- [A Guide to Hibernate Types Project](https://www.baeldung.com/a-guide-to-hibernate-types-project/) From cc2dfb4206355318e25b110920e3c2af19a62f2c Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Sun, 17 May 2020 08:52:18 -0400 Subject: [PATCH 105/150] Remove maven wrapper files --- .../.mvn/wrapper/MavenWrapperDownloader.java | 117 ------- .../.mvn/wrapper/maven-wrapper.properties | 2 - persistence-modules/hibernate-libraries/mvnw | 310 ------------------ .../hibernate-libraries/mvnw.cmd | 182 ---------- 4 files changed, 611 deletions(-) delete mode 100644 persistence-modules/hibernate-libraries/.mvn/wrapper/MavenWrapperDownloader.java delete mode 100644 persistence-modules/hibernate-libraries/.mvn/wrapper/maven-wrapper.properties delete mode 100755 persistence-modules/hibernate-libraries/mvnw delete mode 100644 persistence-modules/hibernate-libraries/mvnw.cmd diff --git a/persistence-modules/hibernate-libraries/.mvn/wrapper/MavenWrapperDownloader.java b/persistence-modules/hibernate-libraries/.mvn/wrapper/MavenWrapperDownloader.java deleted file mode 100644 index b901097f2d..0000000000 --- a/persistence-modules/hibernate-libraries/.mvn/wrapper/MavenWrapperDownloader.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2007-present the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import java.net.*; -import java.io.*; -import java.nio.channels.*; -import java.util.Properties; - -public class MavenWrapperDownloader { - - private static final String WRAPPER_VERSION = "0.5.6"; - /** - * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. - */ - private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" - + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; - - /** - * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to - * use instead of the default one. - */ - private static final String MAVEN_WRAPPER_PROPERTIES_PATH = - ".mvn/wrapper/maven-wrapper.properties"; - - /** - * Path where the maven-wrapper.jar will be saved to. - */ - private static final String MAVEN_WRAPPER_JAR_PATH = - ".mvn/wrapper/maven-wrapper.jar"; - - /** - * Name of the property which should be used to override the default download url for the wrapper. - */ - private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; - - public static void main(String args[]) { - System.out.println("- Downloader started"); - File baseDirectory = new File(args[0]); - System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); - - // If the maven-wrapper.properties exists, read it and check if it contains a custom - // wrapperUrl parameter. - File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); - String url = DEFAULT_DOWNLOAD_URL; - if(mavenWrapperPropertyFile.exists()) { - FileInputStream mavenWrapperPropertyFileInputStream = null; - try { - mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); - Properties mavenWrapperProperties = new Properties(); - mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); - url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); - } catch (IOException e) { - System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); - } finally { - try { - if(mavenWrapperPropertyFileInputStream != null) { - mavenWrapperPropertyFileInputStream.close(); - } - } catch (IOException e) { - // Ignore ... - } - } - } - System.out.println("- Downloading from: " + url); - - File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); - if(!outputFile.getParentFile().exists()) { - if(!outputFile.getParentFile().mkdirs()) { - System.out.println( - "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); - } - } - System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); - try { - downloadFileFromURL(url, outputFile); - System.out.println("Done"); - System.exit(0); - } catch (Throwable e) { - System.out.println("- Error downloading"); - e.printStackTrace(); - System.exit(1); - } - } - - private static void downloadFileFromURL(String urlString, File destination) throws Exception { - if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { - String username = System.getenv("MVNW_USERNAME"); - char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } - }); - } - URL website = new URL(urlString); - ReadableByteChannel rbc; - rbc = Channels.newChannel(website.openStream()); - FileOutputStream fos = new FileOutputStream(destination); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - fos.close(); - rbc.close(); - } - -} diff --git a/persistence-modules/hibernate-libraries/.mvn/wrapper/maven-wrapper.properties b/persistence-modules/hibernate-libraries/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index 642d572ce9..0000000000 --- a/persistence-modules/hibernate-libraries/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,2 +0,0 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/persistence-modules/hibernate-libraries/mvnw b/persistence-modules/hibernate-libraries/mvnw deleted file mode 100755 index 41c0f0c23d..0000000000 --- a/persistence-modules/hibernate-libraries/mvnw +++ /dev/null @@ -1,310 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi -else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - else - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` - fi - - if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" - else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" - fi - elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f - else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f - fi - - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaClass=`cygpath --path --windows "$javaClass"` - fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi -fi -########################################################################################## -# End of extension -########################################################################################## - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/persistence-modules/hibernate-libraries/mvnw.cmd b/persistence-modules/hibernate-libraries/mvnw.cmd deleted file mode 100644 index 86115719e5..0000000000 --- a/persistence-modules/hibernate-libraries/mvnw.cmd +++ /dev/null @@ -1,182 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - -FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% From 8fd2a5ee8dd72f5e6f026f44f0b6b2e0d64e0006 Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Sun, 17 May 2020 09:10:36 -0400 Subject: [PATCH 106/150] Create create-database.sh --- .../hibernate-libraries/create-database.sh | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 persistence-modules/hibernate-libraries/create-database.sh diff --git a/persistence-modules/hibernate-libraries/create-database.sh b/persistence-modules/hibernate-libraries/create-database.sh new file mode 100644 index 0000000000..aa363b582e --- /dev/null +++ b/persistence-modules/hibernate-libraries/create-database.sh @@ -0,0 +1,8 @@ +#!/bin/bash +docker run \ + -p 53306:3306 \ + --name=mysql57-hibernate-types \ + -e MYSQL_ALLOW_EMPTY_PASSWORD=true \ + -v ${PWD}/docker/etc/mysql/conf.d:/etc/mysql/conf.d \ + -v ${PWD}/docker/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d \ + -d mysql:5.7 From 2819b53e15e4591b3bcd399e95c45b5bd84bf2da Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Sun, 17 May 2020 09:12:52 -0400 Subject: [PATCH 107/150] Make shell script executable --- persistence-modules/hibernate-libraries/create-database.sh | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 persistence-modules/hibernate-libraries/create-database.sh diff --git a/persistence-modules/hibernate-libraries/create-database.sh b/persistence-modules/hibernate-libraries/create-database.sh old mode 100644 new mode 100755 From aa9ee72e9e0b1eef0689b1a58cc848e415af1f43 Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Sun, 17 May 2020 09:49:42 -0400 Subject: [PATCH 108/150] Update create-database.sh --- persistence-modules/hibernate-libraries/create-database.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/persistence-modules/hibernate-libraries/create-database.sh b/persistence-modules/hibernate-libraries/create-database.sh index aa363b582e..fec49cd5db 100755 --- a/persistence-modules/hibernate-libraries/create-database.sh +++ b/persistence-modules/hibernate-libraries/create-database.sh @@ -3,6 +3,6 @@ docker run \ -p 53306:3306 \ --name=mysql57-hibernate-types \ -e MYSQL_ALLOW_EMPTY_PASSWORD=true \ - -v ${PWD}/docker/etc/mysql/conf.d:/etc/mysql/conf.d \ - -v ${PWD}/docker/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d \ + -v "${PWD}/docker/etc/mysql/conf.d":/etc/mysql/conf.d \ + -v "${PWD}/docker/docker-entrypoint-initdb.d":/docker-entrypoint-initdb.d \ -d mysql:5.7 From 8a30bb544c9436ec859a0697e232c1a4d8974031 Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Sun, 17 May 2020 09:50:24 -0400 Subject: [PATCH 109/150] Update pom.xml --- persistence-modules/hibernate-libraries/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/hibernate-libraries/pom.xml b/persistence-modules/hibernate-libraries/pom.xml index 4d686c72a5..418437eb8b 100644 --- a/persistence-modules/hibernate-libraries/pom.xml +++ b/persistence-modules/hibernate-libraries/pom.xml @@ -2,7 +2,7 @@ 4.0.0 - hibernate-types + hibernate-libraries 0.0.1-SNAPSHOT hibernate-types Introduction into hibernate types library From 488989e3de23df21f0050e0f46e4b5d64e8f49e0 Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Sun, 17 May 2020 09:59:02 -0400 Subject: [PATCH 110/150] Update pom.xml --- persistence-modules/hibernate-libraries/pom.xml | 6 +++--- persistence-modules/pom.xml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/persistence-modules/hibernate-libraries/pom.xml b/persistence-modules/hibernate-libraries/pom.xml index 4d686c72a5..0b6b5546aa 100644 --- a/persistence-modules/hibernate-libraries/pom.xml +++ b/persistence-modules/hibernate-libraries/pom.xml @@ -4,7 +4,7 @@ 4.0.0 hibernate-types 0.0.1-SNAPSHOT - hibernate-types + hibernate-libraries Introduction into hibernate types library @@ -142,8 +142,8 @@ maven-compiler-plugin ${maven.version} - ${source.version} - ${target.version} + 1.8 + 1.8 diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 4d39b2d98b..3e2c2e6a0f 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -24,7 +24,7 @@ hibernate-mapping hibernate-ogm hibernate-annotations - hibernate-types + hibernate-libraries hibernate-jpa hibernate-queries hibernate-enterprise From ade74299c8d1d4eaca1807a3e08830df6abce132 Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Sun, 17 May 2020 10:11:56 -0400 Subject: [PATCH 111/150] Remove build plugins --- .../hibernate-libraries/pom.xml | 26 ------------------- 1 file changed, 26 deletions(-) diff --git a/persistence-modules/hibernate-libraries/pom.xml b/persistence-modules/hibernate-libraries/pom.xml index 0e99b0d904..ea2dda7e88 100644 --- a/persistence-modules/hibernate-libraries/pom.xml +++ b/persistence-modules/hibernate-libraries/pom.xml @@ -132,32 +132,6 @@ true - - - org.apache.maven.plugins - maven-war-plugin - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven.version} - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-surefire-plugin - - 3 - true - - **/*IntegrationTest.java - - - - From aca989958fb2143df787a11b0770b5a04dccba10 Mon Sep 17 00:00:00 2001 From: andrebrowne <42154231+andrebrowne@users.noreply.github.com> Date: Sun, 17 May 2020 10:17:12 -0400 Subject: [PATCH 112/150] Remove utf8.cnf --- persistence-modules/hibernate-libraries/create-database.sh | 1 - .../hibernate-libraries/docker/etc/mysql/conf.d/utf8.cnf | 7 ------- 2 files changed, 8 deletions(-) delete mode 100644 persistence-modules/hibernate-libraries/docker/etc/mysql/conf.d/utf8.cnf diff --git a/persistence-modules/hibernate-libraries/create-database.sh b/persistence-modules/hibernate-libraries/create-database.sh index fec49cd5db..da55dc917d 100755 --- a/persistence-modules/hibernate-libraries/create-database.sh +++ b/persistence-modules/hibernate-libraries/create-database.sh @@ -3,6 +3,5 @@ docker run \ -p 53306:3306 \ --name=mysql57-hibernate-types \ -e MYSQL_ALLOW_EMPTY_PASSWORD=true \ - -v "${PWD}/docker/etc/mysql/conf.d":/etc/mysql/conf.d \ -v "${PWD}/docker/docker-entrypoint-initdb.d":/docker-entrypoint-initdb.d \ -d mysql:5.7 diff --git a/persistence-modules/hibernate-libraries/docker/etc/mysql/conf.d/utf8.cnf b/persistence-modules/hibernate-libraries/docker/etc/mysql/conf.d/utf8.cnf deleted file mode 100644 index 1885d83c8b..0000000000 --- a/persistence-modules/hibernate-libraries/docker/etc/mysql/conf.d/utf8.cnf +++ /dev/null @@ -1,7 +0,0 @@ -[mysqld] -init_connect='SET collation_connection = utf8_unicode_ci' -character-set-server = utf8 -collation-server = utf8_unicode_ci - -[client] -default-character-set = utf8 \ No newline at end of file From 8de92f7f4c07e3db25349590d497181dfe99bc84 Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sun, 17 May 2020 21:10:55 +0530 Subject: [PATCH 113/150] removed unwanted path from web security config --- spring-security-modules/spring-security-mvc-boot-1/pom.xml | 4 ++++ .../main/java/com/baeldung/roles/voter/VoterApplication.java | 2 +- .../main/java/com/baeldung/roles/voter/WebSecurityConfig.java | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/spring-security-modules/spring-security-mvc-boot-1/pom.xml b/spring-security-modules/spring-security-mvc-boot-1/pom.xml index 7ad18376ec..b00b7bab32 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/pom.xml +++ b/spring-security-modules/spring-security-mvc-boot-1/pom.xml @@ -106,6 +106,10 @@ ${ehcache-core.version} jar + + net.bytebuddy + byte-buddy + diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterApplication.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterApplication.java index d3e0652ae9..148f9c17b1 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterApplication.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/VoterApplication.java @@ -7,7 +7,7 @@ import org.springframework.context.annotation.Configuration; @Configuration @EnableAutoConfiguration -@ComponentScan(basePackages = {"com.baeldung.voter"}) +@ComponentScan(basePackages = {"com.baeldung.roles.voter"}) public class VoterApplication { public static void main(String[] args) { diff --git a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/WebSecurityConfig.java b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/WebSecurityConfig.java index 8a0f438b49..1a6d1b8235 100644 --- a/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/WebSecurityConfig.java +++ b/spring-security-modules/spring-security-mvc-boot-1/src/main/java/com/baeldung/roles/voter/WebSecurityConfig.java @@ -34,7 +34,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { // @formatter: off http // needed so our login could work - .csrf().disable().authorizeRequests().anyRequest().authenticated().accessDecisionManager(accessDecisionManager()).antMatchers("/").hasAnyRole("ROLE_ADMIN", "ROLE_USER").and().formLogin().permitAll().and().logout().permitAll() + .csrf().disable().authorizeRequests().anyRequest().authenticated().accessDecisionManager(accessDecisionManager()).and().formLogin().permitAll().and().logout().permitAll() .deleteCookies("JSESSIONID").logoutSuccessUrl("/login"); // @formatter: on } From c66c60bcffa4c1023636f136acf52e7a7d7bd3e4 Mon Sep 17 00:00:00 2001 From: Amy DeGregorio Date: Sun, 17 May 2020 14:17:51 -0400 Subject: [PATCH 114/150] BAEL-3462 Univosity Parsers (#9222) * BAEL-3462 CSV Univosity Example * Added a row processor example --- libraries-data-2/pom.xml | 6 + .../com/baeldung/univocity/OutputService.java | 80 +++++++++++++ .../baeldung/univocity/ParsingService.java | 85 +++++++++++++ .../com/baeldung/univocity/model/Product.java | 44 +++++++ .../univocity/ParsingServiceUnitTest.java | 112 ++++++++++++++++++ .../src/test/resources/largeProductList.csv | 36 ++++++ .../src/test/resources/productList.csv | 3 + .../src/test/resources/productList.txt | 3 + .../test/resources/productListWithHeaders.csv | 3 + .../test/resources/productListWithHeaders.txt | 2 + 10 files changed, 374 insertions(+) create mode 100644 libraries-data-2/src/main/java/com/baeldung/univocity/OutputService.java create mode 100644 libraries-data-2/src/main/java/com/baeldung/univocity/ParsingService.java create mode 100644 libraries-data-2/src/main/java/com/baeldung/univocity/model/Product.java create mode 100644 libraries-data-2/src/test/java/com/baeldung/univocity/ParsingServiceUnitTest.java create mode 100644 libraries-data-2/src/test/resources/largeProductList.csv create mode 100644 libraries-data-2/src/test/resources/productList.csv create mode 100644 libraries-data-2/src/test/resources/productList.txt create mode 100644 libraries-data-2/src/test/resources/productListWithHeaders.csv create mode 100644 libraries-data-2/src/test/resources/productListWithHeaders.txt diff --git a/libraries-data-2/pom.xml b/libraries-data-2/pom.xml index 73c5452f77..cbb24edd3f 100644 --- a/libraries-data-2/pom.xml +++ b/libraries-data-2/pom.xml @@ -116,6 +116,11 @@ slf4j-log4j12 ${slf4j.version} + + com.univocity + univocity-parsers + ${univocity.version} + org.awaitility awaitility @@ -175,6 +180,7 @@ 3.6.2 1.7.25 3.0.0 + 2.8.4 RELEASE 3.0 1.8.1 diff --git a/libraries-data-2/src/main/java/com/baeldung/univocity/OutputService.java b/libraries-data-2/src/main/java/com/baeldung/univocity/OutputService.java new file mode 100644 index 0000000000..b316a602ad --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/univocity/OutputService.java @@ -0,0 +1,80 @@ +package com.baeldung.univocity; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.univocity.model.Product; +import com.univocity.parsers.common.processor.BeanWriterProcessor; +import com.univocity.parsers.csv.CsvWriter; +import com.univocity.parsers.csv.CsvWriterSettings; +import com.univocity.parsers.fixed.FixedWidthFields; +import com.univocity.parsers.fixed.FixedWidthWriter; +import com.univocity.parsers.fixed.FixedWidthWriterSettings; +import com.univocity.parsers.tsv.TsvWriter; +import com.univocity.parsers.tsv.TsvWriterSettings; + +public class OutputService { + private Logger logger = LoggerFactory.getLogger(ParsingService.class); + + public enum OutputType { + CSV, TSV, FIXED_WIDTH + }; + + public boolean writeData(List products, OutputType outputType, String outputPath) { + try (Writer outputWriter = new OutputStreamWriter(new FileOutputStream(new File(outputPath)), "UTF-8")) { + switch (outputType) { + case CSV: { + CsvWriter writer = new CsvWriter(outputWriter, new CsvWriterSettings()); + writer.writeRowsAndClose(products); + } + break; + case TSV: { + TsvWriter writer = new TsvWriter(outputWriter, new TsvWriterSettings()); + writer.writeRowsAndClose(products); + } + break; + case FIXED_WIDTH: { + FixedWidthFields fieldLengths = new FixedWidthFields(8, 30, 10); + FixedWidthWriterSettings settings = new FixedWidthWriterSettings(fieldLengths); + FixedWidthWriter writer = new FixedWidthWriter(outputWriter, settings); + writer.writeRowsAndClose(products); + } + break; + default: + logger.warn("Invalid OutputType: " + outputType); + return false; + } + return true; + } catch (IOException e) { + logger.error(e.getMessage()); + return false; + } + } + + public boolean writeBeanToFixedWidthFile(List products, String outputPath) { + try (Writer outputWriter = new OutputStreamWriter(new FileOutputStream(new File(outputPath)), "UTF-8")) { + BeanWriterProcessor rowProcessor = new BeanWriterProcessor(Product.class); + FixedWidthFields fieldLengths = new FixedWidthFields(8, 30, 10); + FixedWidthWriterSettings settings = new FixedWidthWriterSettings(fieldLengths); + settings.setHeaders("product_no", "description", "unit_price"); + settings.setRowWriterProcessor(rowProcessor); + FixedWidthWriter writer = new FixedWidthWriter(outputWriter, settings); + writer.writeHeaders(); + for (Product product : products) { + writer.processRecord(product); + } + writer.close(); + return true; + } catch (IOException e) { + logger.error(e.getMessage()); + return false; + } + } +} diff --git a/libraries-data-2/src/main/java/com/baeldung/univocity/ParsingService.java b/libraries-data-2/src/main/java/com/baeldung/univocity/ParsingService.java new file mode 100644 index 0000000000..a88023b5d3 --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/univocity/ParsingService.java @@ -0,0 +1,85 @@ +package com.baeldung.univocity; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.univocity.model.Product; +import com.univocity.parsers.common.processor.BatchedColumnProcessor; +import com.univocity.parsers.common.processor.BeanListProcessor; +import com.univocity.parsers.csv.CsvParser; +import com.univocity.parsers.csv.CsvParserSettings; +import com.univocity.parsers.fixed.FixedWidthFields; +import com.univocity.parsers.fixed.FixedWidthParser; +import com.univocity.parsers.fixed.FixedWidthParserSettings; + +public class ParsingService { + private Logger logger = LoggerFactory.getLogger(ParsingService.class); + + public List parseCsvFile(String relativePath) { + try (Reader inputReader = new InputStreamReader(new FileInputStream(new File(relativePath)), "UTF-8")) { + CsvParserSettings settings = new CsvParserSettings(); + settings.setMaxCharsPerColumn(100); + settings.setMaxColumns(50); + CsvParser parser = new CsvParser(settings); + List parsedRows = parser.parseAll(inputReader); + return parsedRows; + } catch (IOException e) { + logger.error("IOException opening file: " + relativePath + " " + e.getMessage()); + return new ArrayList(); + } + } + + public List parseFixedWidthFile(String relativePath) { + try (Reader inputReader = new InputStreamReader(new FileInputStream(new File(relativePath)), "UTF-8")) { + FixedWidthFields fieldLengths = new FixedWidthFields(8, 30, 10); + FixedWidthParserSettings settings = new FixedWidthParserSettings(fieldLengths); + + FixedWidthParser parser = new FixedWidthParser(settings); + List parsedRows = parser.parseAll(inputReader); + return parsedRows; + } catch (IOException e) { + logger.error("IOException opening file: " + relativePath + " " + e.getMessage()); + return new ArrayList(); + } + } + + public List parseCsvFileIntoBeans(String relativePath) { + try (Reader inputReader = new InputStreamReader(new FileInputStream(new File(relativePath)), "UTF-8")) { + BeanListProcessor rowProcessor = new BeanListProcessor(Product.class); + CsvParserSettings settings = new CsvParserSettings(); + settings.setHeaderExtractionEnabled(true); + settings.setProcessor(rowProcessor); + CsvParser parser = new CsvParser(settings); + parser.parse(inputReader); + return rowProcessor.getBeans(); + } catch (IOException e) { + logger.error("IOException opening file: " + relativePath + " " + e.getMessage()); + return new ArrayList(); + } + } + + public List parseCsvFileInBatches(String relativePath) { + try (Reader inputReader = new InputStreamReader(new FileInputStream(new File(relativePath)), "UTF-8")) { + CsvParserSettings settings = new CsvParserSettings(); + settings.setProcessor(new BatchedColumnProcessor(5) { + @Override + public void batchProcessed(int rowsInThisBatch) { + } + }); + CsvParser parser = new CsvParser(settings); + List parsedRows = parser.parseAll(inputReader); + return parsedRows; + } catch (IOException e) { + logger.error("IOException opening file: " + relativePath + " " + e.getMessage()); + return new ArrayList(); + } + } +} diff --git a/libraries-data-2/src/main/java/com/baeldung/univocity/model/Product.java b/libraries-data-2/src/main/java/com/baeldung/univocity/model/Product.java new file mode 100644 index 0000000000..dc4a28f62a --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/univocity/model/Product.java @@ -0,0 +1,44 @@ +package com.baeldung.univocity.model; + +import com.univocity.parsers.annotations.Parsed; + +public class Product { + + @Parsed(field = "product_no") + private String productNumber; + + @Parsed + private String description; + + @Parsed(field = "unit_price") + private float unitPrice; + + public String getProductNumber() { + return productNumber; + } + + public void setProductNumber(String productNumber) { + this.productNumber = productNumber; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public float getUnitPrice() { + return unitPrice; + } + + public void setUnitPrice(float unitPrice) { + this.unitPrice = unitPrice; + } + + @Override + public String toString() { + return "Product [Product Number: " + productNumber + ", Description: " + description + ", Unit Price: " + unitPrice + "]"; + } +} diff --git a/libraries-data-2/src/test/java/com/baeldung/univocity/ParsingServiceUnitTest.java b/libraries-data-2/src/test/java/com/baeldung/univocity/ParsingServiceUnitTest.java new file mode 100644 index 0000000000..8cac0bc4b8 --- /dev/null +++ b/libraries-data-2/src/test/java/com/baeldung/univocity/ParsingServiceUnitTest.java @@ -0,0 +1,112 @@ +package com.baeldung.univocity; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import com.baeldung.univocity.model.Product; + +public class ParsingServiceUnitTest { + + @Test + public void givenCsvFile_thenParsedResultsShouldBeReturned() { + ParsingService parsingService = new ParsingService(); + List productData = parsingService.parseCsvFile("src/test/resources/productList.csv"); + assertEquals(3, productData.size()); + assertEquals(3, productData.get(0).length); + assertEquals("A8993-10", productData.get(0)[0]); + assertEquals("Extra large widget", productData.get(0)[1]); + assertEquals("35.42", productData.get(0)[2]); + assertEquals("D-2938-1", productData.get(1)[0]); + assertEquals("Winding widget \"Deluxe Model\"", productData.get(1)[1]); + assertEquals("245.99", productData.get(1)[2]); + assertEquals("R3212-32", productData.get(2)[0]); + assertEquals("Standard widget", productData.get(2)[1]); + assertEquals("2.34", productData.get(2)[2]); + } + + @Test + public void givenFixedWidthFile_thenParsedResultsShouldBeReturned() { + ParsingService parsingService = new ParsingService(); + List productData = parsingService.parseFixedWidthFile("src/test/resources/productList.txt"); + // Note: any extra spaces on the end will cause a null line to be added + assertEquals(3, productData.size()); + assertEquals(3, productData.get(0).length); + assertEquals("A8993-10", productData.get(0)[0]); + assertEquals("Extra large widget", productData.get(0)[1]); + assertEquals("35.42", productData.get(0)[2]); + assertEquals("D-2938-1", productData.get(1)[0]); + assertEquals("Winding widget \"Deluxe Model\"", productData.get(1)[1]); + assertEquals("245.99", productData.get(1)[2]); + assertEquals("R3212-32", productData.get(2)[0]); + assertEquals("Standard widget", productData.get(2)[1]); + assertEquals("2.34", productData.get(2)[2]); + } + + @Test + public void givenDataAndCsvOutputType_thenCsvFileProduced() { + OutputService outputService = new OutputService(); + List productData = new ArrayList<>(); + productData.add(new Object[] { "1000-3-0", "Widget No. 96", "5.67" }); + productData.add(new Object[] { "G930-M-P", "1/4\" Wocket", ".67" }); + productData.add(new Object[] { "8080-0-M", "No. 54 Jumbo Widget", "35.74" }); + outputService.writeData(productData, OutputService.OutputType.CSV, "src/test/resources/outputProductList.csv"); + + ParsingService parsingService = new ParsingService(); + List writtenData = parsingService.parseCsvFile("src/test/resources/outputProductList.csv"); + assertEquals(3, writtenData.size()); + assertEquals(3, writtenData.get(0).length); + } + + @Test + public void givenDataAndFixedWidthOutputType_thenFixedWidthFileProduced() { + OutputService outputService = new OutputService(); + List productData = new ArrayList<>(); + productData.add(new Object[] { "1000-3-0", "Widget No. 96", "5.67" }); + productData.add(new Object[] { "G930-M-P", "1/4\" Wocket", ".67" }); + productData.add(new Object[] { "8080-0-M", "No. 54 Jumbo Widget", "35.74" }); + outputService.writeData(productData, OutputService.OutputType.FIXED_WIDTH, "src/test/resources/outputProductList.txt"); + + ParsingService parsingService = new ParsingService(); + List writtenData = parsingService.parseFixedWidthFile("src/test/resources/outputProductList.txt"); + assertEquals(3, writtenData.size()); + assertEquals(3, writtenData.get(0).length); + } + + @Test + public void givenCsvFile_thenCsvFileParsedIntoBeans() { + ParsingService parsingService = new ParsingService(); + List products = parsingService.parseCsvFileIntoBeans("src/test/resources/productListWithHeaders.csv"); + assertEquals(2, products.size()); + assertEquals("Product [Product Number: 99-378AG, Description: Wocket Widget #42, Unit Price: 3.56]", products.get(0) + .toString()); + assertEquals("Product [Product Number: TB-333-0, Description: Turbine Widget replacement kit, Unit Price: 800.99]", products.get(1) + .toString()); + } + + @Test + public void givenLisOfProduct_thenWriteFixedWidthFile() { + OutputService outputService = new OutputService(); + Product product = new Product(); + product.setProductNumber("007-PPG0"); + product.setDescription("3/8\" x 1\" Wocket"); + product.setUnitPrice(45.99f); + List products = new ArrayList<>(); + products.add(product); + outputService.writeBeanToFixedWidthFile(products, "src/test/resources/productListWithHeaders.txt"); + ParsingService parsingService = new ParsingService(); + List writtenData = parsingService.parseFixedWidthFile("src/test/resources/productListWithHeaders.txt"); + assertEquals(2, writtenData.size()); + assertEquals(3, writtenData.get(0).length); + } + + @Test + public void givenLargeCsvFile_thenParsedDataShouldBeReturned() { + ParsingService parsingService = new ParsingService(); + List productData = parsingService.parseCsvFileInBatches("src/test/resources/largeProductList.csv"); + assertEquals(36, productData.size()); + } +} diff --git a/libraries-data-2/src/test/resources/largeProductList.csv b/libraries-data-2/src/test/resources/largeProductList.csv new file mode 100644 index 0000000000..2b1813d974 --- /dev/null +++ b/libraries-data-2/src/test/resources/largeProductList.csv @@ -0,0 +1,36 @@ +A8993-10,"Extra large widget",35.42 +D-2938-1,"Winding widget ""Deluxe Model""",245.99 +R3212-32,"Standard widget",2.34 +A8993-10,"Extra large widget",35.42 +D-2938-1,"Winding widget ""Deluxe Model""",245.99 +R3212-32,"Standard widget",2.34 +A8993-10,"Extra large widget",35.42 +D-2938-1,"Winding widget ""Deluxe Model""",245.99 +R3212-32,"Standard widget",2.34 +A8993-10,"Extra large widget",35.42 +D-2938-1,"Winding widget ""Deluxe Model""",245.99 +R3212-32,"Standard widget",2.34 +A8993-10,"Extra large widget",35.42 +D-2938-1,"Winding widget ""Deluxe Model""",245.99 +R3212-32,"Standard widget",2.34 +A8993-10,"Extra large widget",35.42 +D-2938-1,"Winding widget ""Deluxe Model""",245.99 +R3212-32,"Standard widget",2.34 +A8993-10,"Extra large widget",35.42 +D-2938-1,"Winding widget ""Deluxe Model""",245.99 +R3212-32,"Standard widget",2.34 +A8993-10,"Extra large widget",35.42 +D-2938-1,"Winding widget ""Deluxe Model""",245.99 +R3212-32,"Standard widget",2.34 +A8993-10,"Extra large widget",35.42 +D-2938-1,"Winding widget ""Deluxe Model""",245.99 +R3212-32,"Standard widget",2.34 +A8993-10,"Extra large widget",35.42 +D-2938-1,"Winding widget ""Deluxe Model""",245.99 +R3212-32,"Standard widget",2.34 +A8993-10,"Extra large widget",35.42 +D-2938-1,"Winding widget ""Deluxe Model""",245.99 +R3212-32,"Standard widget",2.34 +A8993-10,"Extra large widget",35.42 +D-2938-1,"Winding widget ""Deluxe Model""",245.99 +R3212-32,"Standard widget",2.34 \ No newline at end of file diff --git a/libraries-data-2/src/test/resources/productList.csv b/libraries-data-2/src/test/resources/productList.csv new file mode 100644 index 0000000000..f3a03b6c98 --- /dev/null +++ b/libraries-data-2/src/test/resources/productList.csv @@ -0,0 +1,3 @@ +A8993-10,"Extra large widget",35.42 +D-2938-1,"Winding widget ""Deluxe Model""",245.99 +R3212-32,"Standard widget",2.34 \ No newline at end of file diff --git a/libraries-data-2/src/test/resources/productList.txt b/libraries-data-2/src/test/resources/productList.txt new file mode 100644 index 0000000000..eca4caf55a --- /dev/null +++ b/libraries-data-2/src/test/resources/productList.txt @@ -0,0 +1,3 @@ +A8993-10Extra large widget 35.42 +D-2938-1Winding widget "Deluxe Model" 245.99 +R3212-32Standard widget 2.34 \ No newline at end of file diff --git a/libraries-data-2/src/test/resources/productListWithHeaders.csv b/libraries-data-2/src/test/resources/productListWithHeaders.csv new file mode 100644 index 0000000000..6514a7f0f7 --- /dev/null +++ b/libraries-data-2/src/test/resources/productListWithHeaders.csv @@ -0,0 +1,3 @@ +product_no, description, unit_price +99-378AG,Wocket Widget #42,3.56 +TB-333-0,Turbine Widget replacement kit,800.99 \ No newline at end of file diff --git a/libraries-data-2/src/test/resources/productListWithHeaders.txt b/libraries-data-2/src/test/resources/productListWithHeaders.txt new file mode 100644 index 0000000000..0fced57aed --- /dev/null +++ b/libraries-data-2/src/test/resources/productListWithHeaders.txt @@ -0,0 +1,2 @@ +product_description unit_price +007-PPG03/8" x 1" Wocket 45.99 From 515bcf55ea8f2787c33ee8b8351374b192868208 Mon Sep 17 00:00:00 2001 From: ajay74984 <51405689+ajay74984@users.noreply.github.com> Date: Sun, 17 May 2020 20:51:59 +0200 Subject: [PATCH 115/150] OCP review comments. (#9310) * OCP change * calculator unit test * renamed variable and abstract class addition --- .../o/AbstractCalculatorOperation.java | 7 +++ .../main/java/com/baeldung/o/Addition.java | 28 ++++----- .../main/java/com/baeldung/o/Division.java | 62 +++++++++---------- .../main/java/com/baeldung/o/Subtraction.java | 28 ++++----- .../com/baeldung/o/CalculatorUnitTest.java | 10 +-- 5 files changed, 71 insertions(+), 64 deletions(-) create mode 100644 patterns/solid/src/main/java/com/baeldung/o/AbstractCalculatorOperation.java diff --git a/patterns/solid/src/main/java/com/baeldung/o/AbstractCalculatorOperation.java b/patterns/solid/src/main/java/com/baeldung/o/AbstractCalculatorOperation.java new file mode 100644 index 0000000000..798d5e2d95 --- /dev/null +++ b/patterns/solid/src/main/java/com/baeldung/o/AbstractCalculatorOperation.java @@ -0,0 +1,7 @@ +package com.baeldung.o; + +public abstract class AbstractCalculatorOperation { + + abstract void perform(); + +} diff --git a/patterns/solid/src/main/java/com/baeldung/o/Addition.java b/patterns/solid/src/main/java/com/baeldung/o/Addition.java index 6145b386d9..1ad99aad4b 100644 --- a/patterns/solid/src/main/java/com/baeldung/o/Addition.java +++ b/patterns/solid/src/main/java/com/baeldung/o/Addition.java @@ -1,29 +1,29 @@ package com.baeldung.o; public class Addition implements CalculatorOperation { - private double number1; - private double number2; + private double left; + private double right; private double result = 0.0; - public Addition(double number1, double number2) { - this.number1 = number1; - this.number2 = number2; + public Addition(double left, double right) { + this.left = left; + this.right = right; } - public double getNumber1() { - return number1; + public double getLeft() { + return left; } - public void setNumber1(double number1) { - this.number1 = number1; + public void setLeft(double left) { + this.left = left; } - public double getNumber2() { - return number2; + public double getRight() { + return right; } - public void setNumber2(double number2) { - this.number2 = number2; + public void setRight(double right) { + this.right = right; } public double getResult() { @@ -36,6 +36,6 @@ public class Addition implements CalculatorOperation { @Override public void perform() { - result = number1 + number2; + result = left + right; } } diff --git a/patterns/solid/src/main/java/com/baeldung/o/Division.java b/patterns/solid/src/main/java/com/baeldung/o/Division.java index 24ab4355c2..fbb8a1f523 100644 --- a/patterns/solid/src/main/java/com/baeldung/o/Division.java +++ b/patterns/solid/src/main/java/com/baeldung/o/Division.java @@ -1,43 +1,43 @@ package com.baeldung.o; public class Division implements CalculatorOperation { - private double number1; - private double number2; - private double result = 0.0; + private double left; + private double right; + private double result = 0.0; - public Division(double number1, double number2) { - this.number1 = number1; - this.number2 = number2; - } + public Division(double left, double right) { + this.left = left; + this.right = right; + } - public double getNumber1() { - return number1; - } + public double getLeft() { + return left; + } - public void setNumber1(double number1) { - this.number1 = number1; - } + public void setLeft(double left) { + this.left = left; + } - public double getNumber2() { - return number2; - } + public double getRight() { + return right; + } - public void setNumber2(double number2) { - this.number2 = number2; - } + public void setRight(double right) { + this.right = right; + } - public double getResult() { - return result; - } + public double getResult() { + return result; + } - public void setResult(double result) { - this.result = result; - } + public void setResult(double result) { + this.result = result; + } - @Override - public void perform() { - if (number2 != 0) { - result = number1 / number2; - } - } + @Override + public void perform() { + if (right != 0) { + result = left / right; + } + } } diff --git a/patterns/solid/src/main/java/com/baeldung/o/Subtraction.java b/patterns/solid/src/main/java/com/baeldung/o/Subtraction.java index b74e0c5f73..5827d33568 100644 --- a/patterns/solid/src/main/java/com/baeldung/o/Subtraction.java +++ b/patterns/solid/src/main/java/com/baeldung/o/Subtraction.java @@ -1,29 +1,29 @@ package com.baeldung.o; public class Subtraction implements CalculatorOperation { - private double number1; - private double number2; + private double left; + private double right; private double result = 0.0; - public Subtraction(double number1, double number2) { - this.number1 = number1; - this.number2 = number2; + public Subtraction(double left, double right) { + this.left = left; + this.right = right; } - public double getNumber1() { - return number1; + public double getLeft() { + return left; } - public void setNumber1(double number1) { - this.number1 = number1; + public void setLeft(double left) { + this.left = left; } - public double getNumber2() { - return number2; + public double getRight() { + return right; } - public void setNumber2(double number2) { - this.number2 = number2; + public void setRight(double right) { + this.right = right; } public double getResult() { @@ -36,6 +36,6 @@ public class Subtraction implements CalculatorOperation { @Override public void perform() { - result = number1 - number2; + result = left - right; } } diff --git a/patterns/solid/src/main/test/com/baeldung/o/CalculatorUnitTest.java b/patterns/solid/src/main/test/com/baeldung/o/CalculatorUnitTest.java index f372d450a7..3ae894e963 100644 --- a/patterns/solid/src/main/test/com/baeldung/o/CalculatorUnitTest.java +++ b/patterns/solid/src/main/test/com/baeldung/o/CalculatorUnitTest.java @@ -7,8 +7,8 @@ import org.junit.jupiter.api.Test; public class CalculatorUnitTest { - private static final double NUMBER_1 = 10.0; - private static final double NUMBER_2 = 20.0; + private static final double RIGHT = 10.0; + private static final double LEFT = 20.0; private static final double SUM = 30.0; private static final double SUBTRACTION_RESULT = 10.0; private static final double DIVISION_RESULT = 2.0; @@ -22,21 +22,21 @@ public class CalculatorUnitTest { @Test public void whenAddTwoNumber_returnSum() { - Addition addition = new Addition(NUMBER_1, NUMBER_2); + Addition addition = new Addition(RIGHT, LEFT); calculator.calculate(addition); assertEquals(SUM, addition.getResult(), 0.0); } @Test public void whenSutractTwoNumber_returnCorrectResult() { - Subtraction subtraction = new Subtraction(NUMBER_2, NUMBER_1); + Subtraction subtraction = new Subtraction(LEFT, RIGHT); calculator.calculate(subtraction); assertEquals(SUBTRACTION_RESULT, subtraction.getResult(), 0.0); } @Test public void whenDivideTwoNumber_returnCorrectResult() { - Division division = new Division(NUMBER_2, NUMBER_1); + Division division = new Division(LEFT, RIGHT); calculator.calculate(division); assertEquals(DIVISION_RESULT, division.getResult(), 0.0); } From 5183afbce183afd825d67d7494717251a03205e7 Mon Sep 17 00:00:00 2001 From: Kyle Doyle Date: Sun, 17 May 2020 23:45:25 -0400 Subject: [PATCH 116/150] Bael 3893 - Move module in pom --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 8f2cc8e902..81d414f540 100644 --- a/pom.xml +++ b/pom.xml @@ -370,6 +370,7 @@ asm atomix aws + aws-app-sync aws-lambda axon azure @@ -1015,7 +1016,6 @@ asm atomix aws - aws-app-sync aws-lambda axon azure From 642b12365ae3cbe6e3cccb03ddebd38935d89761 Mon Sep 17 00:00:00 2001 From: CHANDRAKANT Kumar Date: Mon, 18 May 2020 23:04:48 +0530 Subject: [PATCH 117/150] Removed blank lines from the parent pom. --- patterns/pom.xml | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/patterns/pom.xml b/patterns/pom.xml index fa46a79f5a..be8d183be0 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -5,13 +5,11 @@ patterns patterns pom - com.baeldung parent-modules 1.0.0-SNAPSHOT - design-patterns-architectural design-patterns-behavioral @@ -26,7 +24,6 @@ intercepting-filter solid - @@ -37,7 +34,6 @@ - @@ -54,9 +50,7 @@ - 9.4.0.v20161208 - - + \ No newline at end of file From 4ab92fd3fc050fdca2e6a3dd47559fee979995df Mon Sep 17 00:00:00 2001 From: Krzysztof Woyke Date: Mon, 18 May 2020 21:35:09 +0200 Subject: [PATCH 118/150] JAVA-1643: Align Spring Boot versions used in articles and in the repo --- .../spring-boot-with-starter-parent/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-boot-modules/spring-boot-parent/spring-boot-with-starter-parent/pom.xml b/spring-boot-modules/spring-boot-parent/spring-boot-with-starter-parent/pom.xml index baba410b39..331a85ec5b 100644 --- a/spring-boot-modules/spring-boot-parent/spring-boot-with-starter-parent/pom.xml +++ b/spring-boot-modules/spring-boot-parent/spring-boot-with-starter-parent/pom.xml @@ -20,7 +20,7 @@ org.springframework.boot spring-boot-starter-data-jpa - ${spring-boot.version} + ${spring-boot-starter-data-jpa.version} @@ -38,7 +38,7 @@ 1.8 - 2.1.5.RELEASE + 2.2.5.RELEASE 4.11 From 51b4218f25c139a333c0ceb8a6f9ce6d534896cd Mon Sep 17 00:00:00 2001 From: Jonathan Cook Date: Mon, 18 May 2020 23:15:04 +0200 Subject: [PATCH 119/150] BAEL-3925 - How to call Python from Java (#9312) * BAEL-3491 - Check for null before calling parse in the Double.parseDouble * BAEL-3491 - Check for null before calling parse in the Double.parseDouble - Return to indentation with spaces. * BAEL-3854 - Pattern Matching for instanceof in Java 14 * BAEL-3854 - Pattern Matching for instanceof in Java 14 - add unit test * BAEL-3868 - Fix the integrations tests in mocks * BAEL-3925 - How to call Python from Java * BAEL-3925-How to call Python from Java * BAEL-3925-How to call Python from Java Co-authored-by: Jonathan Cook --- java-python-interop/README.md | 5 ----- language-interop/README.md | 5 +++++ {java-python-interop => language-interop}/pom.xml | 8 ++++---- .../interop/python}/ScriptEngineManagerUtils.java | 2 +- .../src/main/resources/logback.xml | 0 .../interop/python}/JavaPythonInteropUnitTest.java | 2 +- .../src/test/resources/hello.py | 0 pom.xml | 4 ++-- 8 files changed, 13 insertions(+), 13 deletions(-) delete mode 100644 java-python-interop/README.md create mode 100644 language-interop/README.md rename {java-python-interop => language-interop}/pom.xml (91%) rename {java-python-interop/src/main/java/com/baeldung/python/interop => language-interop/src/main/java/com/baeldung/language/interop/python}/ScriptEngineManagerUtils.java (95%) rename {java-python-interop => language-interop}/src/main/resources/logback.xml (100%) rename {java-python-interop/src/test/java/com/baeldung/python/interop => language-interop/src/test/java/com/baeldung/language/interop/python}/JavaPythonInteropUnitTest.java (99%) rename {java-python-interop => language-interop}/src/test/resources/hello.py (100%) diff --git a/java-python-interop/README.md b/java-python-interop/README.md deleted file mode 100644 index dc9573ecde..0000000000 --- a/java-python-interop/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## Java Python Interop - -This module contains articles about Java and Python interoperability. - -### Relevant Articles: diff --git a/language-interop/README.md b/language-interop/README.md new file mode 100644 index 0000000000..a28c4a5405 --- /dev/null +++ b/language-interop/README.md @@ -0,0 +1,5 @@ +## Language Interop + +This module contains articles about Java interop with other language integrations. + +### Relevant Articles: diff --git a/java-python-interop/pom.xml b/language-interop/pom.xml similarity index 91% rename from java-python-interop/pom.xml rename to language-interop/pom.xml index 6ee5a0be3b..bdf872a076 100644 --- a/java-python-interop/pom.xml +++ b/language-interop/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 - java-python-interop + language-interop 0.0.1-SNAPSHOT - java-python-interop + language-interop com.baeldung @@ -33,7 +33,7 @@ - java-python-interop + language-interop src/main/resources @@ -52,4 +52,4 @@ 3.6.1 - \ No newline at end of file + diff --git a/java-python-interop/src/main/java/com/baeldung/python/interop/ScriptEngineManagerUtils.java b/language-interop/src/main/java/com/baeldung/language/interop/python/ScriptEngineManagerUtils.java similarity index 95% rename from java-python-interop/src/main/java/com/baeldung/python/interop/ScriptEngineManagerUtils.java rename to language-interop/src/main/java/com/baeldung/language/interop/python/ScriptEngineManagerUtils.java index 981f174c33..7bf07cf598 100644 --- a/java-python-interop/src/main/java/com/baeldung/python/interop/ScriptEngineManagerUtils.java +++ b/language-interop/src/main/java/com/baeldung/language/interop/python/ScriptEngineManagerUtils.java @@ -1,4 +1,4 @@ -package com.baeldung.python.interop; +package com.baeldung.language.interop.python; import java.util.List; diff --git a/java-python-interop/src/main/resources/logback.xml b/language-interop/src/main/resources/logback.xml similarity index 100% rename from java-python-interop/src/main/resources/logback.xml rename to language-interop/src/main/resources/logback.xml diff --git a/java-python-interop/src/test/java/com/baeldung/python/interop/JavaPythonInteropUnitTest.java b/language-interop/src/test/java/com/baeldung/language/interop/python/JavaPythonInteropUnitTest.java similarity index 99% rename from java-python-interop/src/test/java/com/baeldung/python/interop/JavaPythonInteropUnitTest.java rename to language-interop/src/test/java/com/baeldung/language/interop/python/JavaPythonInteropUnitTest.java index 5ec3a2b61f..50e7403470 100644 --- a/java-python-interop/src/test/java/com/baeldung/python/interop/JavaPythonInteropUnitTest.java +++ b/language-interop/src/test/java/com/baeldung/language/interop/python/JavaPythonInteropUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.python.interop; +package com.baeldung.language.interop.python; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.empty; diff --git a/java-python-interop/src/test/resources/hello.py b/language-interop/src/test/resources/hello.py similarity index 100% rename from java-python-interop/src/test/resources/hello.py rename to language-interop/src/test/resources/hello.py diff --git a/pom.xml b/pom.xml index 1efce8457b..2efea40c91 100644 --- a/pom.xml +++ b/pom.xml @@ -463,7 +463,6 @@ java-numbers java-numbers-2 java-numbers-3 - java-python-interop java-rmi java-spi java-vavr-stream @@ -497,7 +496,8 @@ kotlin-quasar - libraries-2 + language-interop + libraries-2 libraries-3 libraries-apache-commons libraries-apache-commons-collections From 93809a3441102cb0f5803a5dbd2eeed65b6dfa11 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Tue, 19 May 2020 08:17:45 +0200 Subject: [PATCH 120/150] update package name --- .../SeleniumJavaScriptClickTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/{junit => clickusingjavascript}/SeleniumJavaScriptClickTest.java (97%) diff --git a/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumJavaScriptClickTest.java b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/clickusingjavascript/SeleniumJavaScriptClickTest.java similarity index 97% rename from testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumJavaScriptClickTest.java rename to testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/clickusingjavascript/SeleniumJavaScriptClickTest.java index e738454ea7..6d2ab8ef1f 100644 --- a/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/SeleniumJavaScriptClickTest.java +++ b/testing-modules/selenium-junit-testng/src/test/java/com/baeldung/selenium/clickusingjavascript/SeleniumJavaScriptClickTest.java @@ -1,4 +1,4 @@ -package java.com.baeldung.selenium.junit; +package java.com.baeldung.selenium.clickusingjavascript; import org.junit.After; import org.junit.Before; From 24fe7f5fe413e0e56e113852bfc8ffbc9e5e88dd Mon Sep 17 00:00:00 2001 From: CHANDRAKANT Kumar Date: Tue, 19 May 2020 16:56:21 +0530 Subject: [PATCH 121/150] Incorporated review comments from the editor. --- .../com/baeldung/patterns/cqrs/aggregates/UserAggregate.java | 2 +- .../com/baeldung/patterns/cqrs/commands/CreateUserCommand.java | 2 +- .../com/baeldung/patterns/escqrs/aggregates/UserAggregate.java | 2 +- patterns/pom.xml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/aggregates/UserAggregate.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/aggregates/UserAggregate.java index b5e16cff0e..96476dc15a 100644 --- a/patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/aggregates/UserAggregate.java +++ b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/aggregates/UserAggregate.java @@ -14,7 +14,7 @@ public class UserAggregate { } public User handleCreateUserCommand(CreateUserCommand command) { - User user = new User(command.getUserId(), command.getFiratName(), command.getLastName()); + User user = new User(command.getUserId(), command.getFirstName(), command.getLastName()); writeRepository.addUser(user.getUserid(), user); return user; } diff --git a/patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/commands/CreateUserCommand.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/commands/CreateUserCommand.java index 4ab939dbab..362804c610 100644 --- a/patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/commands/CreateUserCommand.java +++ b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/cqrs/commands/CreateUserCommand.java @@ -8,7 +8,7 @@ import lombok.Data; public class CreateUserCommand { private String userId; - private String firatName; + private String firstName; private String lastName; } diff --git a/patterns/cqrs-es/src/main/java/com/baeldung/patterns/escqrs/aggregates/UserAggregate.java b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/escqrs/aggregates/UserAggregate.java index 7d32aeb2a2..04bfeb634d 100644 --- a/patterns/cqrs-es/src/main/java/com/baeldung/patterns/escqrs/aggregates/UserAggregate.java +++ b/patterns/cqrs-es/src/main/java/com/baeldung/patterns/escqrs/aggregates/UserAggregate.java @@ -28,7 +28,7 @@ public class UserAggregate { } public List handleCreateUserCommand(CreateUserCommand command) { - UserCreatedEvent event = new UserCreatedEvent(command.getUserId(), command.getFiratName(), command.getLastName()); + UserCreatedEvent event = new UserCreatedEvent(command.getUserId(), command.getFirstName(), command.getLastName()); writeRepository.addEvent(command.getUserId(), event); return Arrays.asList(event); } diff --git a/patterns/pom.xml b/patterns/pom.xml index be8d183be0..e1753aba56 100644 --- a/patterns/pom.xml +++ b/patterns/pom.xml @@ -19,7 +19,7 @@ design-patterns-functional design-patterns-structural dip - cqrs-es + cqrs-es front-controller intercepting-filter solid From 73762873f6def0fc720e3e8abf59a30d9e196cd7 Mon Sep 17 00:00:00 2001 From: Somnath Musib <7885767+musibs@users.noreply.github.com> Date: Wed, 20 May 2020 02:48:58 +1000 Subject: [PATCH 122/150] BAEL-4033 LinkedBlockingQueue vs ConcurrentLinkedQueue (#9281) * BAEL-4033 Added unit test cases for LinkedBlockingQueue and ConcurrentLinkedQueue * BAEL-4033 Updated unit test class names due to PMD rule violations * Moved files to another module based on the editor review --- .../pom.xml | 9 ++- .../queue/TestConcurrentLinkedQueue.java | 66 +++++++++++++++ .../queue/TestLinkedBlockingQueue.java | 81 +++++++++++++++++++ 3 files changed, 155 insertions(+), 1 deletion(-) create mode 100644 core-java-modules/core-java-concurrency-collections-2/src/test/java/com/baeldung/concurrent/queue/TestConcurrentLinkedQueue.java create mode 100644 core-java-modules/core-java-concurrency-collections-2/src/test/java/com/baeldung/concurrent/queue/TestLinkedBlockingQueue.java diff --git a/core-java-modules/core-java-concurrency-collections-2/pom.xml b/core-java-modules/core-java-concurrency-collections-2/pom.xml index 65a91c9a9c..7fdd348dc5 100644 --- a/core-java-modules/core-java-concurrency-collections-2/pom.xml +++ b/core-java-modules/core-java-concurrency-collections-2/pom.xml @@ -23,7 +23,12 @@ jmh-generator-annprocess ${jmh.version} - + + org.assertj + assertj-core + ${assertj.version} + test + src @@ -42,6 +47,8 @@ 1.21 28.2-jre + + 3.6.1 \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-collections-2/src/test/java/com/baeldung/concurrent/queue/TestConcurrentLinkedQueue.java b/core-java-modules/core-java-concurrency-collections-2/src/test/java/com/baeldung/concurrent/queue/TestConcurrentLinkedQueue.java new file mode 100644 index 0000000000..c61becc366 --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/src/test/java/com/baeldung/concurrent/queue/TestConcurrentLinkedQueue.java @@ -0,0 +1,66 @@ +package com.baeldung.concurrent.queue; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; + +import java.util.Arrays; +import java.util.Collection; +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import org.junit.FixMethodOrder; +import org.junit.Test; + +@FixMethodOrder +public class TestConcurrentLinkedQueue { + + @Test + public void givenThereIsExistingCollection_WhenAddedIntoQueue_ThenShouldContainElements() { + Collection elements = Arrays.asList(1, 2, 3, 4, 5); + ConcurrentLinkedQueue concurrentLinkedQueue = new ConcurrentLinkedQueue<>(elements); + assertThat(concurrentLinkedQueue).containsExactly(1, 2, 3, 4, 5); + } + + @Test + public void givenQueueIsEmpty_WhenAccessingTheQueue_ThenQueueReturnsNull() throws InterruptedException { + ExecutorService executorService = Executors.newFixedThreadPool(1); + ConcurrentLinkedQueue concurrentLinkedQueue = new ConcurrentLinkedQueue<>(); + executorService.submit(() -> assertNull("Retrieve object is null", concurrentLinkedQueue.poll())); + TimeUnit.SECONDS.sleep(1); + executorService.awaitTermination(1, TimeUnit.SECONDS); + executorService.shutdown(); + } + + @Test + public void givenProducerOffersElementInQueue_WhenConsumerPollsQueue_ThenItRetrievesElement() throws Exception { + int element = 1; + + ExecutorService executorService = Executors.newFixedThreadPool(2); + ConcurrentLinkedQueue concurrentLinkedQueue = new ConcurrentLinkedQueue<>(); + Runnable offerTask = () -> concurrentLinkedQueue.offer(element); + + Callable pollTask = () -> { + while (concurrentLinkedQueue.peek() != null) { + return concurrentLinkedQueue.poll() + .intValue(); + } + return null; + }; + + executorService.submit(offerTask); + TimeUnit.SECONDS.sleep(1); + + Future returnedElement = executorService.submit(pollTask); + assertThat(returnedElement.get() + .intValue(), is(equalTo(element))); + executorService.awaitTermination(1, TimeUnit.SECONDS); + executorService.shutdown(); + } +} diff --git a/core-java-modules/core-java-concurrency-collections-2/src/test/java/com/baeldung/concurrent/queue/TestLinkedBlockingQueue.java b/core-java-modules/core-java-concurrency-collections-2/src/test/java/com/baeldung/concurrent/queue/TestLinkedBlockingQueue.java new file mode 100644 index 0000000000..7a78bc7b3b --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/src/test/java/com/baeldung/concurrent/queue/TestLinkedBlockingQueue.java @@ -0,0 +1,81 @@ +package com.baeldung.concurrent.queue; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.Arrays; +import java.util.Collection; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +import org.junit.FixMethodOrder; +import org.junit.Test; + +@FixMethodOrder +public class TestLinkedBlockingQueue { + + @Test + public void givenThereIsExistingCollection_WhenAddedIntoQueue_ThenShouldContainElements() { + Collection elements = Arrays.asList(1, 2, 3, 4, 5); + LinkedBlockingQueue linkedBlockingQueue = new LinkedBlockingQueue<>(elements); + assertThat(linkedBlockingQueue).containsExactly(1, 2, 3, 4, 5); + } + + @Test + public void givenQueueIsEmpty_WhenAccessingTheQueue_ThenThreadBlocks() throws InterruptedException { + ExecutorService executorService = Executors.newFixedThreadPool(1); + LinkedBlockingQueue linkedBlockingQueue = new LinkedBlockingQueue<>(); + executorService.submit(() -> { + try { + linkedBlockingQueue.take(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + TimeUnit.SECONDS.sleep(1); + executorService.awaitTermination(1, TimeUnit.SECONDS); + executorService.shutdown(); + } + + @Test + public void givenProducerPutsElementInQueue_WhenConsumerAccessQueue_ThenItRetrieve() { + int element = 10; + ExecutorService executorService = Executors.newFixedThreadPool(2); + LinkedBlockingQueue linkedBlockingQueue = new LinkedBlockingQueue<>(); + Runnable putTask = () -> { + try { + linkedBlockingQueue.put(element); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }; + + Callable takeTask = () -> { + try { + return linkedBlockingQueue.take(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return null; + }; + + executorService.submit(putTask); + Future returnElement = executorService.submit(takeTask); + try { + TimeUnit.SECONDS.sleep(1); + assertThat(returnElement.get() + .intValue(), is(equalTo(element))); + executorService.awaitTermination(1, TimeUnit.SECONDS); + } catch (Exception e) { + e.printStackTrace(); + } + + executorService.shutdown(); + } +} From 7bc07fdac96a914f3edad82fd8881420db77e24c Mon Sep 17 00:00:00 2001 From: kwoyke Date: Tue, 19 May 2020 21:59:55 +0200 Subject: [PATCH 123/150] BAEL-4069: Add example of using @Value with constructor/setter (#9318) --- .../baeldung/value/CollectionProvider.java | 27 +++++++++++++++++++ .../com/baeldung/value/PriorityProvider.java | 22 +++++++++++++++ .../src/main/resources/values.properties | 2 +- .../CollectionProviderIntegrationTest.java | 22 +++++++++++++++ .../PriorityProviderIntegrationTest.java | 22 +++++++++++++++ 5 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/CollectionProvider.java create mode 100644 spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/PriorityProvider.java create mode 100644 spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/CollectionProviderIntegrationTest.java create mode 100644 spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/PriorityProviderIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/CollectionProvider.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/CollectionProvider.java new file mode 100644 index 0000000000..fdc1f8ee03 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/CollectionProvider.java @@ -0,0 +1,27 @@ +package com.baeldung.value; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +@Component +@PropertySource("classpath:values.properties") +public class CollectionProvider { + + private final List values = new ArrayList<>(); + + public Collection getValues() { + return Collections.unmodifiableCollection(values); + } + + @Autowired + public void setValues(@Value("#{'${listOfValues}'.split(',')}") List values) { + this.values.addAll(values); + } +} diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/PriorityProvider.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/PriorityProvider.java new file mode 100644 index 0000000000..9d4b105afa --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/PriorityProvider.java @@ -0,0 +1,22 @@ +package com.baeldung.value; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +@Component +@PropertySource("classpath:values.properties") +public class PriorityProvider { + + private final String priority; + + @Autowired + public PriorityProvider(@Value("${priority:normal}") String priority) { + this.priority = priority; + } + + public String getPriority() { + return priority; + } +} diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/values.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/values.properties index c6db5873fb..9c85893d5f 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/resources/values.properties +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/values.properties @@ -1,4 +1,4 @@ value.from.file=Value got from the file -priority=Properties file +priority=high listOfValues=A,B,C valuesMap={key1:'1', key2 : '2', key3 : '3'} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/CollectionProviderIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/CollectionProviderIntegrationTest.java new file mode 100644 index 0000000000..33552f2e1a --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/CollectionProviderIntegrationTest.java @@ -0,0 +1,22 @@ +package com.baeldung.value; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = CollectionProvider.class) +public class CollectionProviderIntegrationTest { + + @Autowired + private CollectionProvider collectionProvider; + + @Test + public void givenPropertyFileWhenSetterInjectionUsedThenValueInjected() { + assertThat(collectionProvider.getValues()).contains("A", "B", "C"); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/PriorityProviderIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/PriorityProviderIntegrationTest.java new file mode 100644 index 0000000000..19b5a36ff5 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/PriorityProviderIntegrationTest.java @@ -0,0 +1,22 @@ +package com.baeldung.value; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PriorityProvider.class) +public class PriorityProviderIntegrationTest { + + @Autowired + private PriorityProvider priorityProvider; + + @Test + public void givenPropertyFileWhenConstructorInjectionUsedThenValueInjected() { + assertThat(priorityProvider.getPriority()).isEqualTo("Properties file"); + } +} \ No newline at end of file From c119a51ff995182df4625c0d7fc6357cca959979 Mon Sep 17 00:00:00 2001 From: Roland Weisleder Date: Tue, 19 May 2020 22:24:05 +0200 Subject: [PATCH 124/150] BAEL-4010 Add test for InputStream.readAllBytes() (#9265) * BAEL-4010 Add test for InputStream.readAllBytes() * BAEL-4010 Refactor: Move "InputStream to Bytes" to Java 9 specific module The issue BAEL-4010 introduces a new example to the article "Java InputStream to Byte Array and ByteBuffer". The example is about byte[] InputStream.readAllBytes() which was added with Java 9. To be consistent, all examples for this article were moved to a module which is compiled with at least Java 9. --- .../core-java-9-improvements/README.md | 1 + .../core-java-9-improvements/pom.xml | 5 ++ .../InputStreamToByteArrayUnitTest.java | 57 +++++++++++++++++++ .../InputStreamToByteBufferUnitTest.java | 2 +- .../core-java-io-conversions-2/README.md | 1 - .../JavaInputStreamToXUnitTest.java | 37 ------------ 6 files changed, 64 insertions(+), 39 deletions(-) create mode 100644 core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/io/conversion/InputStreamToByteArrayUnitTest.java rename core-java-modules/{core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtobytes => core-java-9-improvements/src/test/java/com/baeldung/java9/io/conversion}/InputStreamToByteBufferUnitTest.java (97%) diff --git a/core-java-modules/core-java-9-improvements/README.md b/core-java-modules/core-java-9-improvements/README.md index c89d0e3c09..3b0bdcd651 100644 --- a/core-java-modules/core-java-9-improvements/README.md +++ b/core-java-modules/core-java-9-improvements/README.md @@ -9,3 +9,4 @@ This module contains articles about the improvements to core Java features intro - [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api) - [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new) - [Java 9 CompletableFuture API Improvements](https://www.baeldung.com/java-9-completablefuture) +- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes) diff --git a/core-java-modules/core-java-9-improvements/pom.xml b/core-java-modules/core-java-9-improvements/pom.xml index d1c6bac9ec..5cc4fce7a9 100644 --- a/core-java-modules/core-java-9-improvements/pom.xml +++ b/core-java-modules/core-java-9-improvements/pom.xml @@ -33,6 +33,11 @@ guava ${guava.version} + + commons-io + commons-io + ${commons-io.version} + org.junit.platform junit-platform-runner diff --git a/core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/io/conversion/InputStreamToByteArrayUnitTest.java b/core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/io/conversion/InputStreamToByteArrayUnitTest.java new file mode 100644 index 0000000000..b64709be09 --- /dev/null +++ b/core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/io/conversion/InputStreamToByteArrayUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.java9.io.conversion; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.apache.commons.io.IOUtils; +import org.junit.Test; + +import com.google.common.io.ByteSource; +import com.google.common.io.ByteStreams; + +public class InputStreamToByteArrayUnitTest { + + @Test + public final void givenUsingPlainJavaOnFixedSizeStream_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException { + final InputStream initialStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 }); + final byte[] targetArray = new byte[initialStream.available()]; + initialStream.read(targetArray); + } + + @Test + public final void givenUsingPlainJavaOnUnknownSizeStream_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException { + final InputStream is = new ByteArrayInputStream(new byte[] { 0, 1, 2 }); + + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + int nRead; + final byte[] data = new byte[1024]; + while ((nRead = is.read(data, 0, data.length)) != -1) { + buffer.write(data, 0, nRead); + } + + buffer.flush(); + final byte[] byteArray = buffer.toByteArray(); + } + + @Test + public void givenUsingPlainJava9_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException { + final InputStream is = new ByteArrayInputStream(new byte[] { 0, 1, 2 }); + + byte[] data = is.readAllBytes(); + } + + @Test + public final void givenUsingGuava_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException { + final InputStream initialStream = ByteSource.wrap(new byte[] { 0, 1, 2 }) + .openStream(); + final byte[] targetArray = ByteStreams.toByteArray(initialStream); + } + + @Test + public final void givenUsingCommonsIO_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException { + final InputStream initialStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 }); + final byte[] targetArray = IOUtils.toByteArray(initialStream); + } +} diff --git a/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtobytes/InputStreamToByteBufferUnitTest.java b/core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/io/conversion/InputStreamToByteBufferUnitTest.java similarity index 97% rename from core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtobytes/InputStreamToByteBufferUnitTest.java rename to core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/io/conversion/InputStreamToByteBufferUnitTest.java index c10aaae22a..f97352ac27 100644 --- a/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtobytes/InputStreamToByteBufferUnitTest.java +++ b/core-java-modules/core-java-9-improvements/src/test/java/com/baeldung/java9/io/conversion/InputStreamToByteBufferUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.inputstreamtobytes; +package com.baeldung.java9.io.conversion; import com.google.common.io.ByteSource; import com.google.common.io.ByteStreams; diff --git a/core-java-modules/core-java-io-conversions-2/README.md b/core-java-modules/core-java-io-conversions-2/README.md index 4a28bf37c5..5cb9c21c54 100644 --- a/core-java-modules/core-java-io-conversions-2/README.md +++ b/core-java-modules/core-java-io-conversions-2/README.md @@ -4,6 +4,5 @@ This module contains articles about core Java input/output(IO) conversions. ### Relevant Articles: - [Java InputStream to String](https://www.baeldung.com/convert-input-stream-to-string) -- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes) - [Java – Write an InputStream to a File](https://www.baeldung.com/convert-input-stream-to-a-file) - More articles: [[<-- prev]](/core-java-modules/core-java-io-conversions) diff --git a/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java index c8c711e328..c34c32891f 100644 --- a/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java +++ b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java @@ -2,7 +2,6 @@ package com.baeldung.inputstreamtostring; import com.google.common.base.Charsets; import com.google.common.io.ByteSource; -import com.google.common.io.ByteStreams; import com.google.common.io.CharStreams; import com.google.common.io.Files; import org.apache.commons.io.FileUtils; @@ -152,42 +151,6 @@ public class JavaInputStreamToXUnitTest { assertThat(result, equalTo(originalString)); } - // tests - InputStream to byte[] - - @Test - public final void givenUsingPlainJavaOnFixedSizeStream_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException { - final InputStream initialStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 }); - final byte[] targetArray = new byte[initialStream.available()]; - initialStream.read(targetArray); - } - - @Test - public final void givenUsingPlainJavaOnUnknownSizeStream_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException { - final InputStream is = new ByteArrayInputStream(new byte[] { 0, 1, 2 }); - - final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - int nRead; - final byte[] data = new byte[1024]; - while ((nRead = is.read(data, 0, data.length)) != -1) { - buffer.write(data, 0, nRead); - } - - buffer.flush(); - final byte[] byteArray = buffer.toByteArray(); - } - - @Test - public final void givenUsingGuava_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException { - final InputStream initialStream = ByteSource.wrap(new byte[] { 0, 1, 2 }).openStream(); - final byte[] targetArray = ByteStreams.toByteArray(initialStream); - } - - @Test - public final void givenUsingCommonsIO_whenConvertingAnInputStreamToAByteArray_thenCorrect() throws IOException { - final InputStream initialStream = new ByteArrayInputStream(new byte[] { 0, 1, 2 }); - final byte[] targetArray = IOUtils.toByteArray(initialStream); - } - // tests - InputStream to File @Test From eb739e3ab22ea1976e023981e1ea910f121ca7fa Mon Sep 17 00:00:00 2001 From: kwoyke Date: Tue, 19 May 2020 22:30:01 +0200 Subject: [PATCH 125/150] BAEL-3745: Update spring-boot-modules pom.xml (#9316) --- spring-boot-modules/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 5acaa30328..6caa93158a 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -49,6 +49,7 @@ spring-boot-parent spring-boot-performance spring-boot-properties + spring-boot-properties-2 spring-boot-property-exp spring-boot-runtime spring-boot-security From 07576ef07b840cdc91aa5639ca6bce3b4c312871 Mon Sep 17 00:00:00 2001 From: Josh Cummings Date: Tue, 19 May 2020 19:24:45 -0600 Subject: [PATCH 126/150] Update README.md Issue BAEL-3751 --- spring-boot-modules/spring-boot-ci-cd/README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/spring-boot-modules/spring-boot-ci-cd/README.md b/spring-boot-modules/spring-boot-ci-cd/README.md index d207cd0fa0..ee8f106b53 100644 --- a/spring-boot-modules/spring-boot-ci-cd/README.md +++ b/spring-boot-modules/spring-boot-ci-cd/README.md @@ -1 +1,7 @@ -# Spring Boot CI/CD \ No newline at end of file +# Spring Boot CI/CD + +This module contains articles about CI/CD with Spring Boot + +## Relevant Articles + +- [CI/CD for a Spring Boot Project](https://www.baeldung.com/spring-boot-ci-cd) From f1be6fa3ae82baeb75918c47864c6f2d10bfd73d Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Wed, 20 May 2020 07:54:02 +0200 Subject: [PATCH 127/150] Update ExchangerPipeLineManualTest.java (#9326) --- .../exchanger/ExchangerPipeLineManualTest.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerPipeLineManualTest.java b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerPipeLineManualTest.java index 093580654b..af8b8b9aa1 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerPipeLineManualTest.java +++ b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/exchanger/ExchangerPipeLineManualTest.java @@ -40,15 +40,15 @@ public class ExchangerPipeLineManualTest { Runnable processor = () -> { Queue processorBuffer = new ConcurrentLinkedQueue<>(); - Queue writterBuffer = new ConcurrentLinkedQueue<>(); + Queue writerBuffer = new ConcurrentLinkedQueue<>(); try { processorBuffer = readerExchanger.exchange(processorBuffer); while (true) { - writterBuffer.add(processorBuffer.poll()); + writerBuffer.add(processorBuffer.poll()); if (processorBuffer.isEmpty()) { try { processorBuffer = readerExchanger.exchange(processorBuffer); - writterBuffer = writerExchanger.exchange(writterBuffer); + writerBuffer = writerExchanger.exchange(writerBuffer); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); @@ -62,13 +62,13 @@ public class ExchangerPipeLineManualTest { }; Runnable writer = () -> { - Queue writterBuffer = new ConcurrentLinkedQueue<>(); + Queue writerBuffer = new ConcurrentLinkedQueue<>(); try { - writterBuffer = writerExchanger.exchange(writterBuffer); + writerBuffer = writerExchanger.exchange(writerBuffer); while (true) { - System.out.println(writterBuffer.poll()); - if (writterBuffer.isEmpty()) { - writterBuffer = writerExchanger.exchange(writterBuffer); + System.out.println(writerBuffer.poll()); + if (writerBuffer.isEmpty()) { + writerBuffer = writerExchanger.exchange(writerBuffer); } } } catch (InterruptedException e) { From 78683ecf0c323d6cf26be7e19aff0dcb1f859044 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 20 May 2020 11:46:37 +0530 Subject: [PATCH 128/150] JAVA-940: Migrate spring-jenkins-pipeline to parent-boot-2 --- spring-jenkins-pipeline/pom.xml | 4 ++-- .../test/java/com/baeldung/SomeIntegrationTest.java | 2 +- .../src/test/java/com/baeldung/TestMongoConfig.java | 11 ----------- 3 files changed, 3 insertions(+), 14 deletions(-) delete mode 100644 spring-jenkins-pipeline/src/test/java/com/baeldung/TestMongoConfig.java diff --git a/spring-jenkins-pipeline/pom.xml b/spring-jenkins-pipeline/pom.xml index aa6008162c..38d4ed15de 100644 --- a/spring-jenkins-pipeline/pom.xml +++ b/spring-jenkins-pipeline/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/spring-jenkins-pipeline/src/test/java/com/baeldung/SomeIntegrationTest.java b/spring-jenkins-pipeline/src/test/java/com/baeldung/SomeIntegrationTest.java index 477a7d2adb..9033d10c5d 100644 --- a/spring-jenkins-pipeline/src/test/java/com/baeldung/SomeIntegrationTest.java +++ b/spring-jenkins-pipeline/src/test/java/com/baeldung/SomeIntegrationTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertNotEquals; @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = {SpringJenkinsPipelineApplication.class, TestMongoConfig.class }) +@SpringBootTest(classes = {SpringJenkinsPipelineApplication.class}) public class SomeIntegrationTest { @Autowired private StudentRepository studentRepository; diff --git a/spring-jenkins-pipeline/src/test/java/com/baeldung/TestMongoConfig.java b/spring-jenkins-pipeline/src/test/java/com/baeldung/TestMongoConfig.java deleted file mode 100644 index a85491cf7e..0000000000 --- a/spring-jenkins-pipeline/src/test/java/com/baeldung/TestMongoConfig.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung; - -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration; -import org.springframework.context.annotation.Configuration; - -@Configuration -@EnableAutoConfiguration(exclude = { EmbeddedMongoAutoConfiguration.class }) -public class TestMongoConfig { - -} \ No newline at end of file From 5ab3de4965aead4cc30ed2027638fd49a480383b Mon Sep 17 00:00:00 2001 From: Krzysztof Woyke Date: Wed, 20 May 2020 13:36:48 +0200 Subject: [PATCH 129/150] JAVA-1526: Copy spring-boot-json-properties to spring-boot-properties-2 --- .../spring-boot-properties-2/pom.xml | 4 ++ .../json/ConfigPropertiesDemoApplication.java | 16 +++++ .../properties/json/CustomJsonProperties.java | 71 +++++++++++++++++++ .../properties/json/JsonProperties.java | 65 +++++++++++++++++ .../json/JsonPropertyContextInitializer.java | 67 +++++++++++++++++ .../factory/JsonPropertySourceFactory.java | 20 ++++++ .../src/main/resources/configprops.json | 10 +++ .../json/JsonPropertiesIntegrationTest.java | 59 +++++++++++++++ 8 files changed, 312 insertions(+) create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/ConfigPropertiesDemoApplication.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/CustomJsonProperties.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/JsonProperties.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/JsonPropertyContextInitializer.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/factory/JsonPropertySourceFactory.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/resources/configprops.json create mode 100644 spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/json/JsonPropertiesIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-properties-2/pom.xml b/spring-boot-modules/spring-boot-properties-2/pom.xml index c3c3e57251..bd2a35b19d 100644 --- a/spring-boot-modules/spring-boot-properties-2/pom.xml +++ b/spring-boot-modules/spring-boot-properties-2/pom.xml @@ -20,6 +20,10 @@ org.springframework.boot spring-boot-starter + + org.springframework.boot + spring-boot-starter-web + diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/ConfigPropertiesDemoApplication.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/ConfigPropertiesDemoApplication.java new file mode 100644 index 0000000000..a1e2584b2c --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/ConfigPropertiesDemoApplication.java @@ -0,0 +1,16 @@ +package com.baeldung.properties.json; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackageClasses = {JsonProperties.class, CustomJsonProperties.class}) +public class ConfigPropertiesDemoApplication { + + public static void main(String[] args) { + new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer()) + .run(); + } + +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/CustomJsonProperties.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/CustomJsonProperties.java new file mode 100644 index 0000000000..555711c49b --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/CustomJsonProperties.java @@ -0,0 +1,71 @@ +package com.baeldung.properties.json; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Component +@ConfigurationProperties(prefix = "custom") +public class CustomJsonProperties { + + private String host; + + private int port; + + private boolean resend; + + private Person sender; + + public static class Person { + + private String name; + private String address; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public boolean isResend() { + return resend; + } + + public void setResend(boolean resend) { + this.resend = resend; + } + + public Person getSender() { + return sender; + } + + public void setSender(Person sender) { + this.sender = sender; + } +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/JsonProperties.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/JsonProperties.java new file mode 100644 index 0000000000..6ada770e3b --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/JsonProperties.java @@ -0,0 +1,65 @@ +package com.baeldung.properties.json; + +import com.baeldung.properties.json.factory.JsonPropertySourceFactory; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +import java.util.LinkedHashMap; +import java.util.List; + +@Component +@PropertySource(value = "classpath:configprops.json", factory = JsonPropertySourceFactory.class) +@ConfigurationProperties +public class JsonProperties { + + private String host; + + private int port; + + private boolean resend; + + private List topics; + + private LinkedHashMap sender; + + public LinkedHashMap getSender() { + return sender; + } + + public void setSender(LinkedHashMap sender) { + this.sender = sender; + } + + public List getTopics() { + return topics; + } + + public void setTopics(List topics) { + this.topics = topics; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public boolean isResend() { + return resend; + } + + public void setResend(boolean resend) { + this.resend = resend; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/JsonPropertyContextInitializer.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/JsonPropertyContextInitializer.java new file mode 100644 index 0000000000..e3b713f29b --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/JsonPropertyContextInitializer.java @@ -0,0 +1,67 @@ +package com.baeldung.properties.json; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.Resource; + +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +public class JsonPropertyContextInitializer implements ApplicationContextInitializer { + + private final static String CUSTOM_PREFIX = "custom."; + + @Override + @SuppressWarnings("unchecked") + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { + try { + Resource resource = configurableApplicationContext.getResource("classpath:configprops.json"); + Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class); + Set set = readValue.entrySet(); + List propertySources = convertEntrySet(set, Optional.empty()); + for (PropertySource propertySource : propertySources) { + configurableApplicationContext.getEnvironment() + .getPropertySources() + .addFirst(propertySource); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private static List convertEntrySet(Set entrySet, Optional parentKey) { + return entrySet.stream() + .map((Map.Entry e) -> convertToPropertySourceList(e, parentKey)) + .flatMap(Collection::stream) + .collect(Collectors.toList()); + } + + private static List convertToPropertySourceList(Map.Entry e, Optional parentKey) { + String key = parentKey.map(s -> s + ".") + .orElse("") + (String) e.getKey(); + Object value = e.getValue(); + return covertToPropertySourceList(key, value); + } + + @SuppressWarnings("unchecked") + private static List covertToPropertySourceList(String key, Object value) { + if (value instanceof LinkedHashMap) { + LinkedHashMap map = (LinkedHashMap) value; + Set entrySet = map.entrySet(); + return convertEntrySet(entrySet, Optional.ofNullable(key)); + } + String finalKey = CUSTOM_PREFIX + key; + return Collections.singletonList(new MapPropertySource(finalKey, Collections.singletonMap(finalKey, value))); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/factory/JsonPropertySourceFactory.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/factory/JsonPropertySourceFactory.java new file mode 100644 index 0000000000..dccaae4ad2 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/json/factory/JsonPropertySourceFactory.java @@ -0,0 +1,20 @@ +package com.baeldung.properties.json.factory; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.PropertySource; +import org.springframework.core.io.support.EncodedResource; +import org.springframework.core.io.support.PropertySourceFactory; + +import java.io.IOException; +import java.util.Map; + +public class JsonPropertySourceFactory implements PropertySourceFactory { + + @Override + public PropertySource createPropertySource(String name, EncodedResource resource) throws IOException { + Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class); + return new MapPropertySource("json-property", readValue); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/resources/configprops.json b/spring-boot-modules/spring-boot-properties-2/src/main/resources/configprops.json new file mode 100644 index 0000000000..1602663775 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/resources/configprops.json @@ -0,0 +1,10 @@ +{ + "host" : "mailer@mail.com", + "port" : 9090, + "resend" : true, + "topics" : ["spring", "boot"], + "sender" : { + "name": "sender", + "address": "street" + } +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/json/JsonPropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/json/JsonPropertiesIntegrationTest.java new file mode 100644 index 0000000000..6b00489b5c --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/json/JsonPropertiesIntegrationTest.java @@ -0,0 +1,59 @@ +package com.baeldung.properties.json; + +import org.hamcrest.Matchers; +import org.junit.Assert; +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.SpringRunner; + +import java.util.Arrays; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = ConfigPropertiesDemoApplication.class, initializers = JsonPropertyContextInitializer.class) +public class JsonPropertiesIntegrationTest { + + @Autowired + private JsonProperties jsonProperties; + + @Autowired + private CustomJsonProperties customJsonProperties; + + @Test + public void whenPropertiesLoadedViaJsonPropertySource_thenLoadFlatValues() { + Assert.assertEquals("mailer@mail.com", jsonProperties.getHost()); + Assert.assertEquals(9090, jsonProperties.getPort()); + Assert.assertTrue(jsonProperties.isResend()); + } + + @Test + public void whenPropertiesLoadedViaJsonPropertySource_thenLoadListValues() { + Assert.assertThat(jsonProperties.getTopics(), Matchers.is(Arrays.asList("spring", "boot"))); + } + + @Test + public void whenPropertiesLoadedViaJsonPropertySource_thenNestedLoadedAsMap() { + Assert.assertEquals("sender", jsonProperties.getSender() + .get("name")); + Assert.assertEquals("street", jsonProperties.getSender() + .get("address")); + } + + @Test + public void whenLoadedIntoEnvironment_thenFlatValuesPopulated() { + Assert.assertEquals("mailer@mail.com", customJsonProperties.getHost()); + Assert.assertEquals(9090, customJsonProperties.getPort()); + Assert.assertTrue(customJsonProperties.isResend()); + } + + @Test + public void whenLoadedIntoEnvironment_thenValuesLoadedIntoClassObject() { + Assert.assertNotNull(customJsonProperties.getSender()); + Assert.assertEquals("sender", customJsonProperties.getSender() + .getName()); + Assert.assertEquals("street", customJsonProperties.getSender() + .getAddress()); + } + +} From 8afe64de3e82fda4a9333611ae2c3b6c8366e490 Mon Sep 17 00:00:00 2001 From: Krzysztof Woyke Date: Wed, 20 May 2020 14:37:43 +0200 Subject: [PATCH 130/150] JAVA-1526: Remove spring-boot-json-properties from spring-boot-properties --- .../spring-boot-properties-2/README.md | 1 + .../spring-boot-properties/README.md | 1 - .../ConfigPropertiesDemoApplication.java | 7 +- .../properties/CustomJsonProperties.java | 71 ------------------- .../baeldung/properties/JsonProperties.java | 64 ----------------- .../JsonPropertyContextInitializer.java | 68 ------------------ .../properties/JsonPropertySourceFactory.java | 21 ------ .../src/main/resources/configprops.json | 10 --- .../JsonPropertiesIntegrationTest.java | 59 --------------- .../PriorityProviderIntegrationTest.java | 2 +- 10 files changed, 6 insertions(+), 298 deletions(-) delete mode 100644 spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/CustomJsonProperties.java delete mode 100644 spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/JsonProperties.java delete mode 100644 spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/JsonPropertyContextInitializer.java delete mode 100644 spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/JsonPropertySourceFactory.java delete mode 100644 spring-boot-modules/spring-boot-properties/src/main/resources/configprops.json delete mode 100644 spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/JsonPropertiesIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-properties-2/README.md b/spring-boot-modules/spring-boot-properties-2/README.md index 01e2970e89..326e652af3 100644 --- a/spring-boot-modules/spring-boot-properties-2/README.md +++ b/spring-boot-modules/spring-boot-properties-2/README.md @@ -3,3 +3,4 @@ This module contains articles about Properties in Spring Boot. ### Relevant Articles: +- [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties) \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/README.md b/spring-boot-modules/spring-boot-properties/README.md index f861a01d10..addfe01438 100644 --- a/spring-boot-modules/spring-boot-properties/README.md +++ b/spring-boot-modules/spring-boot-properties/README.md @@ -5,7 +5,6 @@ This module contains articles about Properties in Spring Boot. ### Relevant Articles: - [Reloading Properties Files in Spring](https://www.baeldung.com/spring-reloading-properties) - [Guide to @ConfigurationProperties in Spring Boot](https://www.baeldung.com/configuration-properties-in-spring-boot) -- [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties) - [Guide to @EnableConfigurationProperties](https://www.baeldung.com/spring-enable-config-properties) - [Properties with Spring and Spring Boot](https://www.baeldung.com/properties-with-spring) - checkout the `com.baeldung.properties` package for all scenarios of properties injection and usage - [A Quick Guide to Spring @Value](https://www.baeldung.com/spring-value-annotation) diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java index e280bbd79f..88e6f47e51 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java @@ -1,5 +1,7 @@ package com.baeldung.properties; +import com.baeldung.buildproperties.Application; +import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.ComponentScan; @@ -7,11 +9,10 @@ import org.springframework.context.annotation.ComponentScan; import com.baeldung.configurationproperties.ConfigProperties; @SpringBootApplication -@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class}) +@ComponentScan(basePackageClasses = ConfigProperties.class) public class ConfigPropertiesDemoApplication { public static void main(String[] args) { - new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer()) - .run(); + SpringApplication.run(ConfigPropertiesDemoApplication.class, args); } } diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/CustomJsonProperties.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/CustomJsonProperties.java deleted file mode 100644 index 084138ec6f..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/CustomJsonProperties.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.baeldung.properties; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - -@Component -@ConfigurationProperties(prefix = "custom") -public class CustomJsonProperties { - - private String host; - - private int port; - - private boolean resend; - - private Person sender; - - public static class Person { - - private String name; - private String address; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public boolean isResend() { - return resend; - } - - public void setResend(boolean resend) { - this.resend = resend; - } - - public Person getSender() { - return sender; - } - - public void setSender(Person sender) { - this.sender = sender; - } -} diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/JsonProperties.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/JsonProperties.java deleted file mode 100644 index 31b3be14b4..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/JsonProperties.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.properties; - -import java.util.LinkedHashMap; -import java.util.List; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.PropertySource; -import org.springframework.stereotype.Component; - -@Component -@PropertySource(value = "classpath:configprops.json", factory = JsonPropertySourceFactory.class) -@ConfigurationProperties -public class JsonProperties { - - private String host; - - private int port; - - private boolean resend; - - private List topics; - - private LinkedHashMap sender; - - public LinkedHashMap getSender() { - return sender; - } - - public void setSender(LinkedHashMap sender) { - this.sender = sender; - } - - public List getTopics() { - return topics; - } - - public void setTopics(List topics) { - this.topics = topics; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public boolean isResend() { - return resend; - } - - public void setResend(boolean resend) { - this.resend = resend; - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } -} diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/JsonPropertyContextInitializer.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/JsonPropertyContextInitializer.java deleted file mode 100644 index 0aee149123..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/JsonPropertyContextInitializer.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.baeldung.properties; - -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.MapPropertySource; -import org.springframework.core.env.PropertySource; -import org.springframework.core.io.Resource; - -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JsonPropertyContextInitializer implements ApplicationContextInitializer { - - private final static String CUSTOM_PREFIX = "custom."; - - @Override - @SuppressWarnings("unchecked") - public void initialize(ConfigurableApplicationContext configurableApplicationContext) { - try { - Resource resource = configurableApplicationContext.getResource("classpath:configprops.json"); - Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class); - Set set = readValue.entrySet(); - List propertySources = convertEntrySet(set, Optional.empty()); - for (PropertySource propertySource : propertySources) { - configurableApplicationContext.getEnvironment() - .getPropertySources() - .addFirst(propertySource); - } - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - private static List convertEntrySet(Set entrySet, Optional parentKey) { - return entrySet.stream() - .map((Map.Entry e) -> convertToPropertySourceList(e, parentKey)) - .flatMap(Collection::stream) - .collect(Collectors.toList()); - } - - private static List convertToPropertySourceList(Map.Entry e, Optional parentKey) { - String key = parentKey.map(s -> s + ".") - .orElse("") + (String) e.getKey(); - Object value = e.getValue(); - return covertToPropertySourceList(key, value); - } - - @SuppressWarnings("unchecked") - private static List covertToPropertySourceList(String key, Object value) { - if (value instanceof LinkedHashMap) { - LinkedHashMap map = (LinkedHashMap) value; - Set entrySet = map.entrySet(); - return convertEntrySet(entrySet, Optional.ofNullable(key)); - } - String finalKey = CUSTOM_PREFIX + key; - return Collections.singletonList(new MapPropertySource(finalKey, Collections.singletonMap(finalKey, value))); - } - -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/JsonPropertySourceFactory.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/JsonPropertySourceFactory.java deleted file mode 100644 index c14d3faea5..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/JsonPropertySourceFactory.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.properties; - -import java.io.IOException; -import java.util.Map; - -import org.springframework.core.env.MapPropertySource; -import org.springframework.core.env.PropertySource; -import org.springframework.core.io.support.EncodedResource; -import org.springframework.core.io.support.PropertySourceFactory; - -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JsonPropertySourceFactory implements PropertySourceFactory { - - @Override - public PropertySource createPropertySource(String name, EncodedResource resource) throws IOException { - Map readValue = new ObjectMapper().readValue(resource.getInputStream(), Map.class); - return new MapPropertySource("json-property", readValue); - } - -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/configprops.json b/spring-boot-modules/spring-boot-properties/src/main/resources/configprops.json deleted file mode 100644 index 1602663775..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/main/resources/configprops.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "host" : "mailer@mail.com", - "port" : 9090, - "resend" : true, - "topics" : ["spring", "boot"], - "sender" : { - "name": "sender", - "address": "street" - } -} diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/JsonPropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/JsonPropertiesIntegrationTest.java deleted file mode 100644 index 2f0e5ae408..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/JsonPropertiesIntegrationTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.baeldung.properties; - -import java.util.Arrays; - -import org.hamcrest.Matchers; -import org.junit.Assert; -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.SpringRunner; - -@RunWith(SpringRunner.class) -@ContextConfiguration(classes = ConfigPropertiesDemoApplication.class, initializers = JsonPropertyContextInitializer.class) -public class JsonPropertiesIntegrationTest { - - @Autowired - private JsonProperties jsonProperties; - - @Autowired - private CustomJsonProperties customJsonProperties; - - @Test - public void whenPropertiesLoadedViaJsonPropertySource_thenLoadFlatValues() { - Assert.assertEquals("mailer@mail.com", jsonProperties.getHost()); - Assert.assertEquals(9090, jsonProperties.getPort()); - Assert.assertTrue(jsonProperties.isResend()); - } - - @Test - public void whenPropertiesLoadedViaJsonPropertySource_thenLoadListValues() { - Assert.assertThat(jsonProperties.getTopics(), Matchers.is(Arrays.asList("spring", "boot"))); - } - - @Test - public void whenPropertiesLoadedViaJsonPropertySource_thenNestedLoadedAsMap() { - Assert.assertEquals("sender", jsonProperties.getSender() - .get("name")); - Assert.assertEquals("street", jsonProperties.getSender() - .get("address")); - } - - @Test - public void whenLoadedIntoEnvironment_thenFlatValuesPopulated() { - Assert.assertEquals("mailer@mail.com", customJsonProperties.getHost()); - Assert.assertEquals(9090, customJsonProperties.getPort()); - Assert.assertTrue(customJsonProperties.isResend()); - } - - @Test - public void whenLoadedIntoEnvironment_thenValuesLoadedIntoClassObject() { - Assert.assertNotNull(customJsonProperties.getSender()); - Assert.assertEquals("sender", customJsonProperties.getSender() - .getName()); - Assert.assertEquals("street", customJsonProperties.getSender() - .getAddress()); - } - -} diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/PriorityProviderIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/PriorityProviderIntegrationTest.java index 19b5a36ff5..aa365a4b6a 100644 --- a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/PriorityProviderIntegrationTest.java +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/PriorityProviderIntegrationTest.java @@ -17,6 +17,6 @@ public class PriorityProviderIntegrationTest { @Test public void givenPropertyFileWhenConstructorInjectionUsedThenValueInjected() { - assertThat(priorityProvider.getPriority()).isEqualTo("Properties file"); + assertThat(priorityProvider.getPriority()).isEqualTo("high"); } } \ No newline at end of file From c4101d7df754baa839dc6433804198197ad7e4cc Mon Sep 17 00:00:00 2001 From: Krzysztof Woyke Date: Wed, 20 May 2020 14:50:33 +0200 Subject: [PATCH 131/150] JAVA-1526: Fix test configuration --- .../baeldung/properties/ConfigPropertiesDemoApplication.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java index 88e6f47e51..1e5e88921a 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java @@ -9,7 +9,7 @@ import org.springframework.context.annotation.ComponentScan; import com.baeldung.configurationproperties.ConfigProperties; @SpringBootApplication -@ComponentScan(basePackageClasses = ConfigProperties.class) +@ComponentScan(basePackageClasses = {ConfigProperties.class, AdditionalProperties.class}) public class ConfigPropertiesDemoApplication { public static void main(String[] args) { SpringApplication.run(ConfigPropertiesDemoApplication.class, args); From 304a6fb6ccfb37a63b18b0f2534acb90cbd5b7d9 Mon Sep 17 00:00:00 2001 From: Krzysztof Woyke Date: Wed, 20 May 2020 15:51:11 +0200 Subject: [PATCH 132/150] JAVA-1526: Copy three @Value related articles to spring-boot-properties-2 --- .../spring-boot-properties-2/README.md | 5 +- .../value/ClassNotManagedBySpring.java | 28 +++++ .../properties/value/CollectionProvider.java | 27 +++++ .../properties/value/InitializerBean.java | 21 ++++ .../properties/value/PriorityProvider.java | 22 ++++ .../baeldung/properties/value/SomeBean.java | 17 +++ .../baeldung/properties/value/ValuesApp.java | 101 ++++++++++++++++++ .../value/defaults/ValuesWithDefaultsApp.java | 71 ++++++++++++ .../src/main/resources/values.properties | 4 + .../resources/valueswithdefaults.properties | 0 ...lassNotManagedBySpringIntegrationTest.java | 40 +++++++ .../CollectionProviderIntegrationTest.java | 22 ++++ .../PriorityProviderIntegrationTest.java | 22 ++++ .../spring-boot-properties/README.md | 3 - 14 files changed, 379 insertions(+), 4 deletions(-) create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/ClassNotManagedBySpring.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/CollectionProvider.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/InitializerBean.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/PriorityProvider.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/SomeBean.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/ValuesApp.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/defaults/ValuesWithDefaultsApp.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/resources/values.properties create mode 100644 spring-boot-modules/spring-boot-properties-2/src/main/resources/valueswithdefaults.properties create mode 100644 spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/ClassNotManagedBySpringIntegrationTest.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/CollectionProviderIntegrationTest.java create mode 100644 spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/PriorityProviderIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-properties-2/README.md b/spring-boot-modules/spring-boot-properties-2/README.md index 326e652af3..7373932e4f 100644 --- a/spring-boot-modules/spring-boot-properties-2/README.md +++ b/spring-boot-modules/spring-boot-properties-2/README.md @@ -3,4 +3,7 @@ This module contains articles about Properties in Spring Boot. ### Relevant Articles: -- [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties) \ No newline at end of file +- [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties) +- [A Quick Guide to Spring @Value](https://www.baeldung.com/spring-value-annotation) +- [Using Spring @Value with Defaults](https://www.baeldung.com/spring-value-defaults) +- [How to Inject a Property Value Into a Class Not Managed by Spring?](https://www.baeldung.com/inject-properties-value-non-spring-class) \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/ClassNotManagedBySpring.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/ClassNotManagedBySpring.java new file mode 100644 index 0000000000..59ee73a07b --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/ClassNotManagedBySpring.java @@ -0,0 +1,28 @@ +package com.baeldung.properties.value; + +public class ClassNotManagedBySpring { + + private String customVariable; + private String anotherCustomVariable; + + public ClassNotManagedBySpring(String someInitialValue, String anotherManagedValue) { + this.customVariable = someInitialValue; + this.anotherCustomVariable = anotherManagedValue; + } + + public String getCustomVariable() { + return customVariable; + } + + public void setCustomVariable(String customVariable) { + this.customVariable = customVariable; + } + + public String getAnotherCustomVariable() { + return anotherCustomVariable; + } + + public void setAnotherCustomVariable(String anotherCustomVariable) { + this.anotherCustomVariable = anotherCustomVariable; + } +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/CollectionProvider.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/CollectionProvider.java new file mode 100644 index 0000000000..6327e688e8 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/CollectionProvider.java @@ -0,0 +1,27 @@ +package com.baeldung.properties.value; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +@Component +@PropertySource("classpath:values.properties") +public class CollectionProvider { + + private final List values = new ArrayList<>(); + + public Collection getValues() { + return Collections.unmodifiableCollection(values); + } + + @Autowired + public void setValues(@Value("#{'${listOfValues}'.split(',')}") List values) { + this.values.addAll(values); + } +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/InitializerBean.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/InitializerBean.java new file mode 100644 index 0000000000..b06cfa12ea --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/InitializerBean.java @@ -0,0 +1,21 @@ +package com.baeldung.properties.value; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class InitializerBean { + + private String someInitialValue; + private String anotherManagedValue; + + public InitializerBean(@Value("someInitialValue") String someInitialValue, @Value("anotherValue") String anotherManagedValue) { + this.someInitialValue = someInitialValue; + this.anotherManagedValue = anotherManagedValue; + } + + public ClassNotManagedBySpring initClass() { + return new ClassNotManagedBySpring(this.someInitialValue, this.anotherManagedValue); + } + +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/PriorityProvider.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/PriorityProvider.java new file mode 100644 index 0000000000..892118eb06 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/PriorityProvider.java @@ -0,0 +1,22 @@ +package com.baeldung.properties.value; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +@Component +@PropertySource("classpath:values.properties") +public class PriorityProvider { + + private final String priority; + + @Autowired + public PriorityProvider(@Value("${priority:normal}") String priority) { + this.priority = priority; + } + + public String getPriority() { + return priority; + } +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/SomeBean.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/SomeBean.java new file mode 100644 index 0000000000..b3346a96dd --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/SomeBean.java @@ -0,0 +1,17 @@ +package com.baeldung.properties.value; + +public class SomeBean { + private int someValue; + + public SomeBean(int someValue) { + this.someValue = someValue; + } + + public int getSomeValue() { + return someValue; + } + + public void setSomeValue(int someValue) { + this.someValue = someValue; + } +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/ValuesApp.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/ValuesApp.java new file mode 100644 index 0000000000..67547199a6 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/ValuesApp.java @@ -0,0 +1,101 @@ +package com.baeldung.properties.value; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; + +import javax.annotation.PostConstruct; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +@Configuration +@PropertySource(name = "myProperties", value = "values.properties") +public class ValuesApp { + + @Value("string value") + private String stringValue; + + @Value("${value.from.file}") + private String valueFromFile; + + @Value("${systemValue}") + private String systemValue; + + @Value("${unknown_param:some default}") + private String someDefault; + + @Value("${priority}") + private String prioritySystemProperty; + + @Value("${listOfValues}") + private String[] valuesArray; + + @Value("#{systemProperties['priority']}") + private String spelValue; + + @Value("#{systemProperties['unknown'] ?: 'some default'}") + private String spelSomeDefault; + + @Value("#{someBean.someValue}") + private Integer someBeanValue; + + @Value("#{'${listOfValues}'.split(',')}") + private List valuesList; + + @Value("#{${valuesMap}}") + private Map valuesMap; + + @Value("#{${valuesMap}.key1}") + private Integer valuesMapKey1; + + @Value("#{${valuesMap}['unknownKey']}") + private Integer unknownMapKey; + + @Value("#{${unknownMap : {key1:'1', key2 : '2'}}}") + private Map unknownMap; + + @Value("#{${valuesMap}['unknownKey'] ?: 5}") + private Integer unknownMapKeyWithDefaultValue; + + @Value("#{${valuesMap}.?[value>'1']}") + private Map valuesMapFiltered; + + @Value("#{systemProperties}") + private Map systemPropertiesMap; + + public static void main(String[] args) { + System.setProperty("systemValue", "Some system parameter value"); + System.setProperty("priority", "System property"); + ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ValuesApp.class); + } + + @Bean + public SomeBean someBean() { + return new SomeBean(10); + } + + @PostConstruct + public void afterInitialize() { + System.out.println(stringValue); + System.out.println(valueFromFile); + System.out.println(systemValue); + System.out.println(someDefault); + System.out.println(prioritySystemProperty); + System.out.println(Arrays.toString(valuesArray)); + System.out.println(spelValue); + System.out.println(spelSomeDefault); + System.out.println(someBeanValue); + System.out.println(valuesList); + System.out.println(valuesMap); + System.out.println(valuesMapKey1); + System.out.println(unknownMapKey); + System.out.println(unknownMap); + System.out.println(unknownMapKeyWithDefaultValue); + System.out.println(valuesMapFiltered); + System.out.println(systemPropertiesMap); + } +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/defaults/ValuesWithDefaultsApp.java b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/defaults/ValuesWithDefaultsApp.java new file mode 100644 index 0000000000..72fa0e03c0 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/java/com/baeldung/properties/value/defaults/ValuesWithDefaultsApp.java @@ -0,0 +1,71 @@ +package com.baeldung.properties.value.defaults; + +import org.apache.commons.lang3.ArrayUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.util.Assert; + +import javax.annotation.PostConstruct; +import java.util.Arrays; +import java.util.List; + +/** + * Demonstrates setting defaults for @Value annotation. Note that there are no properties + * defined in the specified property source. We also assume that the user here + * does not have a system property named some.key. + * + */ +@Configuration +@PropertySource(name = "myProperties", value = "valueswithdefaults.properties") +public class ValuesWithDefaultsApp { + + @Value("${some.key:my default value}") + private String stringWithDefaultValue; + + @Value("${some.key:}") + private String stringWithBlankDefaultValue; + + @Value("${some.key:true}") + private boolean booleanWithDefaultValue; + + @Value("${some.key:42}") + private int intWithDefaultValue; + + @Value("${some.key:one,two,three}") + private String[] stringArrayWithDefaults; + + @Value("${some.key:1,2,3}") + private int[] intArrayWithDefaults; + + @Value("#{systemProperties['some.key'] ?: 'my default system property value'}") + private String spelWithDefaultValue; + + + public static void main(String[] args) { + ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ValuesWithDefaultsApp.class); + } + + @PostConstruct + public void afterInitialize() { + // strings + Assert.isTrue(stringWithDefaultValue.equals("my default value")); + Assert.isTrue(stringWithBlankDefaultValue.equals("")); + + // other primitives + Assert.isTrue(booleanWithDefaultValue); + Assert.isTrue(intWithDefaultValue == 42); + + // arrays + List stringListValues = Arrays.asList("one", "two", "three"); + Assert.isTrue(Arrays.asList(stringArrayWithDefaults).containsAll(stringListValues)); + + List intListValues = Arrays.asList(1, 2, 3); + Assert.isTrue(Arrays.asList(ArrayUtils.toObject(intArrayWithDefaults)).containsAll(intListValues)); + + // SpEL + Assert.isTrue(spelWithDefaultValue.equals("my default system property value")); + } +} diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/resources/values.properties b/spring-boot-modules/spring-boot-properties-2/src/main/resources/values.properties new file mode 100644 index 0000000000..9c85893d5f --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/main/resources/values.properties @@ -0,0 +1,4 @@ +value.from.file=Value got from the file +priority=high +listOfValues=A,B,C +valuesMap={key1:'1', key2 : '2', key3 : '3'} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties-2/src/main/resources/valueswithdefaults.properties b/spring-boot-modules/spring-boot-properties-2/src/main/resources/valueswithdefaults.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/ClassNotManagedBySpringIntegrationTest.java b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/ClassNotManagedBySpringIntegrationTest.java new file mode 100644 index 0000000000..271242d4e8 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/ClassNotManagedBySpringIntegrationTest.java @@ -0,0 +1,40 @@ +package com.baeldung.properties.value; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; + +import static junit.framework.TestCase.assertEquals; +import static org.mockito.Mockito.when; + +@RunWith(SpringRunner.class) +public class ClassNotManagedBySpringIntegrationTest { + + @MockBean + private InitializerBean initializerBean; + + @Before + public void init() { + when(initializerBean.initClass()) + .thenReturn(new ClassNotManagedBySpring("This is only sample value", "Another configured value")); + } + + @Test + public void givenInitializerBean_whenInvokedInitClass_shouldInitialize() throws Exception { + + //given + ClassNotManagedBySpring classNotManagedBySpring = initializerBean.initClass(); + + //when + String initializedValue = classNotManagedBySpring.getCustomVariable(); + String anotherCustomVariable = classNotManagedBySpring.getAnotherCustomVariable(); + + //then + assertEquals("This is only sample value", initializedValue); + assertEquals("Another configured value", anotherCustomVariable); + + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/CollectionProviderIntegrationTest.java b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/CollectionProviderIntegrationTest.java new file mode 100644 index 0000000000..b045786a29 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/CollectionProviderIntegrationTest.java @@ -0,0 +1,22 @@ +package com.baeldung.properties.value; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = CollectionProvider.class) +public class CollectionProviderIntegrationTest { + + @Autowired + private CollectionProvider collectionProvider; + + @Test + public void givenPropertyFileWhenSetterInjectionUsedThenValueInjected() { + assertThat(collectionProvider.getValues()).contains("A", "B", "C"); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/PriorityProviderIntegrationTest.java b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/PriorityProviderIntegrationTest.java new file mode 100644 index 0000000000..d7d1e7d78b --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-2/src/test/java/com/baeldung/properties/value/PriorityProviderIntegrationTest.java @@ -0,0 +1,22 @@ +package com.baeldung.properties.value; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PriorityProvider.class) +public class PriorityProviderIntegrationTest { + + @Autowired + private PriorityProvider priorityProvider; + + @Test + public void givenPropertyFileWhenConstructorInjectionUsedThenValueInjected() { + assertThat(priorityProvider.getPriority()).isEqualTo("high"); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/README.md b/spring-boot-modules/spring-boot-properties/README.md index addfe01438..bea3d6a293 100644 --- a/spring-boot-modules/spring-boot-properties/README.md +++ b/spring-boot-modules/spring-boot-properties/README.md @@ -7,9 +7,6 @@ This module contains articles about Properties in Spring Boot. - [Guide to @ConfigurationProperties in Spring Boot](https://www.baeldung.com/configuration-properties-in-spring-boot) - [Guide to @EnableConfigurationProperties](https://www.baeldung.com/spring-enable-config-properties) - [Properties with Spring and Spring Boot](https://www.baeldung.com/properties-with-spring) - checkout the `com.baeldung.properties` package for all scenarios of properties injection and usage -- [A Quick Guide to Spring @Value](https://www.baeldung.com/spring-value-annotation) - [Spring YAML Configuration](https://www.baeldung.com/spring-yaml) -- [Using Spring @Value with Defaults](https://www.baeldung.com/spring-value-defaults) -- [How to Inject a Property Value Into a Class Not Managed by Spring?](https://www.baeldung.com/inject-properties-value-non-spring-class) - [Add Build Properties to a Spring Boot Application](https://www.baeldung.com/spring-boot-build-properties) - [IntelliJ – Cannot Resolve Spring Boot Configuration Properties Error](https://www.baeldung.com/intellij-resolve-spring-boot-configuration-properties) From 7c0fa2dbcf183bcec2dace829746f874a47e527e Mon Sep 17 00:00:00 2001 From: Krzysztof Woyke Date: Wed, 20 May 2020 15:58:43 +0200 Subject: [PATCH 133/150] JAVA-1526: Delete moved articles from spring-boot-properties --- .../value/ClassNotManagedBySpring.java | 28 ----- .../baeldung/value/CollectionProvider.java | 27 ----- .../com/baeldung/value/InitializerBean.java | 21 ---- .../com/baeldung/value/PriorityProvider.java | 22 ---- .../java/com/baeldung/value/SomeBean.java | 17 --- .../java/com/baeldung/value/ValuesApp.java | 102 ------------------ .../ValuesWithDefaultsApp.java | 75 ------------- .../src/main/resources/values.properties | 4 - .../resources/valueswithdefaults.properties | 0 ...lassNotManagedBySpringIntegrationTest.java | 40 ------- .../CollectionProviderIntegrationTest.java | 22 ---- .../PriorityProviderIntegrationTest.java | 22 ---- 12 files changed, 380 deletions(-) delete mode 100644 spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/ClassNotManagedBySpring.java delete mode 100644 spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/CollectionProvider.java delete mode 100644 spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/InitializerBean.java delete mode 100644 spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/PriorityProvider.java delete mode 100644 spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/SomeBean.java delete mode 100644 spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/ValuesApp.java delete mode 100644 spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java delete mode 100644 spring-boot-modules/spring-boot-properties/src/main/resources/values.properties delete mode 100644 spring-boot-modules/spring-boot-properties/src/main/resources/valueswithdefaults.properties delete mode 100644 spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/ClassNotManagedBySpringIntegrationTest.java delete mode 100644 spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/CollectionProviderIntegrationTest.java delete mode 100644 spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/PriorityProviderIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/ClassNotManagedBySpring.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/ClassNotManagedBySpring.java deleted file mode 100644 index 0329769d3c..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/ClassNotManagedBySpring.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.value; - -public class ClassNotManagedBySpring { - - private String customVariable; - private String anotherCustomVariable; - - public ClassNotManagedBySpring(String someInitialValue, String anotherManagedValue) { - this.customVariable = someInitialValue; - this.anotherCustomVariable = anotherManagedValue; - } - - public String getCustomVariable() { - return customVariable; - } - - public void setCustomVariable(String customVariable) { - this.customVariable = customVariable; - } - - public String getAnotherCustomVariable() { - return anotherCustomVariable; - } - - public void setAnotherCustomVariable(String anotherCustomVariable) { - this.anotherCustomVariable = anotherCustomVariable; - } -} diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/CollectionProvider.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/CollectionProvider.java deleted file mode 100644 index fdc1f8ee03..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/CollectionProvider.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.value; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.PropertySource; -import org.springframework.stereotype.Component; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -@Component -@PropertySource("classpath:values.properties") -public class CollectionProvider { - - private final List values = new ArrayList<>(); - - public Collection getValues() { - return Collections.unmodifiableCollection(values); - } - - @Autowired - public void setValues(@Value("#{'${listOfValues}'.split(',')}") List values) { - this.values.addAll(values); - } -} diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/InitializerBean.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/InitializerBean.java deleted file mode 100644 index 8c8634c767..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/InitializerBean.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.value; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -@Component -public class InitializerBean { - - private String someInitialValue; - private String anotherManagedValue; - - public InitializerBean(@Value("someInitialValue") String someInitialValue, @Value("anotherValue") String anotherManagedValue) { - this.someInitialValue = someInitialValue; - this.anotherManagedValue = anotherManagedValue; - } - - public ClassNotManagedBySpring initClass() { - return new ClassNotManagedBySpring(this.someInitialValue, this.anotherManagedValue); - } - -} diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/PriorityProvider.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/PriorityProvider.java deleted file mode 100644 index 9d4b105afa..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/PriorityProvider.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.value; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.PropertySource; -import org.springframework.stereotype.Component; - -@Component -@PropertySource("classpath:values.properties") -public class PriorityProvider { - - private final String priority; - - @Autowired - public PriorityProvider(@Value("${priority:normal}") String priority) { - this.priority = priority; - } - - public String getPriority() { - return priority; - } -} diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/SomeBean.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/SomeBean.java deleted file mode 100644 index 39d5245049..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/SomeBean.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.value; - -public class SomeBean { - private int someValue; - - public SomeBean(int someValue) { - this.someValue = someValue; - } - - public int getSomeValue() { - return someValue; - } - - public void setSomeValue(int someValue) { - this.someValue = someValue; - } -} diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/ValuesApp.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/ValuesApp.java deleted file mode 100644 index 80893c1adf..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/value/ValuesApp.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.baeldung.value; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import javax.annotation.PostConstruct; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; - -@Configuration -@PropertySource(name = "myProperties", value = "values.properties") -public class ValuesApp { - - @Value("string value") - private String stringValue; - - @Value("${value.from.file}") - private String valueFromFile; - - @Value("${systemValue}") - private String systemValue; - - @Value("${unknown_param:some default}") - private String someDefault; - - @Value("${priority}") - private String prioritySystemProperty; - - @Value("${listOfValues}") - private String[] valuesArray; - - @Value("#{systemProperties['priority']}") - private String spelValue; - - @Value("#{systemProperties['unknown'] ?: 'some default'}") - private String spelSomeDefault; - - @Value("#{someBean.someValue}") - private Integer someBeanValue; - - @Value("#{'${listOfValues}'.split(',')}") - private List valuesList; - - @Value("#{${valuesMap}}") - private Map valuesMap; - - @Value("#{${valuesMap}.key1}") - private Integer valuesMapKey1; - - @Value("#{${valuesMap}['unknownKey']}") - private Integer unknownMapKey; - - @Value("#{${unknownMap : {key1:'1', key2 : '2'}}}") - private Map unknownMap; - - @Value("#{${valuesMap}['unknownKey'] ?: 5}") - private Integer unknownMapKeyWithDefaultValue; - - @Value("#{${valuesMap}.?[value>'1']}") - private Map valuesMapFiltered; - - @Value("#{systemProperties}") - private Map systemPropertiesMap; - - public static void main(String[] args) { - System.setProperty("systemValue", "Some system parameter value"); - System.setProperty("priority", "System property"); - ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ValuesApp.class); - } - - @Bean - public SomeBean someBean() { - return new SomeBean(10); - } - - @PostConstruct - public void afterInitialize() { - System.out.println(stringValue); - System.out.println(valueFromFile); - System.out.println(systemValue); - System.out.println(someDefault); - System.out.println(prioritySystemProperty); - System.out.println(Arrays.toString(valuesArray)); - System.out.println(spelValue); - System.out.println(spelSomeDefault); - System.out.println(someBeanValue); - System.out.println(valuesList); - System.out.println(valuesMap); - System.out.println(valuesMapKey1); - System.out.println(unknownMapKey); - System.out.println(unknownMap); - System.out.println(unknownMapKeyWithDefaultValue); - System.out.println(valuesMapFiltered); - System.out.println(systemPropertiesMap); - } -} diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java deleted file mode 100644 index 589f891e6b..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/valuewithdefaults/ValuesWithDefaultsApp.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.valuewithdefaults; - -import java.util.Arrays; -import java.util.List; - -import javax.annotation.PostConstruct; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.util.Assert; - -import com.google.common.collect.Lists; -import com.google.common.primitives.Ints; - -/** - * Demonstrates setting defaults for @Value annotation. Note that there are no properties - * defined in the specified property source. We also assume that the user here - * does not have a system property named some.key. - * - */ -@Configuration -@PropertySource(name = "myProperties", value = "valueswithdefaults.properties") -public class ValuesWithDefaultsApp { - - @Value("${some.key:my default value}") - private String stringWithDefaultValue; - - @Value("${some.key:}") - private String stringWithBlankDefaultValue; - - @Value("${some.key:true}") - private boolean booleanWithDefaultValue; - - @Value("${some.key:42}") - private int intWithDefaultValue; - - @Value("${some.key:one,two,three}") - private String[] stringArrayWithDefaults; - - @Value("${some.key:1,2,3}") - private int[] intArrayWithDefaults; - - @Value("#{systemProperties['some.key'] ?: 'my default system property value'}") - private String spelWithDefaultValue; - - - public static void main(String[] args) { - ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ValuesWithDefaultsApp.class); - } - - @PostConstruct - public void afterInitialize() { - // strings - Assert.isTrue(stringWithDefaultValue.equals("my default value")); - Assert.isTrue(stringWithBlankDefaultValue.equals("")); - - // other primitives - Assert.isTrue(booleanWithDefaultValue); - Assert.isTrue(intWithDefaultValue == 42); - - // arrays - List stringListValues = Lists.newArrayList("one", "two", "three"); - Assert.isTrue(Arrays.asList(stringArrayWithDefaults).containsAll(stringListValues)); - - List intListValues = Lists.newArrayList(1, 2, 3); - Assert.isTrue(Ints.asList(intArrayWithDefaults).containsAll(intListValues)); - - // SpEL - Assert.isTrue(spelWithDefaultValue.equals("my default system property value")); - - } -} diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/values.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/values.properties deleted file mode 100644 index 9c85893d5f..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/main/resources/values.properties +++ /dev/null @@ -1,4 +0,0 @@ -value.from.file=Value got from the file -priority=high -listOfValues=A,B,C -valuesMap={key1:'1', key2 : '2', key3 : '3'} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/valueswithdefaults.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/valueswithdefaults.properties deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/ClassNotManagedBySpringIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/ClassNotManagedBySpringIntegrationTest.java deleted file mode 100644 index 689801bece..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/ClassNotManagedBySpringIntegrationTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.value; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit4.SpringRunner; - -import static junit.framework.TestCase.assertEquals; -import static org.mockito.Mockito.when; - -@RunWith(SpringRunner.class) -public class ClassNotManagedBySpringIntegrationTest { - - @MockBean - private InitializerBean initializerBean; - - @Before - public void init() { - when(initializerBean.initClass()) - .thenReturn(new ClassNotManagedBySpring("This is only sample value", "Another configured value")); - } - - @Test - public void givenInitializerBean_whenInvokedInitClass_shouldInitialize() throws Exception { - - //given - ClassNotManagedBySpring classNotManagedBySpring = initializerBean.initClass(); - - //when - String initializedValue = classNotManagedBySpring.getCustomVariable(); - String anotherCustomVariable = classNotManagedBySpring.getAnotherCustomVariable(); - - //then - assertEquals("This is only sample value", initializedValue); - assertEquals("Another configured value", anotherCustomVariable); - - } - -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/CollectionProviderIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/CollectionProviderIntegrationTest.java deleted file mode 100644 index 33552f2e1a..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/CollectionProviderIntegrationTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.value; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = CollectionProvider.class) -public class CollectionProviderIntegrationTest { - - @Autowired - private CollectionProvider collectionProvider; - - @Test - public void givenPropertyFileWhenSetterInjectionUsedThenValueInjected() { - assertThat(collectionProvider.getValues()).contains("A", "B", "C"); - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/PriorityProviderIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/PriorityProviderIntegrationTest.java deleted file mode 100644 index aa365a4b6a..0000000000 --- a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/value/PriorityProviderIntegrationTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.value; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = PriorityProvider.class) -public class PriorityProviderIntegrationTest { - - @Autowired - private PriorityProvider priorityProvider; - - @Test - public void givenPropertyFileWhenConstructorInjectionUsedThenValueInjected() { - assertThat(priorityProvider.getPriority()).isEqualTo("high"); - } -} \ No newline at end of file From adb8dd9fe2bebd2752b626e9bd811891010d7f87 Mon Sep 17 00:00:00 2001 From: Krzysztof Woyke Date: Wed, 20 May 2020 16:03:49 +0200 Subject: [PATCH 134/150] JAVA-1526: Add pagination to the README files --- spring-boot-modules/spring-boot-properties-2/README.md | 3 ++- spring-boot-modules/spring-boot-properties/README.md | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/spring-boot-modules/spring-boot-properties-2/README.md b/spring-boot-modules/spring-boot-properties-2/README.md index 7373932e4f..cd0fd5e5ee 100644 --- a/spring-boot-modules/spring-boot-properties-2/README.md +++ b/spring-boot-modules/spring-boot-properties-2/README.md @@ -6,4 +6,5 @@ This module contains articles about Properties in Spring Boot. - [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties) - [A Quick Guide to Spring @Value](https://www.baeldung.com/spring-value-annotation) - [Using Spring @Value with Defaults](https://www.baeldung.com/spring-value-defaults) -- [How to Inject a Property Value Into a Class Not Managed by Spring?](https://www.baeldung.com/inject-properties-value-non-spring-class) \ No newline at end of file +- [How to Inject a Property Value Into a Class Not Managed by Spring?](https://www.baeldung.com/inject-properties-value-non-spring-class) +- More articles: [[<-- prev]](../spring-boot-properties) \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/README.md b/spring-boot-modules/spring-boot-properties/README.md index bea3d6a293..b6685c7587 100644 --- a/spring-boot-modules/spring-boot-properties/README.md +++ b/spring-boot-modules/spring-boot-properties/README.md @@ -10,3 +10,4 @@ This module contains articles about Properties in Spring Boot. - [Spring YAML Configuration](https://www.baeldung.com/spring-yaml) - [Add Build Properties to a Spring Boot Application](https://www.baeldung.com/spring-boot-build-properties) - [IntelliJ – Cannot Resolve Spring Boot Configuration Properties Error](https://www.baeldung.com/intellij-resolve-spring-boot-configuration-properties) +- More articles: [[more -->]](../spring-boot-properties-2) \ No newline at end of file From 8b156e0289316112ed4a6b9610664bc5630617e5 Mon Sep 17 00:00:00 2001 From: Sampada <46674082+sampada07@users.noreply.github.com> Date: Wed, 20 May 2020 20:51:55 +0530 Subject: [PATCH 135/150] BAEL-3493: sectioned off new properties specific to this article (#9325) --- .../src/main/resources/application.properties | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties b/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties index 4191d8ba25..7debdc6503 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties @@ -7,5 +7,7 @@ springdoc.api-docs.path=/api-docs # H2 Related Configurations spring.datasource.url=jdbc:h2:mem:springdoc +## for com.baeldung.restdocopenapi ## springdoc.version=@springdoc.version@ -spring.jpa.hibernate.ddl-auto=none \ No newline at end of file +spring.jpa.hibernate.ddl-auto=none +###################################### \ No newline at end of file From 5f8f1873ae94951580c0c0769fd97f5f555ac3ef Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Wed, 20 May 2020 23:21:40 +0530 Subject: [PATCH 136/150] JAVA-941: Migrate spring-jinq to parent-boot-2 --- spring-jinq/pom.xml | 9 ++++++++- spring-jinq/src/main/resources/application.properties | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/spring-jinq/pom.xml b/spring-jinq/pom.xml index 96cff4b886..073808823c 100644 --- a/spring-jinq/pom.xml +++ b/spring-jinq/pom.xml @@ -36,6 +36,12 @@ org.springframework.boot spring-boot-starter-data-jpa + + + net.bytebuddy + byte-buddy-dep + ${bytebuddy.version} + @@ -66,7 +72,8 @@ - 1.8.22 + 1.8.29 + 1.10.10 diff --git a/spring-jinq/src/main/resources/application.properties b/spring-jinq/src/main/resources/application.properties index dc73bed0c5..c9440b3b45 100644 --- a/spring-jinq/src/main/resources/application.properties +++ b/spring-jinq/src/main/resources/application.properties @@ -1,4 +1,4 @@ -spring.datasource.url=jdbc:h2:~/jinq +spring.datasource.url=jdbc:h2:~/jinq;;DB_CLOSE_ON_EXIT=FALSE spring.datasource.username=sa spring.datasource.password= From 8e941329df2caddf76253d3c1a22ff27a3406b17 Mon Sep 17 00:00:00 2001 From: Krzysztof Woyke Date: Wed, 20 May 2020 21:22:30 +0200 Subject: [PATCH 137/150] JAVA-1637: Remove overriden spring-boot.version property --- ddd/pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/ddd/pom.xml b/ddd/pom.xml index 7f3c417b71..1253f2ac48 100644 --- a/ddd/pom.xml +++ b/ddd/pom.xml @@ -96,7 +96,6 @@ 1.0.1 - 2.0.6.RELEASE From dbdb32da463d8a59c92f31c30fb02336d184bb28 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Wed, 29 Apr 2020 10:05:02 +0200 Subject: [PATCH 138/150] [BAEL-3981] Code for article * Equality operators * Object#equals method * Objects#equals static method * Comparable interface * Comparator interface * Apache Commons features * Guava features --- core-java-modules/core-java-lang-2/pom.xml | 9 +- .../java/com/baeldung/comparing/Person.java | 217 ++++++++++++++++++ .../ApacheCommonsObjectUtilsUnitTest.java | 59 +++++ .../ComparableInterfaceUnitTest.java | 107 +++++++++ .../ComparatorInterfaceUnitTest.java | 81 +++++++ .../comparing/EqualityOperatorUnitTest.java | 116 ++++++++++ .../comparing/EqualsMethodUnitTest.java | 73 ++++++ .../com/baeldung/comparing/GuavaUnitTest.java | 80 +++++++ .../ObjectsEqualsStaticMethodUnitTest.java | 50 ++++ 9 files changed, 791 insertions(+), 1 deletion(-) create mode 100644 core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/Person.java create mode 100644 core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ApacheCommonsObjectUtilsUnitTest.java create mode 100644 core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ComparableInterfaceUnitTest.java create mode 100644 core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ComparatorInterfaceUnitTest.java create mode 100644 core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/EqualityOperatorUnitTest.java create mode 100644 core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/EqualsMethodUnitTest.java create mode 100644 core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/GuavaUnitTest.java create mode 100644 core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ObjectsEqualsStaticMethodUnitTest.java diff --git a/core-java-modules/core-java-lang-2/pom.xml b/core-java-modules/core-java-lang-2/pom.xml index 5aa80ce3df..449b700560 100644 --- a/core-java-modules/core-java-lang-2/pom.xml +++ b/core-java-modules/core-java-lang-2/pom.xml @@ -20,7 +20,12 @@ org.apache.commons commons-lang3 - 3.9 + ${commons-lang3.version} + + + com.google.guava + guava + ${guava.version} commons-beanutils @@ -65,6 +70,8 @@ 1.19 3.12.2 1.9.4 + 3.9 + 29.0-jre diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/Person.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/Person.java new file mode 100644 index 0000000000..7c7088a0c7 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/Person.java @@ -0,0 +1,217 @@ +package com.baeldung.comparing; + +import java.time.LocalDate; +import java.util.Comparator; +import java.util.Objects; + +public class Person { + public static class PersonWithoutEquals { + private String firstName; + private String lastName; + + public PersonWithoutEquals(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + } + + public static class PersonWithEquals { + private String firstName; + private String lastName; + private LocalDate birthDate; + + public PersonWithEquals(String firstName, String lastName) { + if (firstName == null || lastName == null) { + throw new NullPointerException("Names can't be null"); + } + this.firstName = firstName; + this.lastName = lastName; + } + + public PersonWithEquals(String firstName, String lastName, LocalDate birthDate) { + this(firstName, lastName); + + this.birthDate = birthDate; + } + + public String firstName() { + return firstName; + } + + public String lastName() { + return lastName; + } + + public LocalDate birthDate() { + return birthDate; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + PersonWithEquals that = (PersonWithEquals) o; + return firstName.equals(that.firstName) && + lastName.equals(that.lastName) && + Objects.equals(birthDate, that.birthDate); + } + + @Override + public int hashCode() { + return Objects.hash(firstName, lastName); + } + } + + public static class PersonWithEqualsAndWrongComparable implements Comparable { + private String firstName; + private String lastName; + private LocalDate birthDate; + + public PersonWithEqualsAndWrongComparable(String firstName, String lastName) { + if (firstName == null || lastName == null) { + throw new NullPointerException("Names can't be null"); + } + this.firstName = firstName; + this.lastName = lastName; + } + + public PersonWithEqualsAndWrongComparable(String firstName, String lastName, LocalDate birthDate) { + this(firstName, lastName); + + this.birthDate = birthDate; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + PersonWithEqualsAndWrongComparable that = (PersonWithEqualsAndWrongComparable) o; + return firstName.equals(that.firstName) && + lastName.equals(that.lastName) && + Objects.equals(birthDate, that.birthDate); + } + + @Override + public int hashCode() { + return Objects.hash(firstName, lastName); + } + + @Override + public int compareTo(PersonWithEqualsAndWrongComparable o) { + return this.lastName.compareTo(o.lastName); + } + } + + public static class PersonWithEqualsAndComparable implements Comparable { + private String firstName; + private String lastName; + private LocalDate birthDate; + + public PersonWithEqualsAndComparable(String firstName, String lastName) { + if (firstName == null || lastName == null) { + throw new NullPointerException("Names can't be null"); + } + this.firstName = firstName; + this.lastName = lastName; + } + + public PersonWithEqualsAndComparable(String firstName, String lastName, LocalDate birthDate) { + this(firstName, lastName); + + this.birthDate = birthDate; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + PersonWithEqualsAndComparable that = (PersonWithEqualsAndComparable) o; + return firstName.equals(that.firstName) && + lastName.equals(that.lastName) && + Objects.equals(birthDate, that.birthDate); + } + + @Override + public int hashCode() { + return Objects.hash(firstName, lastName); + } + + @Override + public int compareTo(PersonWithEqualsAndComparable o) { + int lastNamesComparison = this.lastName.compareTo(o.lastName); + if (lastNamesComparison == 0) { + int firstNamesComparison = this.firstName.compareTo(o.firstName); + if (firstNamesComparison == 0) { + if (this.birthDate != null && o.birthDate != null) { + return this.birthDate.compareTo(o.birthDate); + } else if (this.birthDate != null) { + return 1; + } else if (o.birthDate != null) { + return -1; + } else { + return 0; + } + } else { + return firstNamesComparison; + } + } else { + return lastNamesComparison; + } + } + } + + public static class PersonWithEqualsAndComparableUsingComparator implements Comparable { + private String firstName; + private String lastName; + private LocalDate birthDate; + + public PersonWithEqualsAndComparableUsingComparator(String firstName, String lastName) { + if (firstName == null || lastName == null) { + throw new NullPointerException("Names can't be null"); + } + this.firstName = firstName; + this.lastName = lastName; + } + + public PersonWithEqualsAndComparableUsingComparator(String firstName, String lastName, LocalDate birthDate) { + this(firstName, lastName); + + this.birthDate = birthDate; + } + + public String firstName() { + return firstName; + } + + public String lastName() { + return lastName; + } + + public LocalDate birthDate() { + return birthDate; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + PersonWithEqualsAndComparableUsingComparator that = (PersonWithEqualsAndComparableUsingComparator) o; + return firstName.equals(that.firstName) && + lastName.equals(that.lastName) && + Objects.equals(birthDate, that.birthDate); + } + + @Override + public int hashCode() { + return Objects.hash(firstName, lastName); + } + + @Override + public int compareTo(PersonWithEqualsAndComparableUsingComparator o) { + return Comparator.comparing(PersonWithEqualsAndComparableUsingComparator::lastName) + .thenComparing(PersonWithEqualsAndComparableUsingComparator::firstName) + .thenComparing(PersonWithEqualsAndComparableUsingComparator::birthDate, Comparator.nullsLast(Comparator.naturalOrder())) + .compare(this, o); + } + } +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ApacheCommonsObjectUtilsUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ApacheCommonsObjectUtilsUnitTest.java new file mode 100644 index 0000000000..33b8dcb3fc --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ApacheCommonsObjectUtilsUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.comparing; + +import org.apache.commons.lang3.ObjectUtils; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class ApacheCommonsObjectUtilsUnitTest { + + @Test + void givenTwoStringsWithSameValues_whenApacheCommonsEqualityMethods_thenEqualsTrueNotEqualsFalse() { + String a = new String("Hello!"); + String b = new String("Hello!"); + + assertThat(ObjectUtils.equals(a, b)).isTrue(); + assertThat(ObjectUtils.notEqual(a, b)).isFalse(); + } + + @Test + void givenTwoStringsWithDifferentValues_whenApacheCommonsEqualityMethods_thenEqualsFalseNotEqualsTrue() { + String a = new String("Hello!"); + String b = new String("Hello World!"); + + assertThat(ObjectUtils.equals(a, b)).isFalse(); + assertThat(ObjectUtils.notEqual(a, b)).isTrue(); + } + + @Test + void givenTwoStringsWithConsecutiveValues_whenApacheCommonsCompare_thenNegative() { + String first = new String("Hello!"); + String second = new String("How are you?"); + + assertThat(ObjectUtils.compare(first, second)).isNegative(); + } + + @Test + void givenTwoStringsWithSameValues_whenApacheCommonsEqualityMethods_thenEqualsFalseNotEqualsTrue() { + String first = new String("Hello!"); + String second = new String("Hello!"); + + assertThat(ObjectUtils.compare(first, second)).isZero(); + } + + @Test + void givenTwoStringsWithConsecutiveValues_whenApacheCommonsCompareReversed_thenPositive() { + String first = new String("Hello!"); + String second = new String("How are you?"); + + assertThat(ObjectUtils.compare(second, first)).isPositive(); + } + + @Test + void givenTwoStringsOneNull_whenApacheCommonsCompare_thenPositive() { + String first = new String("Hello!"); + String second = null; + + assertThat(ObjectUtils.compare(first, second, false)).isPositive(); + } +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ComparableInterfaceUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ComparableInterfaceUnitTest.java new file mode 100644 index 0000000000..6e10188852 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ComparableInterfaceUnitTest.java @@ -0,0 +1,107 @@ +package com.baeldung.comparing; + +import org.junit.jupiter.api.Test; + +import java.util.SortedSet; +import java.util.TreeSet; + +import static org.assertj.core.api.Assertions.assertThat; + +class ComparableInterfaceUnitTest { + + @Test + void givenTwoConsecutiveStrings_whenCompareTo_thenNegative() { + String first = "Google"; + String second = "Microsoft"; + + assertThat(first.compareTo(second)).isNegative(); + } + + @Test + void givenTwoEqualsStrings_whenCompareTo_thenZero() { + String first = "Google"; + String second = "Google"; + + assertThat(first.compareTo(second)).isZero(); + } + + @Test + void givenTwoConsecutiveStrings_whenReversedCompareTo_thenPositive() { + String first = "Google"; + String second = "Microsoft"; + + assertThat(second.compareTo(first)).isPositive(); + } + + @Test + void givenTwoPersonWithEqualsAndWrongComparableAndConsecutiveLastNames_whenCompareTo_thenNegative() { + Person.PersonWithEqualsAndWrongComparable richard = new Person.PersonWithEqualsAndWrongComparable("Richard", "Jefferson"); + Person.PersonWithEqualsAndWrongComparable joe = new Person.PersonWithEqualsAndWrongComparable("Joe", "Portman"); + + assertThat(richard.compareTo(joe)).isNegative(); + } + + @Test + void givenTwoPersonWithEqualsAndWrongComparableAndSameLastNames_whenReversedCompareTo_thenZero() { + Person.PersonWithEqualsAndWrongComparable richard = new Person.PersonWithEqualsAndWrongComparable("Richard", "Jefferson"); + Person.PersonWithEqualsAndWrongComparable mike = new Person.PersonWithEqualsAndWrongComparable("Mike", "Jefferson"); + + assertThat(richard.compareTo(mike)).isZero(); + } + + @Test + void givenTwoPersonWithEqualsAndWrongComparableAndConsecutiveLastNames_whenReversedCompareTo_thenPositive() { + Person.PersonWithEqualsAndWrongComparable richard = new Person.PersonWithEqualsAndWrongComparable("Richard", "Jefferson"); + Person.PersonWithEqualsAndWrongComparable joe = new Person.PersonWithEqualsAndWrongComparable("Joe", "Portman"); + + assertThat(joe.compareTo(richard)).isPositive(); + } + + @Test + void givenTwoPersonWithEqualsAndWrongComparableAndSameLastNames_whenSortedSet_thenProblem() { + Person.PersonWithEqualsAndWrongComparable richard = new Person.PersonWithEqualsAndWrongComparable("Richard", "Jefferson"); + Person.PersonWithEqualsAndWrongComparable mike = new Person.PersonWithEqualsAndWrongComparable("Mike", "Jefferson"); + + SortedSet people = new TreeSet<>(); + people.add(richard); + people.add(mike); + + assertThat(people).containsExactly(richard); + } + + @Test + void givenTwoPersonWithEqualsAndComparableAndConsecutiveLastNames_whenCompareTo_thenNegative() { + Person.PersonWithEqualsAndComparable richard = new Person.PersonWithEqualsAndComparable("Richard", "Jefferson"); + Person.PersonWithEqualsAndComparable joe = new Person.PersonWithEqualsAndComparable("Joe", "Portman"); + + assertThat(richard.compareTo(joe)).isNegative(); + } + + @Test + void givenTwoPersonWithEqualsAndComparableAndSameLastNames_whenReversedCompareTo_thenZero() { + Person.PersonWithEqualsAndComparable richard = new Person.PersonWithEqualsAndComparable("Richard", "Jefferson"); + Person.PersonWithEqualsAndComparable mike = new Person.PersonWithEqualsAndComparable("Mike", "Jefferson"); + + assertThat(richard.compareTo(mike)).isPositive(); + } + + @Test + void givenTwoPersonWithEqualsAndComparableAndConsecutiveLastNames_whenReversedCompareTo_thenPositive() { + Person.PersonWithEqualsAndComparable richard = new Person.PersonWithEqualsAndComparable("Richard", "Jefferson"); + Person.PersonWithEqualsAndComparable joe = new Person.PersonWithEqualsAndComparable("Joe", "Portman"); + + assertThat(joe.compareTo(richard)).isPositive(); + } + + @Test + void givenTwoPersonWithEqualsAndComparableAndSameLastNames_whenSortedSet_thenProblem() { + Person.PersonWithEqualsAndComparable richard = new Person.PersonWithEqualsAndComparable("Richard", "Jefferson"); + Person.PersonWithEqualsAndComparable mike = new Person.PersonWithEqualsAndComparable("Mike", "Jefferson"); + + SortedSet people = new TreeSet<>(); + people.add(richard); + people.add(mike); + + assertThat(people).containsExactly(mike, richard); + } +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ComparatorInterfaceUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ComparatorInterfaceUnitTest.java new file mode 100644 index 0000000000..a406b12752 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ComparatorInterfaceUnitTest.java @@ -0,0 +1,81 @@ +package com.baeldung.comparing; + +import org.junit.jupiter.api.Test; + +import java.util.*; + +import static org.assertj.core.api.Assertions.assertThat; + +class ComparatorInterfaceUnitTest { + + @Test + void givenListOfTwoPersonWithEqualsAndComparatorByFirstName_whenSort_thenSortedByFirstNames() { + Person.PersonWithEquals joe = new Person.PersonWithEquals("Joe", "Portman"); + Person.PersonWithEquals allan = new Person.PersonWithEquals("Allan", "Dale"); + + List people = new ArrayList<>(); + people.add(joe); + people.add(allan); + + Comparator compareByFirstNames = new Comparator() { + @Override + public int compare(Person.PersonWithEquals o1, Person.PersonWithEquals o2) { + return o1.firstName().compareTo(o2.firstName()); + } + }; + people.sort(compareByFirstNames); + + assertThat(people).containsExactly(allan, joe); + } + + @Test + void givenListOfTwoPersonWithEqualsAndComparatorByFirstNameFunctionalStyle_whenSort_thenSortedByFirstNames() { + Person.PersonWithEquals joe = new Person.PersonWithEquals("Joe", "Portman"); + Person.PersonWithEquals allan = new Person.PersonWithEquals("Allan", "Dale"); + + List people = new ArrayList<>(); + people.add(joe); + people.add(allan); + + Comparator compareByFirstNames = Comparator.comparing(Person.PersonWithEquals::firstName); + people.sort(compareByFirstNames); + + assertThat(people).containsExactly(allan, joe); + } + + @Test + void givenTwoPersonWithEqualsAndComparableUsingComparatorAndConsecutiveLastNames_whenCompareTo_thenNegative() { + Person.PersonWithEqualsAndComparableUsingComparator richard = new Person.PersonWithEqualsAndComparableUsingComparator("Richard", "Jefferson"); + Person.PersonWithEqualsAndComparableUsingComparator joe = new Person.PersonWithEqualsAndComparableUsingComparator("Joe", "Portman"); + + assertThat(richard.compareTo(joe)).isNegative(); + } + + @Test + void givenTwoPersonWithEqualsAndComparableUsingComparatorAndSameLastNames_whenReversedCompareTo_thenZero() { + Person.PersonWithEqualsAndComparableUsingComparator richard = new Person.PersonWithEqualsAndComparableUsingComparator("Richard", "Jefferson"); + Person.PersonWithEqualsAndComparableUsingComparator mike = new Person.PersonWithEqualsAndComparableUsingComparator("Mike", "Jefferson"); + + assertThat(richard.compareTo(mike)).isPositive(); + } + + @Test + void givenTwoPersonWithEqualsAndComparableUsingComparatorAndConsecutiveLastNames_whenReversedCompareTo_thenPositive() { + Person.PersonWithEqualsAndComparableUsingComparator richard = new Person.PersonWithEqualsAndComparableUsingComparator("Richard", "Jefferson"); + Person.PersonWithEqualsAndComparableUsingComparator joe = new Person.PersonWithEqualsAndComparableUsingComparator("Joe", "Portman"); + + assertThat(joe.compareTo(richard)).isPositive(); + } + + @Test + void givenTwoPersonWithEqualsAndComparableUsingComparatorAndSameLastNames_whenSortedSet_thenProblem() { + Person.PersonWithEqualsAndComparableUsingComparator richard = new Person.PersonWithEqualsAndComparableUsingComparator("Richard", "Jefferson"); + Person.PersonWithEqualsAndComparableUsingComparator mike = new Person.PersonWithEqualsAndComparableUsingComparator("Mike", "Jefferson"); + + SortedSet people = new TreeSet<>(); + people.add(richard); + people.add(mike); + + assertThat(people).containsExactly(mike, richard); + } +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/EqualityOperatorUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/EqualityOperatorUnitTest.java new file mode 100644 index 0000000000..ebcf83ef5b --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/EqualityOperatorUnitTest.java @@ -0,0 +1,116 @@ +package com.baeldung.comparing; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class EqualityOperatorUnitTest { + + @Test + void givenTwoIntsWithSameValues_whenEqualityOperators_thenConsideredSame() { + int a = 1; + int b = 1; + + assertThat(a == b).isTrue(); + assertThat(a != b).isFalse(); + } + + @Test + void givenTwoIntsWithDifferentValues_whenEqualityOperators_thenNotConsideredSame() { + int a = 1; + int b = 2; + + assertThat(a == b).isFalse(); + assertThat(a != b).isTrue(); + } + + @Test + void givenTwoIntsWithSameValuesOneWrapped_whenEqualityOperators_thenConsideredSame() { + int a = 1; + Integer b = new Integer(1); + + assertThat(a == b).isTrue(); + assertThat(a != b).isFalse(); + } + + @Test + void givenTwoIntsWithDifferentValuesOneWrapped_whenEqualityOperators_thenNotConsideredSame() { + int a = 1; + Integer b = new Integer(2); + + assertThat(a == b).isFalse(); + assertThat(a != b).isTrue(); + } + + @Test + void givenTwoIntegersWithSameValues_whenEqualityOperators_thenNotConsideredSame() { + Integer a = new Integer(1); + Integer b = new Integer(1); + + assertThat(a == b).isFalse(); + assertThat(a != b).isTrue(); + } + + @Test + void givenTwoIntegersWithDifferentValues_whenEqualityOperators_thenNotConsideredSame() { + Integer a = new Integer(1); + Integer b = new Integer(2); + + assertThat(a == b).isFalse(); + assertThat(a != b).isTrue(); + } + + @Test + void givenTwoIntegersWithSameReference_whenEqualityOperators_thenConsideredSame() { + Integer a = new Integer(1); + Integer b = a; + + assertThat(a == b).isTrue(); + assertThat(a != b).isFalse(); + } + + @Test + void givenTwoIntegersFromValueOfWithSameValues_whenEqualityOperators_thenConsideredSame() { + Integer a = Integer.valueOf(1); + Integer b = Integer.valueOf(1); + + assertThat(a == b).isTrue(); + assertThat(a != b).isFalse(); + } + + @Test + void givenTwoStringsWithSameValues_whenEqualityOperators_thenNotConsideredSame() { + String a = new String("Hello!"); + String b = new String("Hello!"); + + assertThat(a == b).isFalse(); + assertThat(a != b).isTrue(); + } + + @Test + void givenTwoStringsFromLiteralsWithSameValues_whenEqualityOperators_thenConsideredSame() { + String a = "Hello!"; + String b = "Hello!"; + + assertThat(a == b).isTrue(); + assertThat(a != b).isFalse(); + } + + @Test + void givenTwoNullObjects_whenEqualityOperators_thenConsideredSame() { + Object a = null; + Object b = null; + + assertThat(a == b).isTrue(); + assertThat(a != b).isFalse(); + } + + @Test + void givenTwoObjectsOneNull_whenEqualityOperators_thenNotConsideredSame() { + Object a = null; + Object b = "Hello!"; + + assertThat(a == b).isFalse(); + assertThat(a != b).isTrue(); + } +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/EqualsMethodUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/EqualsMethodUnitTest.java new file mode 100644 index 0000000000..4775bc3de1 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/EqualsMethodUnitTest.java @@ -0,0 +1,73 @@ +package com.baeldung.comparing; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class EqualsMethodUnitTest { + + @Test + void givenTwoIntegersWithSameValue_whenEquals_thenTrue() { + Integer a = new Integer(1); + Integer b = new Integer(1); + + assertThat(a.equals(b)).isTrue(); + } + + @Test + void givenTwoStringsWithSameValue_whenEquals_thenTrue() { + String a = new String("Hello!"); + String b = new String("Hello!"); + + assertThat(a.equals(b)).isTrue(); + } + + @Test + void givenTwoStringsWithDifferentValue_whenEquals_thenFalse() { + String a = new String("Hello!"); + String b = new String("Hello World!"); + + assertThat(a.equals(b)).isFalse(); + } + + @Test + void givenTwoObjectsFirstNull_whenEquals_thenNullPointerExceptionThrown() { + Object a = null; + Object b = new String("Hello!"); + + assertThrows(NullPointerException.class, () -> a.equals(b)); + } + + @Test + void givenTwoObjectsSecondNull_whenEquals_thenFalse() { + Object a = new String("Hello!"); + Object b = null; + + assertThat(a.equals(b)).isFalse(); + } + + @Test + void givenTwoPersonWithoutEqualsWithSameNames_whenEquals_thenFalse() { + Person.PersonWithoutEquals joe = new Person.PersonWithoutEquals("Joe", "Portman"); + Person.PersonWithoutEquals joeAgain = new Person.PersonWithoutEquals("Joe", "Portman"); + + assertThat(joe.equals(joeAgain)).isFalse(); + } + + @Test + void givenTwoPersonWithEqualsWithSameNames_whenEquals_thenTrue() { + Person.PersonWithEquals joe = new Person.PersonWithEquals("Joe", "Portman"); + Person.PersonWithEquals joeAgain = new Person.PersonWithEquals("Joe", "Portman"); + + assertThat(joe.equals(joeAgain)).isTrue(); + } + + @Test + void givenTwoPersonWittEqualsWithDifferentNames_whenEquals_thenFalse() { + Person.PersonWithEquals joe = new Person.PersonWithEquals("Joe", "Portman"); + Person.PersonWithEquals nathalie = new Person.PersonWithEquals("Nathalie", "Portman"); + + assertThat(joe.equals(nathalie)).isFalse(); + } +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/GuavaUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/GuavaUnitTest.java new file mode 100644 index 0000000000..0a4d0dd8d3 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/GuavaUnitTest.java @@ -0,0 +1,80 @@ +package com.baeldung.comparing; + +import com.google.common.base.Objects; +import com.google.common.base.Strings; +import com.google.common.collect.ComparisonChain; +import com.google.common.primitives.Booleans; +import com.google.common.primitives.Bytes; +import com.google.common.primitives.Ints; +import com.google.common.primitives.Shorts; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +class GuavaUnitTest { + + @Nested + class ObjectsEqualMethod { + @Test + void givenTwoStringsWithSameValues_whenObjectsEqualMethods_thenTrue() { + String a = new String("Hello!"); + String b = new String("Hello!"); + + assertThat(Objects.equal(a, b)).isTrue(); + } + + @Test + void givenTwoStringsWithDifferentValues_whenObjectsEqualMethods_thenFalse() { + String a = new String("Hello!"); + String b = new String("Hello World!"); + + assertThat(Objects.equal(a, b)).isFalse(); + } + } + + @Nested + class ComparisonMethods { + @Test + void givenTwoIntsWithConsecutiveValues_whenIntsCompareMethods_thenNegative() { + int first = 1; + int second = 2; + assertThat(Ints.compare(first, second)).isNegative(); + } + + @Test + void givenTwoIntsWithSameValues_whenIntsCompareMethods_thenZero() { + int first = 1; + int second = 1; + + assertThat(Ints.compare(first, second)).isZero(); + } + + @Test + void givenTwoIntsWithConsecutiveValues_whenIntsCompareMethodsReversed_thenNegative() { + int first = 1; + int second = 2; + + assertThat(Ints.compare(second, first)).isPositive(); + } + } + + @Nested + class ComparisonChainClass { + @Test + void givenTwoPersonWithEquals_whenComparisonChainByLastNameThenFirstName_thenSortedJoeFirstAndNathalieSecond() { + Person.PersonWithEquals nathalie = new Person.PersonWithEquals("Nathalie", "Portman"); + Person.PersonWithEquals joe = new Person.PersonWithEquals("Joe", "Portman"); + + int comparisonResult = ComparisonChain.start() + .compare(nathalie.lastName(), joe.lastName()) + .compare(nathalie.firstName(), joe.firstName()) + .result(); + + assertThat(comparisonResult).isPositive(); + } + } +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ObjectsEqualsStaticMethodUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ObjectsEqualsStaticMethodUnitTest.java new file mode 100644 index 0000000000..c26cb4e08c --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ObjectsEqualsStaticMethodUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.comparing; + +import org.junit.jupiter.api.Test; + +import java.util.Objects; + +import static org.assertj.core.api.Assertions.assertThat; + +class ObjectsEqualsStaticMethodUnitTest { + + @Test + void givenTwoPersonWithEqualsWithSameNames_whenObjectsEquals_thenTrue() { + Person.PersonWithEquals joe = new Person.PersonWithEquals("Joe", "Portman"); + Person.PersonWithEquals joeAgain = new Person.PersonWithEquals("Joe", "Portman"); + + assertThat(Objects.equals(joe, joeAgain)).isTrue(); + } + + @Test + void givenTwoPersonWithEqualsWithDifferentNames_whenObjectsEquals_thenFalse() { + Person.PersonWithEquals joe = new Person.PersonWithEquals("Joe", "Portman"); + Person.PersonWithEquals nathalie = new Person.PersonWithEquals("Nathalie", "Portman"); + + assertThat(Objects.equals(joe, nathalie)).isFalse(); + } + + @Test + void givenTwoPersonWithEqualsFirstNull_whenObjectsEquals_thenFalse() { + Person.PersonWithEquals nobody = null; + Person.PersonWithEquals joe = new Person.PersonWithEquals("Joe", "Portman"); + + assertThat(Objects.equals(nobody, joe)).isFalse(); + } + + @Test + void givenTwoObjectsSecondtNull_whenObjectsEquals_thenFalse() { + Person.PersonWithEquals joe = new Person.PersonWithEquals("Joe", "Portman"); + Person.PersonWithEquals nobody = null; + + assertThat(Objects.equals(joe, nobody)).isFalse(); + } + + @Test + void givenTwoObjectsNull_whenObjectsEquals_thenTrue() { + Person.PersonWithEquals nobody = null; + Person.PersonWithEquals nobodyAgain = null; + + assertThat(Objects.equals(nobody, nobodyAgain)).isTrue(); + } +} From 24a88c11ac6eb27cb12249a5e7be574894e1168b Mon Sep 17 00:00:00 2001 From: dupirefr Date: Wed, 13 May 2020 19:17:02 +0200 Subject: [PATCH 139/150] [BAEL-3981] Moved inner classes to upper level --- .../java/com/baeldung/comparing/Person.java | 217 ------------------ .../baeldung/comparing/PersonWithEquals.java | 51 ++++ .../PersonWithEqualsAndComparable.java | 62 +++++ ...ithEqualsAndComparableUsingComparator.java | 60 +++++ .../PersonWithEqualsAndWrongComparable.java | 44 ++++ .../comparing/PersonWithoutEquals.java | 11 + .../ComparableInterfaceUnitTest.java | 36 +-- .../ComparatorInterfaceUnitTest.java | 36 +-- .../comparing/EqualsMethodUnitTest.java | 12 +- .../com/baeldung/comparing/GuavaUnitTest.java | 11 +- .../ObjectsEqualsStaticMethodUnitTest.java | 20 +- 11 files changed, 282 insertions(+), 278 deletions(-) delete mode 100644 core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/Person.java create mode 100644 core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithEquals.java create mode 100644 core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithEqualsAndComparable.java create mode 100644 core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithEqualsAndComparableUsingComparator.java create mode 100644 core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithEqualsAndWrongComparable.java create mode 100644 core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithoutEquals.java diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/Person.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/Person.java deleted file mode 100644 index 7c7088a0c7..0000000000 --- a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/Person.java +++ /dev/null @@ -1,217 +0,0 @@ -package com.baeldung.comparing; - -import java.time.LocalDate; -import java.util.Comparator; -import java.util.Objects; - -public class Person { - public static class PersonWithoutEquals { - private String firstName; - private String lastName; - - public PersonWithoutEquals(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - } - - public static class PersonWithEquals { - private String firstName; - private String lastName; - private LocalDate birthDate; - - public PersonWithEquals(String firstName, String lastName) { - if (firstName == null || lastName == null) { - throw new NullPointerException("Names can't be null"); - } - this.firstName = firstName; - this.lastName = lastName; - } - - public PersonWithEquals(String firstName, String lastName, LocalDate birthDate) { - this(firstName, lastName); - - this.birthDate = birthDate; - } - - public String firstName() { - return firstName; - } - - public String lastName() { - return lastName; - } - - public LocalDate birthDate() { - return birthDate; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - PersonWithEquals that = (PersonWithEquals) o; - return firstName.equals(that.firstName) && - lastName.equals(that.lastName) && - Objects.equals(birthDate, that.birthDate); - } - - @Override - public int hashCode() { - return Objects.hash(firstName, lastName); - } - } - - public static class PersonWithEqualsAndWrongComparable implements Comparable { - private String firstName; - private String lastName; - private LocalDate birthDate; - - public PersonWithEqualsAndWrongComparable(String firstName, String lastName) { - if (firstName == null || lastName == null) { - throw new NullPointerException("Names can't be null"); - } - this.firstName = firstName; - this.lastName = lastName; - } - - public PersonWithEqualsAndWrongComparable(String firstName, String lastName, LocalDate birthDate) { - this(firstName, lastName); - - this.birthDate = birthDate; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - PersonWithEqualsAndWrongComparable that = (PersonWithEqualsAndWrongComparable) o; - return firstName.equals(that.firstName) && - lastName.equals(that.lastName) && - Objects.equals(birthDate, that.birthDate); - } - - @Override - public int hashCode() { - return Objects.hash(firstName, lastName); - } - - @Override - public int compareTo(PersonWithEqualsAndWrongComparable o) { - return this.lastName.compareTo(o.lastName); - } - } - - public static class PersonWithEqualsAndComparable implements Comparable { - private String firstName; - private String lastName; - private LocalDate birthDate; - - public PersonWithEqualsAndComparable(String firstName, String lastName) { - if (firstName == null || lastName == null) { - throw new NullPointerException("Names can't be null"); - } - this.firstName = firstName; - this.lastName = lastName; - } - - public PersonWithEqualsAndComparable(String firstName, String lastName, LocalDate birthDate) { - this(firstName, lastName); - - this.birthDate = birthDate; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - PersonWithEqualsAndComparable that = (PersonWithEqualsAndComparable) o; - return firstName.equals(that.firstName) && - lastName.equals(that.lastName) && - Objects.equals(birthDate, that.birthDate); - } - - @Override - public int hashCode() { - return Objects.hash(firstName, lastName); - } - - @Override - public int compareTo(PersonWithEqualsAndComparable o) { - int lastNamesComparison = this.lastName.compareTo(o.lastName); - if (lastNamesComparison == 0) { - int firstNamesComparison = this.firstName.compareTo(o.firstName); - if (firstNamesComparison == 0) { - if (this.birthDate != null && o.birthDate != null) { - return this.birthDate.compareTo(o.birthDate); - } else if (this.birthDate != null) { - return 1; - } else if (o.birthDate != null) { - return -1; - } else { - return 0; - } - } else { - return firstNamesComparison; - } - } else { - return lastNamesComparison; - } - } - } - - public static class PersonWithEqualsAndComparableUsingComparator implements Comparable { - private String firstName; - private String lastName; - private LocalDate birthDate; - - public PersonWithEqualsAndComparableUsingComparator(String firstName, String lastName) { - if (firstName == null || lastName == null) { - throw new NullPointerException("Names can't be null"); - } - this.firstName = firstName; - this.lastName = lastName; - } - - public PersonWithEqualsAndComparableUsingComparator(String firstName, String lastName, LocalDate birthDate) { - this(firstName, lastName); - - this.birthDate = birthDate; - } - - public String firstName() { - return firstName; - } - - public String lastName() { - return lastName; - } - - public LocalDate birthDate() { - return birthDate; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - PersonWithEqualsAndComparableUsingComparator that = (PersonWithEqualsAndComparableUsingComparator) o; - return firstName.equals(that.firstName) && - lastName.equals(that.lastName) && - Objects.equals(birthDate, that.birthDate); - } - - @Override - public int hashCode() { - return Objects.hash(firstName, lastName); - } - - @Override - public int compareTo(PersonWithEqualsAndComparableUsingComparator o) { - return Comparator.comparing(PersonWithEqualsAndComparableUsingComparator::lastName) - .thenComparing(PersonWithEqualsAndComparableUsingComparator::firstName) - .thenComparing(PersonWithEqualsAndComparableUsingComparator::birthDate, Comparator.nullsLast(Comparator.naturalOrder())) - .compare(this, o); - } - } -} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithEquals.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithEquals.java new file mode 100644 index 0000000000..e3a61fc05a --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithEquals.java @@ -0,0 +1,51 @@ +package com.baeldung.comparing; + +import java.time.LocalDate; +import java.util.Objects; + +public class PersonWithEquals { + private String firstName; + private String lastName; + private LocalDate birthDate; + + public PersonWithEquals(String firstName, String lastName) { + if (firstName == null || lastName == null) { + throw new NullPointerException("Names can't be null"); + } + this.firstName = firstName; + this.lastName = lastName; + } + + public PersonWithEquals(String firstName, String lastName, LocalDate birthDate) { + this(firstName, lastName); + + this.birthDate = birthDate; + } + + public String firstName() { + return firstName; + } + + public String lastName() { + return lastName; + } + + public LocalDate birthDate() { + return birthDate; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + PersonWithEquals that = (PersonWithEquals) o; + return firstName.equals(that.firstName) && + lastName.equals(that.lastName) && + Objects.equals(birthDate, that.birthDate); + } + + @Override + public int hashCode() { + return Objects.hash(firstName, lastName); + } +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithEqualsAndComparable.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithEqualsAndComparable.java new file mode 100644 index 0000000000..5611ce8a09 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithEqualsAndComparable.java @@ -0,0 +1,62 @@ +package com.baeldung.comparing; + +import java.time.LocalDate; +import java.util.Objects; + +public class PersonWithEqualsAndComparable implements Comparable { + private String firstName; + private String lastName; + private LocalDate birthDate; + + public PersonWithEqualsAndComparable(String firstName, String lastName) { + if (firstName == null || lastName == null) { + throw new NullPointerException("Names can't be null"); + } + this.firstName = firstName; + this.lastName = lastName; + } + + public PersonWithEqualsAndComparable(String firstName, String lastName, LocalDate birthDate) { + this(firstName, lastName); + + this.birthDate = birthDate; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + PersonWithEqualsAndComparable that = (PersonWithEqualsAndComparable) o; + return firstName.equals(that.firstName) && + lastName.equals(that.lastName) && + Objects.equals(birthDate, that.birthDate); + } + + @Override + public int hashCode() { + return Objects.hash(firstName, lastName); + } + + @Override + public int compareTo(PersonWithEqualsAndComparable o) { + int lastNamesComparison = this.lastName.compareTo(o.lastName); + if (lastNamesComparison == 0) { + int firstNamesComparison = this.firstName.compareTo(o.firstName); + if (firstNamesComparison == 0) { + if (this.birthDate != null && o.birthDate != null) { + return this.birthDate.compareTo(o.birthDate); + } else if (this.birthDate != null) { + return 1; + } else if (o.birthDate != null) { + return -1; + } else { + return 0; + } + } else { + return firstNamesComparison; + } + } else { + return lastNamesComparison; + } + } +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithEqualsAndComparableUsingComparator.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithEqualsAndComparableUsingComparator.java new file mode 100644 index 0000000000..ed322cb353 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithEqualsAndComparableUsingComparator.java @@ -0,0 +1,60 @@ +package com.baeldung.comparing; + +import java.time.LocalDate; +import java.util.Comparator; +import java.util.Objects; + +public class PersonWithEqualsAndComparableUsingComparator implements Comparable { + private String firstName; + private String lastName; + private LocalDate birthDate; + + public PersonWithEqualsAndComparableUsingComparator(String firstName, String lastName) { + if (firstName == null || lastName == null) { + throw new NullPointerException("Names can't be null"); + } + this.firstName = firstName; + this.lastName = lastName; + } + + public PersonWithEqualsAndComparableUsingComparator(String firstName, String lastName, LocalDate birthDate) { + this(firstName, lastName); + + this.birthDate = birthDate; + } + + public String firstName() { + return firstName; + } + + public String lastName() { + return lastName; + } + + public LocalDate birthDate() { + return birthDate; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + PersonWithEqualsAndComparableUsingComparator that = (PersonWithEqualsAndComparableUsingComparator) o; + return firstName.equals(that.firstName) && + lastName.equals(that.lastName) && + Objects.equals(birthDate, that.birthDate); + } + + @Override + public int hashCode() { + return Objects.hash(firstName, lastName); + } + + @Override + public int compareTo(PersonWithEqualsAndComparableUsingComparator o) { + return Comparator.comparing(PersonWithEqualsAndComparableUsingComparator::lastName) + .thenComparing(PersonWithEqualsAndComparableUsingComparator::firstName) + .thenComparing(PersonWithEqualsAndComparableUsingComparator::birthDate, Comparator.nullsLast(Comparator.naturalOrder())) + .compare(this, o); + } +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithEqualsAndWrongComparable.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithEqualsAndWrongComparable.java new file mode 100644 index 0000000000..e0bdaa413a --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithEqualsAndWrongComparable.java @@ -0,0 +1,44 @@ +package com.baeldung.comparing; + +import java.time.LocalDate; +import java.util.Objects; + +public class PersonWithEqualsAndWrongComparable implements Comparable { + private String firstName; + private String lastName; + private LocalDate birthDate; + + public PersonWithEqualsAndWrongComparable(String firstName, String lastName) { + if (firstName == null || lastName == null) { + throw new NullPointerException("Names can't be null"); + } + this.firstName = firstName; + this.lastName = lastName; + } + + public PersonWithEqualsAndWrongComparable(String firstName, String lastName, LocalDate birthDate) { + this(firstName, lastName); + + this.birthDate = birthDate; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + PersonWithEqualsAndWrongComparable that = (PersonWithEqualsAndWrongComparable) o; + return firstName.equals(that.firstName) && + lastName.equals(that.lastName) && + Objects.equals(birthDate, that.birthDate); + } + + @Override + public int hashCode() { + return Objects.hash(firstName, lastName); + } + + @Override + public int compareTo(PersonWithEqualsAndWrongComparable o) { + return this.lastName.compareTo(o.lastName); + } +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithoutEquals.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithoutEquals.java new file mode 100644 index 0000000000..bb4c6b958b --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/comparing/PersonWithoutEquals.java @@ -0,0 +1,11 @@ +package com.baeldung.comparing; + +public class PersonWithoutEquals { + private String firstName; + private String lastName; + + public PersonWithoutEquals(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } +} diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ComparableInterfaceUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ComparableInterfaceUnitTest.java index 6e10188852..281c4a0201 100644 --- a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ComparableInterfaceUnitTest.java +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ComparableInterfaceUnitTest.java @@ -35,34 +35,34 @@ class ComparableInterfaceUnitTest { @Test void givenTwoPersonWithEqualsAndWrongComparableAndConsecutiveLastNames_whenCompareTo_thenNegative() { - Person.PersonWithEqualsAndWrongComparable richard = new Person.PersonWithEqualsAndWrongComparable("Richard", "Jefferson"); - Person.PersonWithEqualsAndWrongComparable joe = new Person.PersonWithEqualsAndWrongComparable("Joe", "Portman"); + PersonWithEqualsAndWrongComparable richard = new PersonWithEqualsAndWrongComparable("Richard", "Jefferson"); + PersonWithEqualsAndWrongComparable joe = new PersonWithEqualsAndWrongComparable("Joe", "Portman"); assertThat(richard.compareTo(joe)).isNegative(); } @Test void givenTwoPersonWithEqualsAndWrongComparableAndSameLastNames_whenReversedCompareTo_thenZero() { - Person.PersonWithEqualsAndWrongComparable richard = new Person.PersonWithEqualsAndWrongComparable("Richard", "Jefferson"); - Person.PersonWithEqualsAndWrongComparable mike = new Person.PersonWithEqualsAndWrongComparable("Mike", "Jefferson"); + PersonWithEqualsAndWrongComparable richard = new PersonWithEqualsAndWrongComparable("Richard", "Jefferson"); + PersonWithEqualsAndWrongComparable mike = new PersonWithEqualsAndWrongComparable("Mike", "Jefferson"); assertThat(richard.compareTo(mike)).isZero(); } @Test void givenTwoPersonWithEqualsAndWrongComparableAndConsecutiveLastNames_whenReversedCompareTo_thenPositive() { - Person.PersonWithEqualsAndWrongComparable richard = new Person.PersonWithEqualsAndWrongComparable("Richard", "Jefferson"); - Person.PersonWithEqualsAndWrongComparable joe = new Person.PersonWithEqualsAndWrongComparable("Joe", "Portman"); + PersonWithEqualsAndWrongComparable richard = new PersonWithEqualsAndWrongComparable("Richard", "Jefferson"); + PersonWithEqualsAndWrongComparable joe = new PersonWithEqualsAndWrongComparable("Joe", "Portman"); assertThat(joe.compareTo(richard)).isPositive(); } @Test void givenTwoPersonWithEqualsAndWrongComparableAndSameLastNames_whenSortedSet_thenProblem() { - Person.PersonWithEqualsAndWrongComparable richard = new Person.PersonWithEqualsAndWrongComparable("Richard", "Jefferson"); - Person.PersonWithEqualsAndWrongComparable mike = new Person.PersonWithEqualsAndWrongComparable("Mike", "Jefferson"); + PersonWithEqualsAndWrongComparable richard = new PersonWithEqualsAndWrongComparable("Richard", "Jefferson"); + PersonWithEqualsAndWrongComparable mike = new PersonWithEqualsAndWrongComparable("Mike", "Jefferson"); - SortedSet people = new TreeSet<>(); + SortedSet people = new TreeSet<>(); people.add(richard); people.add(mike); @@ -71,34 +71,34 @@ class ComparableInterfaceUnitTest { @Test void givenTwoPersonWithEqualsAndComparableAndConsecutiveLastNames_whenCompareTo_thenNegative() { - Person.PersonWithEqualsAndComparable richard = new Person.PersonWithEqualsAndComparable("Richard", "Jefferson"); - Person.PersonWithEqualsAndComparable joe = new Person.PersonWithEqualsAndComparable("Joe", "Portman"); + PersonWithEqualsAndComparable richard = new PersonWithEqualsAndComparable("Richard", "Jefferson"); + PersonWithEqualsAndComparable joe = new PersonWithEqualsAndComparable("Joe", "Portman"); assertThat(richard.compareTo(joe)).isNegative(); } @Test void givenTwoPersonWithEqualsAndComparableAndSameLastNames_whenReversedCompareTo_thenZero() { - Person.PersonWithEqualsAndComparable richard = new Person.PersonWithEqualsAndComparable("Richard", "Jefferson"); - Person.PersonWithEqualsAndComparable mike = new Person.PersonWithEqualsAndComparable("Mike", "Jefferson"); + PersonWithEqualsAndComparable richard = new PersonWithEqualsAndComparable("Richard", "Jefferson"); + PersonWithEqualsAndComparable mike = new PersonWithEqualsAndComparable("Mike", "Jefferson"); assertThat(richard.compareTo(mike)).isPositive(); } @Test void givenTwoPersonWithEqualsAndComparableAndConsecutiveLastNames_whenReversedCompareTo_thenPositive() { - Person.PersonWithEqualsAndComparable richard = new Person.PersonWithEqualsAndComparable("Richard", "Jefferson"); - Person.PersonWithEqualsAndComparable joe = new Person.PersonWithEqualsAndComparable("Joe", "Portman"); + PersonWithEqualsAndComparable richard = new PersonWithEqualsAndComparable("Richard", "Jefferson"); + PersonWithEqualsAndComparable joe = new PersonWithEqualsAndComparable("Joe", "Portman"); assertThat(joe.compareTo(richard)).isPositive(); } @Test void givenTwoPersonWithEqualsAndComparableAndSameLastNames_whenSortedSet_thenProblem() { - Person.PersonWithEqualsAndComparable richard = new Person.PersonWithEqualsAndComparable("Richard", "Jefferson"); - Person.PersonWithEqualsAndComparable mike = new Person.PersonWithEqualsAndComparable("Mike", "Jefferson"); + PersonWithEqualsAndComparable richard = new PersonWithEqualsAndComparable("Richard", "Jefferson"); + PersonWithEqualsAndComparable mike = new PersonWithEqualsAndComparable("Mike", "Jefferson"); - SortedSet people = new TreeSet<>(); + SortedSet people = new TreeSet<>(); people.add(richard); people.add(mike); diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ComparatorInterfaceUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ComparatorInterfaceUnitTest.java index a406b12752..769ae60bed 100644 --- a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ComparatorInterfaceUnitTest.java +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ComparatorInterfaceUnitTest.java @@ -10,16 +10,16 @@ class ComparatorInterfaceUnitTest { @Test void givenListOfTwoPersonWithEqualsAndComparatorByFirstName_whenSort_thenSortedByFirstNames() { - Person.PersonWithEquals joe = new Person.PersonWithEquals("Joe", "Portman"); - Person.PersonWithEquals allan = new Person.PersonWithEquals("Allan", "Dale"); + PersonWithEquals joe = new PersonWithEquals("Joe", "Portman"); + PersonWithEquals allan = new PersonWithEquals("Allan", "Dale"); - List people = new ArrayList<>(); + List people = new ArrayList<>(); people.add(joe); people.add(allan); - Comparator compareByFirstNames = new Comparator() { + Comparator compareByFirstNames = new Comparator() { @Override - public int compare(Person.PersonWithEquals o1, Person.PersonWithEquals o2) { + public int compare(PersonWithEquals o1, PersonWithEquals o2) { return o1.firstName().compareTo(o2.firstName()); } }; @@ -30,14 +30,14 @@ class ComparatorInterfaceUnitTest { @Test void givenListOfTwoPersonWithEqualsAndComparatorByFirstNameFunctionalStyle_whenSort_thenSortedByFirstNames() { - Person.PersonWithEquals joe = new Person.PersonWithEquals("Joe", "Portman"); - Person.PersonWithEquals allan = new Person.PersonWithEquals("Allan", "Dale"); + PersonWithEquals joe = new PersonWithEquals("Joe", "Portman"); + PersonWithEquals allan = new PersonWithEquals("Allan", "Dale"); - List people = new ArrayList<>(); + List people = new ArrayList<>(); people.add(joe); people.add(allan); - Comparator compareByFirstNames = Comparator.comparing(Person.PersonWithEquals::firstName); + Comparator compareByFirstNames = Comparator.comparing(PersonWithEquals::firstName); people.sort(compareByFirstNames); assertThat(people).containsExactly(allan, joe); @@ -45,34 +45,34 @@ class ComparatorInterfaceUnitTest { @Test void givenTwoPersonWithEqualsAndComparableUsingComparatorAndConsecutiveLastNames_whenCompareTo_thenNegative() { - Person.PersonWithEqualsAndComparableUsingComparator richard = new Person.PersonWithEqualsAndComparableUsingComparator("Richard", "Jefferson"); - Person.PersonWithEqualsAndComparableUsingComparator joe = new Person.PersonWithEqualsAndComparableUsingComparator("Joe", "Portman"); + PersonWithEqualsAndComparableUsingComparator richard = new PersonWithEqualsAndComparableUsingComparator("Richard", "Jefferson"); + PersonWithEqualsAndComparableUsingComparator joe = new PersonWithEqualsAndComparableUsingComparator("Joe", "Portman"); assertThat(richard.compareTo(joe)).isNegative(); } @Test void givenTwoPersonWithEqualsAndComparableUsingComparatorAndSameLastNames_whenReversedCompareTo_thenZero() { - Person.PersonWithEqualsAndComparableUsingComparator richard = new Person.PersonWithEqualsAndComparableUsingComparator("Richard", "Jefferson"); - Person.PersonWithEqualsAndComparableUsingComparator mike = new Person.PersonWithEqualsAndComparableUsingComparator("Mike", "Jefferson"); + PersonWithEqualsAndComparableUsingComparator richard = new PersonWithEqualsAndComparableUsingComparator("Richard", "Jefferson"); + PersonWithEqualsAndComparableUsingComparator mike = new PersonWithEqualsAndComparableUsingComparator("Mike", "Jefferson"); assertThat(richard.compareTo(mike)).isPositive(); } @Test void givenTwoPersonWithEqualsAndComparableUsingComparatorAndConsecutiveLastNames_whenReversedCompareTo_thenPositive() { - Person.PersonWithEqualsAndComparableUsingComparator richard = new Person.PersonWithEqualsAndComparableUsingComparator("Richard", "Jefferson"); - Person.PersonWithEqualsAndComparableUsingComparator joe = new Person.PersonWithEqualsAndComparableUsingComparator("Joe", "Portman"); + PersonWithEqualsAndComparableUsingComparator richard = new PersonWithEqualsAndComparableUsingComparator("Richard", "Jefferson"); + PersonWithEqualsAndComparableUsingComparator joe = new PersonWithEqualsAndComparableUsingComparator("Joe", "Portman"); assertThat(joe.compareTo(richard)).isPositive(); } @Test void givenTwoPersonWithEqualsAndComparableUsingComparatorAndSameLastNames_whenSortedSet_thenProblem() { - Person.PersonWithEqualsAndComparableUsingComparator richard = new Person.PersonWithEqualsAndComparableUsingComparator("Richard", "Jefferson"); - Person.PersonWithEqualsAndComparableUsingComparator mike = new Person.PersonWithEqualsAndComparableUsingComparator("Mike", "Jefferson"); + PersonWithEqualsAndComparableUsingComparator richard = new PersonWithEqualsAndComparableUsingComparator("Richard", "Jefferson"); + PersonWithEqualsAndComparableUsingComparator mike = new PersonWithEqualsAndComparableUsingComparator("Mike", "Jefferson"); - SortedSet people = new TreeSet<>(); + SortedSet people = new TreeSet<>(); people.add(richard); people.add(mike); diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/EqualsMethodUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/EqualsMethodUnitTest.java index 4775bc3de1..6ae243c0ff 100644 --- a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/EqualsMethodUnitTest.java +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/EqualsMethodUnitTest.java @@ -49,24 +49,24 @@ class EqualsMethodUnitTest { @Test void givenTwoPersonWithoutEqualsWithSameNames_whenEquals_thenFalse() { - Person.PersonWithoutEquals joe = new Person.PersonWithoutEquals("Joe", "Portman"); - Person.PersonWithoutEquals joeAgain = new Person.PersonWithoutEquals("Joe", "Portman"); + PersonWithoutEquals joe = new PersonWithoutEquals("Joe", "Portman"); + PersonWithoutEquals joeAgain = new PersonWithoutEquals("Joe", "Portman"); assertThat(joe.equals(joeAgain)).isFalse(); } @Test void givenTwoPersonWithEqualsWithSameNames_whenEquals_thenTrue() { - Person.PersonWithEquals joe = new Person.PersonWithEquals("Joe", "Portman"); - Person.PersonWithEquals joeAgain = new Person.PersonWithEquals("Joe", "Portman"); + PersonWithEquals joe = new PersonWithEquals("Joe", "Portman"); + PersonWithEquals joeAgain = new PersonWithEquals("Joe", "Portman"); assertThat(joe.equals(joeAgain)).isTrue(); } @Test void givenTwoPersonWittEqualsWithDifferentNames_whenEquals_thenFalse() { - Person.PersonWithEquals joe = new Person.PersonWithEquals("Joe", "Portman"); - Person.PersonWithEquals nathalie = new Person.PersonWithEquals("Nathalie", "Portman"); + PersonWithEquals joe = new PersonWithEquals("Joe", "Portman"); + PersonWithEquals nathalie = new PersonWithEquals("Nathalie", "Portman"); assertThat(joe.equals(nathalie)).isFalse(); } diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/GuavaUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/GuavaUnitTest.java index 0a4d0dd8d3..42d3a606a0 100644 --- a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/GuavaUnitTest.java +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/GuavaUnitTest.java @@ -1,18 +1,11 @@ package com.baeldung.comparing; import com.google.common.base.Objects; -import com.google.common.base.Strings; import com.google.common.collect.ComparisonChain; -import com.google.common.primitives.Booleans; -import com.google.common.primitives.Bytes; import com.google.common.primitives.Ints; -import com.google.common.primitives.Shorts; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; class GuavaUnitTest { @@ -66,8 +59,8 @@ class GuavaUnitTest { class ComparisonChainClass { @Test void givenTwoPersonWithEquals_whenComparisonChainByLastNameThenFirstName_thenSortedJoeFirstAndNathalieSecond() { - Person.PersonWithEquals nathalie = new Person.PersonWithEquals("Nathalie", "Portman"); - Person.PersonWithEquals joe = new Person.PersonWithEquals("Joe", "Portman"); + PersonWithEquals nathalie = new PersonWithEquals("Nathalie", "Portman"); + PersonWithEquals joe = new PersonWithEquals("Joe", "Portman"); int comparisonResult = ComparisonChain.start() .compare(nathalie.lastName(), joe.lastName()) diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ObjectsEqualsStaticMethodUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ObjectsEqualsStaticMethodUnitTest.java index c26cb4e08c..0e24305d87 100644 --- a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ObjectsEqualsStaticMethodUnitTest.java +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ObjectsEqualsStaticMethodUnitTest.java @@ -10,40 +10,40 @@ class ObjectsEqualsStaticMethodUnitTest { @Test void givenTwoPersonWithEqualsWithSameNames_whenObjectsEquals_thenTrue() { - Person.PersonWithEquals joe = new Person.PersonWithEquals("Joe", "Portman"); - Person.PersonWithEquals joeAgain = new Person.PersonWithEquals("Joe", "Portman"); + PersonWithEquals joe = new PersonWithEquals("Joe", "Portman"); + PersonWithEquals joeAgain = new PersonWithEquals("Joe", "Portman"); assertThat(Objects.equals(joe, joeAgain)).isTrue(); } @Test void givenTwoPersonWithEqualsWithDifferentNames_whenObjectsEquals_thenFalse() { - Person.PersonWithEquals joe = new Person.PersonWithEquals("Joe", "Portman"); - Person.PersonWithEquals nathalie = new Person.PersonWithEquals("Nathalie", "Portman"); + PersonWithEquals joe = new PersonWithEquals("Joe", "Portman"); + PersonWithEquals nathalie = new PersonWithEquals("Nathalie", "Portman"); assertThat(Objects.equals(joe, nathalie)).isFalse(); } @Test void givenTwoPersonWithEqualsFirstNull_whenObjectsEquals_thenFalse() { - Person.PersonWithEquals nobody = null; - Person.PersonWithEquals joe = new Person.PersonWithEquals("Joe", "Portman"); + PersonWithEquals nobody = null; + PersonWithEquals joe = new PersonWithEquals("Joe", "Portman"); assertThat(Objects.equals(nobody, joe)).isFalse(); } @Test void givenTwoObjectsSecondtNull_whenObjectsEquals_thenFalse() { - Person.PersonWithEquals joe = new Person.PersonWithEquals("Joe", "Portman"); - Person.PersonWithEquals nobody = null; + PersonWithEquals joe = new PersonWithEquals("Joe", "Portman"); + PersonWithEquals nobody = null; assertThat(Objects.equals(joe, nobody)).isFalse(); } @Test void givenTwoObjectsNull_whenObjectsEquals_thenTrue() { - Person.PersonWithEquals nobody = null; - Person.PersonWithEquals nobodyAgain = null; + PersonWithEquals nobody = null; + PersonWithEquals nobodyAgain = null; assertThat(Objects.equals(nobody, nobodyAgain)).isTrue(); } From a990d574074ca020cd1cbb1ae97668e5bfb76537 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Wed, 20 May 2020 23:33:04 +0200 Subject: [PATCH 140/150] [BAEL-3981] Fixes from Josh's review * Upgraded Apache Commons to 3.10 * Replaced Nathalie by Natalie --- core-java-modules/core-java-lang-2/pom.xml | 2 +- .../java/com/baeldung/comparing/EqualsMethodUnitTest.java | 4 ++-- .../test/java/com/baeldung/comparing/GuavaUnitTest.java | 8 ++++---- .../comparing/ObjectsEqualsStaticMethodUnitTest.java | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/core-java-modules/core-java-lang-2/pom.xml b/core-java-modules/core-java-lang-2/pom.xml index 449b700560..21a63d8091 100644 --- a/core-java-modules/core-java-lang-2/pom.xml +++ b/core-java-modules/core-java-lang-2/pom.xml @@ -70,7 +70,7 @@ 1.19 3.12.2 1.9.4 - 3.9 + 3.10 29.0-jre diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/EqualsMethodUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/EqualsMethodUnitTest.java index 6ae243c0ff..a69ac38916 100644 --- a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/EqualsMethodUnitTest.java +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/EqualsMethodUnitTest.java @@ -66,8 +66,8 @@ class EqualsMethodUnitTest { @Test void givenTwoPersonWittEqualsWithDifferentNames_whenEquals_thenFalse() { PersonWithEquals joe = new PersonWithEquals("Joe", "Portman"); - PersonWithEquals nathalie = new PersonWithEquals("Nathalie", "Portman"); + PersonWithEquals natalie = new PersonWithEquals("Natalie", "Portman"); - assertThat(joe.equals(nathalie)).isFalse(); + assertThat(joe.equals(natalie)).isFalse(); } } diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/GuavaUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/GuavaUnitTest.java index 42d3a606a0..5c8591e134 100644 --- a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/GuavaUnitTest.java +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/GuavaUnitTest.java @@ -58,13 +58,13 @@ class GuavaUnitTest { @Nested class ComparisonChainClass { @Test - void givenTwoPersonWithEquals_whenComparisonChainByLastNameThenFirstName_thenSortedJoeFirstAndNathalieSecond() { - PersonWithEquals nathalie = new PersonWithEquals("Nathalie", "Portman"); + void givenTwoPersonWithEquals_whenComparisonChainByLastNameThenFirstName_thenSortedJoeFirstAndNatalieSecond() { + PersonWithEquals natalie = new PersonWithEquals("Natalie", "Portman"); PersonWithEquals joe = new PersonWithEquals("Joe", "Portman"); int comparisonResult = ComparisonChain.start() - .compare(nathalie.lastName(), joe.lastName()) - .compare(nathalie.firstName(), joe.firstName()) + .compare(natalie.lastName(), joe.lastName()) + .compare(natalie.firstName(), joe.firstName()) .result(); assertThat(comparisonResult).isPositive(); diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ObjectsEqualsStaticMethodUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ObjectsEqualsStaticMethodUnitTest.java index 0e24305d87..5ac89da2be 100644 --- a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ObjectsEqualsStaticMethodUnitTest.java +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparing/ObjectsEqualsStaticMethodUnitTest.java @@ -19,9 +19,9 @@ class ObjectsEqualsStaticMethodUnitTest { @Test void givenTwoPersonWithEqualsWithDifferentNames_whenObjectsEquals_thenFalse() { PersonWithEquals joe = new PersonWithEquals("Joe", "Portman"); - PersonWithEquals nathalie = new PersonWithEquals("Nathalie", "Portman"); + PersonWithEquals natalie = new PersonWithEquals("Natalie", "Portman"); - assertThat(Objects.equals(joe, nathalie)).isFalse(); + assertThat(Objects.equals(joe, natalie)).isFalse(); } @Test From 92c446ce4cc444f865ef4bd53b8876344647ba68 Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Thu, 21 May 2020 21:25:37 +0430 Subject: [PATCH 141/150] Adding Super Type Token --- .../com/baeldung/supertype/TypeReference.java | 18 ++++++++++++++ .../supertype/TypeReferenceUnitTest.java | 24 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/supertype/TypeReference.java create mode 100644 core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/supertype/TypeReferenceUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/supertype/TypeReference.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/supertype/TypeReference.java new file mode 100644 index 0000000000..2021f42239 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/supertype/TypeReference.java @@ -0,0 +1,18 @@ +package com.baeldung.supertype; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +public abstract class TypeReference { + + private final Type type; + + public TypeReference() { + Type superclass = getClass().getGenericSuperclass(); + type = ((ParameterizedType) superclass).getActualTypeArguments()[0]; + } + + public Type getType() { + return type; + } +} diff --git a/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/supertype/TypeReferenceUnitTest.java b/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/supertype/TypeReferenceUnitTest.java new file mode 100644 index 0000000000..24e3b698e2 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/supertype/TypeReferenceUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.supertype; + +import org.junit.Test; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +public class TypeReferenceUnitTest { + + @Test + public void givenGenericToken_whenUsingSuperTypeToken_thenPreservesTheTypeInfo() { + TypeReference> token = new TypeReference>() {}; + Type type = token.getType(); + + assertEquals("java.util.Map", type.getTypeName()); + + Type[] typeArguments = ((ParameterizedType) type).getActualTypeArguments(); + assertEquals("java.lang.String", typeArguments[0].getTypeName()); + assertEquals("java.lang.Integer", typeArguments[1].getTypeName()); + } +} From e8531ef7c289ac94d92861bedfdd35d663bb1a7b Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Fri, 22 May 2020 12:08:56 +0530 Subject: [PATCH 142/150] JAVA-939: Migrate spring-data-rest-querydsl to parent-boot-2 --- spring-data-rest-querydsl/pom.xml | 4 ++-- .../com/baeldung/controller/repository/AddressRepository.java | 4 ++-- .../com/baeldung/controller/repository/UserRepository.java | 4 ++-- .../com/baeldung/springdatarestquerydsl/IntegrationTest.java | 4 +--- .../springdatarestquerydsl/QuerydslIntegrationTest.java | 4 +--- 5 files changed, 8 insertions(+), 12 deletions(-) diff --git a/spring-data-rest-querydsl/pom.xml b/spring-data-rest-querydsl/pom.xml index c0ad43fe0b..5e47f4979e 100644 --- a/spring-data-rest-querydsl/pom.xml +++ b/spring-data-rest-querydsl/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/AddressRepository.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/AddressRepository.java index 2e88820c98..476a11ea6b 100644 --- a/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/AddressRepository.java +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/AddressRepository.java @@ -5,13 +5,13 @@ import com.baeldung.entity.QAddress; import com.querydsl.core.types.dsl.StringExpression; import com.querydsl.core.types.dsl.StringPath; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer; import org.springframework.data.querydsl.binding.QuerydslBindings; import org.springframework.data.querydsl.binding.SingleValueBinding; public interface AddressRepository - extends JpaRepository, QueryDslPredicateExecutor
, QuerydslBinderCustomizer { + extends JpaRepository, QuerydslPredicateExecutor
, QuerydslBinderCustomizer { @Override default void customize(final QuerydslBindings bindings, final QAddress root) { bindings.bind(String.class).first((SingleValueBinding) StringExpression::eq); diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/UserRepository.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/UserRepository.java index 98ff2ac5e3..b5f32b3624 100644 --- a/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/UserRepository.java +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/UserRepository.java @@ -5,13 +5,13 @@ import com.baeldung.entity.User; import com.querydsl.core.types.dsl.StringExpression; import com.querydsl.core.types.dsl.StringPath; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.QuerydslPredicateExecutor; import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer; import org.springframework.data.querydsl.binding.QuerydslBindings; import org.springframework.data.querydsl.binding.SingleValueBinding; public interface UserRepository - extends JpaRepository, QueryDslPredicateExecutor, QuerydslBinderCustomizer { + extends JpaRepository, QuerydslPredicateExecutor, QuerydslBinderCustomizer { @Override default void customize(final QuerydslBindings bindings, final QUser root) { bindings.bind(String.class).first((SingleValueBinding) StringExpression::eq); diff --git a/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java index 2d3dbc4c74..ad19c441b6 100644 --- a/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java +++ b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java @@ -13,8 +13,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import java.nio.charset.Charset; - import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -24,7 +22,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. public class IntegrationTest { final MediaType contentType = - new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); + new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype()); @Autowired private WebApplicationContext webApplicationContext; diff --git a/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/QuerydslIntegrationTest.java b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/QuerydslIntegrationTest.java index 11e5ffca05..768d28347b 100644 --- a/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/QuerydslIntegrationTest.java +++ b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/QuerydslIntegrationTest.java @@ -13,8 +13,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import java.nio.charset.Charset; - import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -26,7 +24,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. public class QuerydslIntegrationTest { final MediaType contentType = - new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); + new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype()); @Autowired private WebApplicationContext webApplicationContext; From 7bc1633c7283930e3ee981db534e4c78347ce407 Mon Sep 17 00:00:00 2001 From: Josh Cummings Date: Fri, 22 May 2020 07:40:59 -0600 Subject: [PATCH 143/150] Create README.md Issue BAEL-4009 --- patterns/cqrs-es/README.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 patterns/cqrs-es/README.md diff --git a/patterns/cqrs-es/README.md b/patterns/cqrs-es/README.md new file mode 100644 index 0000000000..92570280ab --- /dev/null +++ b/patterns/cqrs-es/README.md @@ -0,0 +1,5 @@ +This module contains articles about composing together CQRS and Event Sourcing + +## Relevant Articles + +- [CQRS and Event Sourcing in Java](https://www.baeldung.com/cqrs-event-sourcing-java) From d5a03e4c032360082d8ea5c0ba4425dceb362741 Mon Sep 17 00:00:00 2001 From: Josh Cummings Date: Sat, 23 May 2020 08:26:13 -0600 Subject: [PATCH 144/150] Update README.md Issue CS-144 --- core-java-modules/core-java-concurrency-advanced-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-concurrency-advanced-3/README.md b/core-java-modules/core-java-concurrency-advanced-3/README.md index dfd264116c..e33b6ab692 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/README.md +++ b/core-java-modules/core-java-concurrency-advanced-3/README.md @@ -12,4 +12,5 @@ This module contains articles about advanced topics about multithreading with co - [Asynchronous Programming in Java](https://www.baeldung.com/java-asynchronous-programming) - [Java Thread Deadlock and Livelock](https://www.baeldung.com/java-deadlock-livelock) - [Guide to AtomicStampedReference in Java](https://www.baeldung.com/java-atomicstampedreference) +- [The ABA Problem in Concurrency](https://www.baeldung.com/cs/aba-concurrency) - [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2) From f48582cfe1b929a16039dca62090b2ac0a872f69 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Sat, 23 May 2020 19:55:53 +0200 Subject: [PATCH 145/150] BAEL-4079: Add Oracle dependencies (#9338) --- .../spring-boot-persistence-2/pom.xml | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/persistence-modules/spring-boot-persistence-2/pom.xml b/persistence-modules/spring-boot-persistence-2/pom.xml index 33b33d7160..f36d8fc43f 100644 --- a/persistence-modules/spring-boot-persistence-2/pom.xml +++ b/persistence-modules/spring-boot-persistence-2/pom.xml @@ -120,6 +120,22 @@ org.hsqldb hsqldb + + + com.oracle.database.jdbc + ojdbc8 + ${oracle-database.version} + + + com.oracle.database.ha + ons + ${oracle-database.version} + + + com.oracle.database.jdbc + ucp + ${oracle-database.version} + @@ -128,23 +144,6 @@ org.springframework.boot spring-boot-maven-plugin - - - org.apache.maven.plugins - maven-compiler-plugin - - - com/baeldung/spring/oracle/pooling/configuration/OracleConfiguration.java - com/baeldung/spring/oracle/pooling/configuration/OracleUCPConfiguration.java - - - com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleLiveTest.java - com/baeldung/spring/oracle/pooling/SpringOraclePoolingApplicationOracleUCPLiveTest.java - - - @@ -152,6 +151,7 @@ 3.9.1 2.1.8.RELEASE 0.9.5.2 + 19.6.0.0 From 21d03e3e74691ee27092cc2c127e9c5c9c26a579 Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sun, 24 May 2020 17:41:17 +0530 Subject: [PATCH 146/150] updated keyclock to latest version --- spring-boot-modules/spring-boot-keycloak/pom.xml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/spring-boot-modules/spring-boot-keycloak/pom.xml b/spring-boot-modules/spring-boot-keycloak/pom.xml index c29c1a738b..14bd1e4112 100644 --- a/spring-boot-modules/spring-boot-keycloak/pom.xml +++ b/spring-boot-modules/spring-boot-keycloak/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -41,6 +41,10 @@ org.springframework.boot spring-boot-starter-data-jpa + + net.bytebuddy + byte-buddy + org.springframework.boot @@ -50,6 +54,7 @@ org.springframework.boot spring-boot-starter-security + 2.3.0.RELEASE org.springframework.boot @@ -76,7 +81,7 @@ - 3.3.0.Final + 10.0.1 From 0a478423f6021159b881e499de50888448a85aab Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sun, 24 May 2020 20:04:31 +0530 Subject: [PATCH 147/150] removed version from spring security --- spring-boot-modules/spring-boot-keycloak/pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-boot-modules/spring-boot-keycloak/pom.xml b/spring-boot-modules/spring-boot-keycloak/pom.xml index 14bd1e4112..8e917df2b7 100644 --- a/spring-boot-modules/spring-boot-keycloak/pom.xml +++ b/spring-boot-modules/spring-boot-keycloak/pom.xml @@ -54,7 +54,6 @@ org.springframework.boot spring-boot-starter-security - 2.3.0.RELEASE org.springframework.boot From 1fe51ed7c0d42041daac198ffe41d294a6d1b08a Mon Sep 17 00:00:00 2001 From: Sampada <46674082+sampada07@users.noreply.github.com> Date: Sun, 24 May 2020 23:25:06 +0530 Subject: [PATCH 148/150] BAEL-3609: Improve article Documenting a Spring REST API Using OpenAPI (#9334) 3.0 --- .../spring-boot-springdoc/pom.xml | 52 +++++++++++++++++++ .../springdoc/controller/BookController.java | 16 +++++- .../java/com/baeldung/springdoc/kotlin/Foo.kt | 17 ++++++ .../springdoc/kotlin/FooController.kt | 30 +++++++++++ .../src/main/resources/application.properties | 1 + 5 files changed, 115 insertions(+), 1 deletion(-) create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/Foo.kt create mode 100644 spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/FooController.kt diff --git a/spring-boot-modules/spring-boot-springdoc/pom.xml b/spring-boot-modules/spring-boot-springdoc/pom.xml index 1c1f27b5a5..4bede8c796 100644 --- a/spring-boot-modules/spring-boot-springdoc/pom.xml +++ b/spring-boot-modules/spring-boot-springdoc/pom.xml @@ -66,6 +66,22 @@ spring-restdocs-restassured test + + + + org.springdoc + springdoc-openapi-kotlin + ${springdoc.version} + + + org.jetbrains.kotlin + kotlin-stdlib-jre8 + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-reflect + @@ -97,6 +113,41 @@ + + + kotlin-maven-plugin + org.jetbrains.kotlin + ${kotlin.version} + + + spring + + ${java.version} + + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + @@ -116,6 +167,7 @@ 5.2.10.Final 1.2.32 1.5.6 + 1.2.71 ${project.build.directory}/generated-snippets diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java index 05f8c5a946..326a97149b 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java @@ -25,6 +25,13 @@ import com.baeldung.springdoc.exception.BookNotFoundException; import com.baeldung.springdoc.model.Book; import com.baeldung.springdoc.repository.BookRepository; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; + @RestController @RequestMapping("/api/book") public class BookController { @@ -32,8 +39,15 @@ public class BookController { @Autowired private BookRepository repository; + // @formatter:off + @Operation(summary = "Get a book by its id") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Found the book", + content = { @Content(mediaType = "application/json", schema = @Schema(implementation = Book.class)) }), + @ApiResponse(responseCode = "400", description = "Invalid id supplied", content = @Content), + @ApiResponse(responseCode = "404", description = "Book not found", content = @Content) }) // @formatter:on @GetMapping("/{id}") - public Book findById(@PathVariable long id) { + public Book findById(@Parameter(description = "id of book to be searched") @PathVariable long id) { return repository.findById(id) .orElseThrow(() -> new BookNotFoundException()); } diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/Foo.kt b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/Foo.kt new file mode 100644 index 0000000000..3bc3c8fe61 --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/Foo.kt @@ -0,0 +1,17 @@ +package com.baeldung.springdoc.kotlin + +import javax.persistence.Entity +import javax.persistence.GeneratedValue +import javax.persistence.Id +import javax.validation.constraints.NotBlank +import javax.validation.constraints.Size + +@Entity +data class Foo( + @Id + val id: Long = 0, + + @NotBlank + @Size(min = 0, max = 50) + val name: String = "" +) \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/FooController.kt b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/FooController.kt new file mode 100644 index 0000000000..d3ecd6a6ba --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/FooController.kt @@ -0,0 +1,30 @@ +package com.baeldung.springdoc.kotlin + +import io.swagger.v3.oas.annotations.Operation +import io.swagger.v3.oas.annotations.media.ArraySchema +import io.swagger.v3.oas.annotations.media.Content +import io.swagger.v3.oas.annotations.media.Schema +import io.swagger.v3.oas.annotations.responses.ApiResponse +import io.swagger.v3.oas.annotations.responses.ApiResponses +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RestController + +@RestController +@RequestMapping("/") +class FooController() { + val fooList: List = listOf(Foo(1, "one"), Foo(2, "two")) + + @Operation(summary = "Get all foos") + @ApiResponses(value = [ + ApiResponse(responseCode = "200", description = "Found Foos", content = [ + (Content(mediaType = "application/json", array = ( + ArraySchema(schema = Schema(implementation = Foo::class)))))]), + ApiResponse(responseCode = "400", description = "Bad request", content = [Content()]), + ApiResponse(responseCode = "404", description = "Did not find any Foos", content = [Content()])] + ) + @GetMapping("/foo") + fun getAllFoos(): List = fooList +} + + diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties b/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties index 7debdc6503..0eecfbb1c4 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-springdoc/src/main/resources/application.properties @@ -1,5 +1,6 @@ # custom path for swagger-ui springdoc.swagger-ui.path=/swagger-ui-custom.html +springdoc.swagger-ui.operationsSorter=method # custom path for api docs springdoc.api-docs.path=/api-docs From bddea5222bb03cdb266db1ba55ca91d8b4ba4de3 Mon Sep 17 00:00:00 2001 From: Bogdan Feraru Date: Sun, 10 May 2020 22:30:54 +0300 Subject: [PATCH 149/150] [BAEL-3890] Using Kafka MockConsumer --- libraries-data-2/pom.xml | 6 ++ .../kafka/consumer/CountryPopulation.java | 28 +++++ .../consumer/CountryPopulationConsumer.java | 60 +++++++++++ .../CountryPopulationConsumerUnitTest.java | 100 ++++++++++++++++++ 4 files changed, 194 insertions(+) create mode 100644 libraries-data-2/src/main/java/com/baeldung/kafka/consumer/CountryPopulation.java create mode 100644 libraries-data-2/src/main/java/com/baeldung/kafka/consumer/CountryPopulationConsumer.java create mode 100644 libraries-data-2/src/test/java/com/baeldung/kafka/consumer/CountryPopulationConsumerUnitTest.java diff --git a/libraries-data-2/pom.xml b/libraries-data-2/pom.xml index cbb24edd3f..bdfb2c5ed6 100644 --- a/libraries-data-2/pom.xml +++ b/libraries-data-2/pom.xml @@ -121,6 +121,11 @@ univocity-parsers ${univocity.version} + + org.apache.kafka + kafka-clients + ${kafka.version} + org.awaitility awaitility @@ -184,6 +189,7 @@ RELEASE 3.0 1.8.1 + 2.5.0 diff --git a/libraries-data-2/src/main/java/com/baeldung/kafka/consumer/CountryPopulation.java b/libraries-data-2/src/main/java/com/baeldung/kafka/consumer/CountryPopulation.java new file mode 100644 index 0000000000..8c1351642f --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/kafka/consumer/CountryPopulation.java @@ -0,0 +1,28 @@ +package com.baeldung.kafka.consumer; + +class CountryPopulation { + + private String country; + private Integer population; + + public CountryPopulation(String country, Integer population) { + this.country = country; + this.population = population; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public Integer getPopulation() { + return population; + } + + public void setPopulation(Integer population) { + this.population = population; + } +} \ No newline at end of file diff --git a/libraries-data-2/src/main/java/com/baeldung/kafka/consumer/CountryPopulationConsumer.java b/libraries-data-2/src/main/java/com/baeldung/kafka/consumer/CountryPopulationConsumer.java new file mode 100644 index 0000000000..ba4dfe6f3b --- /dev/null +++ b/libraries-data-2/src/main/java/com/baeldung/kafka/consumer/CountryPopulationConsumer.java @@ -0,0 +1,60 @@ +package com.baeldung.kafka.consumer; + +import java.time.Duration; +import java.util.Collections; +import java.util.stream.StreamSupport; + +import org.apache.kafka.clients.consumer.Consumer; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.common.TopicPartition; +import org.apache.kafka.common.errors.WakeupException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CountryPopulationConsumer { + + private static Logger logger = LoggerFactory.getLogger(CountryPopulationConsumer.class); + + private Consumer consumer; + private java.util.function.Consumer exceptionConsumer; + private java.util.function.Consumer countryPopulationConsumer; + + public CountryPopulationConsumer( + Consumer consumer, java.util.function.Consumer exceptionConsumer, + java.util.function.Consumer countryPopulationConsumer) { + this.consumer = consumer; + this.exceptionConsumer = exceptionConsumer; + this.countryPopulationConsumer = countryPopulationConsumer; + } + + void startBySubscribing(String topic) { + consume(() -> consumer.subscribe(Collections.singleton(topic))); + } + + void startByAssigning(String topic, int partition) { + consume(() -> consumer.assign(Collections.singleton(new TopicPartition(topic, partition)))); + } + + private void consume(Runnable beforePollingTask) { + try { + beforePollingTask.run(); + while (true) { + ConsumerRecords records = consumer.poll(Duration.ofMillis(1000)); + StreamSupport.stream(records.spliterator(), false) + .map(record -> new CountryPopulation(record.key(), record.value())) + .forEach(countryPopulationConsumer); + consumer.commitSync(); + } + } catch (WakeupException e) { + logger.info("Shutting down..."); + } catch (RuntimeException ex) { + exceptionConsumer.accept(ex); + } finally { + consumer.close(); + } + } + + public void stop() { + consumer.wakeup(); + } +} \ No newline at end of file diff --git a/libraries-data-2/src/test/java/com/baeldung/kafka/consumer/CountryPopulationConsumerUnitTest.java b/libraries-data-2/src/test/java/com/baeldung/kafka/consumer/CountryPopulationConsumerUnitTest.java new file mode 100644 index 0000000000..1b49c71716 --- /dev/null +++ b/libraries-data-2/src/test/java/com/baeldung/kafka/consumer/CountryPopulationConsumerUnitTest.java @@ -0,0 +1,100 @@ +package com.baeldung.kafka.consumer; + +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; + +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.MockConsumer; +import org.apache.kafka.clients.consumer.OffsetResetStrategy; +import org.apache.kafka.common.KafkaException; +import org.apache.kafka.common.TopicPartition; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class CountryPopulationConsumerUnitTest { + + private static final String TOPIC = "topic"; + private static final int PARTITION = 0; + + private CountryPopulationConsumer countryPopulationConsumer; + + private List updates; + private Throwable pollException; + + private MockConsumer consumer; + + @BeforeEach + void setUp() { + consumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST); + updates = new ArrayList<>(); + countryPopulationConsumer = new CountryPopulationConsumer(consumer, ex -> this.pollException = ex, updates::add); + } + + @Test + void whenStartingByAssigningTopicPartition_thenExpectUpdatesAreConsumedCorrectly() { + // GIVEN + consumer.schedulePollTask(() -> consumer.addRecord(record(TOPIC, PARTITION, "Romania", 19_410_000))); + consumer.schedulePollTask(() -> countryPopulationConsumer.stop()); + + HashMap startOffsets = new HashMap<>(); + TopicPartition tp = new TopicPartition(TOPIC, PARTITION); + startOffsets.put(tp, 0L); + consumer.updateBeginningOffsets(startOffsets); + + // WHEN + countryPopulationConsumer.startByAssigning(TOPIC, PARTITION); + + // THEN + assertThat(updates).hasSize(1); + assertThat(consumer.closed()).isTrue(); + } + + @Test + void whenStartingBySubscribingToTopic_thenExpectUpdatesAreConsumedCorrectly() { + // GIVEN + consumer.schedulePollTask(() -> { + consumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC, 0))); + consumer.addRecord(record(TOPIC, PARTITION, "Romania", 19_410_000)); + }); + consumer.schedulePollTask(() -> countryPopulationConsumer.stop()); + + HashMap startOffsets = new HashMap<>(); + TopicPartition tp = new TopicPartition(TOPIC, PARTITION); + startOffsets.put(tp, 0L); + consumer.updateBeginningOffsets(startOffsets); + + // WHEN + countryPopulationConsumer.startBySubscribing(TOPIC); + + // THEN + assertThat(updates).hasSize(1); + assertThat(consumer.closed()).isTrue(); + } + + @Test + void whenStartingBySubscribingToTopicAndExceptionOccurs_thenExpectExceptionIsHandledCorrectly() { + // GIVEN + consumer.schedulePollTask(() -> consumer.setPollException(new KafkaException("poll exception"))); + consumer.schedulePollTask(() -> countryPopulationConsumer.stop()); + + HashMap startOffsets = new HashMap<>(); + TopicPartition tp = new TopicPartition(TOPIC, 0); + startOffsets.put(tp, 0L); + consumer.updateBeginningOffsets(startOffsets); + + // WHEN + countryPopulationConsumer.startBySubscribing(TOPIC); + + // THEN + assertThat(pollException).isInstanceOf(KafkaException.class).hasMessage("poll exception"); + assertThat(consumer.closed()).isTrue(); + } + + private ConsumerRecord record(String topic, int partition, String country, int population) { + return new ConsumerRecord<>(topic, partition, 0, country, population); + } +} \ No newline at end of file From 2bdba48843234b58fe3086a28f6f008b6a7930cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Dupire?= Date: Mon, 25 May 2020 16:15:48 +0200 Subject: [PATCH 150/150] [JAVA-1657] Junit and Maven Surefire Plugin upgrade in core-java-modules (#9301) * [JAVA-1657] core-java-modules JUnit and Maven Surefire Plugin upgrade * [JAVA-1657] Changed sub modules parents to core-java-modules and core-java-modules to parent-java * [JAVA-1657] Upgraded JUnit Jupiter version * [JAVA-1657] Get JUnit 4 dependency transitively --- core-java-modules/core-java-8-2/pom.xml | 7 ++-- .../core-java-8-datetime-2/pom.xml | 7 ++-- .../core-java-8-datetime/pom.xml | 7 ++-- core-java-modules/core-java-8/pom.xml | 7 ++-- core-java-modules/core-java-9-streams/pom.xml | 7 ++-- .../core-java-annotations/pom.xml | 6 +-- .../core-java-arrays-convert/pom.xml | 2 +- .../core-java-arrays-guides/pom.xml | 2 +- .../core-java-arrays-multidimensional/pom.xml | 2 +- .../pom.xml | 2 +- .../core-java-arrays-operations-basic/pom.xml | 2 +- .../core-java-arrays-sorting/pom.xml | 4 +- .../core-java-collections-2/pom.xml | 7 ++-- .../core-java-collections-3/pom.xml | 7 ++-- .../core-java-collections-array-list/pom.xml | 7 ++-- .../core-java-collections-list-2/pom.xml | 7 ++-- .../core-java-collections-list-3/pom.xml | 7 ++-- .../core-java-collections-list/pom.xml | 7 ++-- .../core-java-collections-maps-2/pom.xml | 7 ++-- .../core-java-collections-maps-3/pom.xml | 7 ++-- .../core-java-collections-maps/pom.xml | 9 ++--- .../core-java-collections-set/pom.xml | 7 ++-- .../core-java-collections/pom.xml | 7 ++-- .../core-java-concurrency-2/pom.xml | 7 ++-- .../core-java-concurrency-advanced-2/pom.xml | 7 ++-- .../core-java-concurrency-advanced-3/pom.xml | 7 ++-- .../core-java-concurrency-advanced/pom.xml | 7 ++-- .../core-java-concurrency-basic-2/pom.xml | 7 ++-- .../core-java-concurrency-basic/pom.xml | 7 ++-- .../core-java-concurrency-collections/pom.xml | 7 ++-- .../core-java-date-operations-1/pom.xml | 7 ++-- .../core-java-date-operations-2/pom.xml | 7 ++-- .../core-java-datetime-conversion/pom.xml | 7 ++-- .../core-java-datetime-string/pom.xml | 7 ++-- .../core-java-exceptions-2/pom.xml | 7 ++-- .../core-java-exceptions/pom.xml | 7 ++-- core-java-modules/core-java-function/pom.xml | 7 ++-- core-java-modules/core-java-io-2/pom.xml | 7 ++-- core-java-modules/core-java-io-apis/pom.xml | 7 ++-- .../core-java-io-conversions-2/pom.xml | 7 ++-- .../core-java-io-conversions/pom.xml | 7 ++-- core-java-modules/core-java-io/pom.xml | 7 ++-- core-java-modules/core-java-jar/pom.xml | 7 ++-- core-java-modules/core-java-jndi/pom.xml | 2 +- core-java-modules/core-java-jpms/pom.xml | 2 +- core-java-modules/core-java-jvm/pom.xml | 8 ++-- core-java-modules/core-java-lambdas/pom.xml | 7 ++-- core-java-modules/core-java-lang-2/pom.xml | 7 ++-- .../core-java-lang-math-2/pom.xml | 7 ++-- core-java-modules/core-java-lang-math/pom.xml | 7 ++-- .../core-java-lang-oop-constructors/pom.xml | 2 +- .../core-java-lang-oop-generics/pom.xml | 2 +- .../core-java-lang-oop-inheritance/pom.xml | 2 +- .../core-java-lang-oop-methods/pom.xml | 2 +- .../core-java-lang-oop-modifiers/pom.xml | 2 +- .../core-java-lang-oop-others/pom.xml | 2 +- .../core-java-lang-oop-patterns/pom.xml | 2 +- .../core-java-lang-oop-types/pom.xml | 2 +- .../core-java-lang-operators/pom.xml | 7 ++-- .../core-java-lang-syntax-2/pom.xml | 7 ++-- .../core-java-lang-syntax/pom.xml | 7 ++-- core-java-modules/core-java-lang/pom.xml | 7 ++-- .../core-java-networking-2/pom.xml | 7 ++-- .../core-java-networking/pom.xml | 7 ++-- core-java-modules/core-java-nio-2/pom.xml | 7 ++-- core-java-modules/core-java-nio/pom.xml | 7 ++-- core-java-modules/core-java-optional/pom.xml | 2 +- core-java-modules/core-java-os/pom.xml | 7 ++-- core-java-modules/core-java-perf/pom.xml | 7 ++-- .../core-java-reflection/pom.xml | 7 ++-- core-java-modules/core-java-regex/pom.xml | 7 ++-- .../core-java-security-2/pom.xml | 7 ++-- core-java-modules/core-java-security/pom.xml | 7 ++-- core-java-modules/core-java-streams-2/pom.xml | 7 ++-- core-java-modules/core-java-streams-3/pom.xml | 7 ++-- core-java-modules/core-java-streams/pom.xml | 7 ++-- .../core-java-string-algorithms-2/pom.xml | 7 ++-- .../core-java-string-algorithms-3/pom.xml | 11 ++---- .../core-java-string-algorithms/pom.xml | 7 ++-- .../core-java-string-apis/pom.xml | 7 ++-- .../core-java-string-conversions-2/pom.xml | 7 ++-- .../core-java-string-conversions/pom.xml | 7 ++-- .../core-java-string-operations-2/pom.xml | 7 ++-- .../core-java-string-operations/pom.xml | 7 ++-- core-java-modules/core-java-strings/pom.xml | 7 ++-- core-java-modules/core-java-sun/pom.xml | 7 ++-- .../core-java-time-measurements/pom.xml | 7 ++-- core-java-modules/core-java/pom.xml | 7 ++-- core-java-modules/pom.xml | 38 ++++++++++++++++++- core-java-modules/pre-jpms/pom.xml | 8 ++-- 90 files changed, 274 insertions(+), 311 deletions(-) diff --git a/core-java-modules/core-java-8-2/pom.xml b/core-java-modules/core-java-8-2/pom.xml index 00579c49b2..48474a5eef 100644 --- a/core-java-modules/core-java-8-2/pom.xml +++ b/core-java-modules/core-java-8-2/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-8-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-8-datetime-2/pom.xml b/core-java-modules/core-java-8-datetime-2/pom.xml index ce98b72781..629ce5234d 100644 --- a/core-java-modules/core-java-8-datetime-2/pom.xml +++ b/core-java-modules/core-java-8-datetime-2/pom.xml @@ -8,12 +8,11 @@ ${project.parent.version} core-java-8-datetime jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-8-datetime/pom.xml b/core-java-modules/core-java-8-datetime/pom.xml index ce98b72781..629ce5234d 100644 --- a/core-java-modules/core-java-8-datetime/pom.xml +++ b/core-java-modules/core-java-8-datetime/pom.xml @@ -8,12 +8,11 @@ ${project.parent.version} core-java-8-datetime jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-8/pom.xml b/core-java-modules/core-java-8/pom.xml index a434be028d..557f9e0dce 100644 --- a/core-java-modules/core-java-8/pom.xml +++ b/core-java-modules/core-java-8/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-8 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-9-streams/pom.xml b/core-java-modules/core-java-9-streams/pom.xml index 7865b336a7..8c1af89b24 100644 --- a/core-java-modules/core-java-9-streams/pom.xml +++ b/core-java-modules/core-java-9-streams/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-9-streams jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-annotations/pom.xml b/core-java-modules/core-java-annotations/pom.xml index 8fc4c15cde..92ba4991bb 100644 --- a/core-java-modules/core-java-annotations/pom.xml +++ b/core-java-modules/core-java-annotations/pom.xml @@ -10,10 +10,10 @@ jar - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-arrays-convert/pom.xml b/core-java-modules/core-java-arrays-convert/pom.xml index bd50289f47..67dc645936 100644 --- a/core-java-modules/core-java-arrays-convert/pom.xml +++ b/core-java-modules/core-java-arrays-convert/pom.xml @@ -5,7 +5,7 @@ core-java-modules com.baeldung.core-java-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT 4.0.0 diff --git a/core-java-modules/core-java-arrays-guides/pom.xml b/core-java-modules/core-java-arrays-guides/pom.xml index ef718d5117..df8639820d 100644 --- a/core-java-modules/core-java-arrays-guides/pom.xml +++ b/core-java-modules/core-java-arrays-guides/pom.xml @@ -5,7 +5,7 @@ core-java-modules com.baeldung.core-java-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT 4.0.0 diff --git a/core-java-modules/core-java-arrays-multidimensional/pom.xml b/core-java-modules/core-java-arrays-multidimensional/pom.xml index 6e49a20521..d90853678c 100644 --- a/core-java-modules/core-java-arrays-multidimensional/pom.xml +++ b/core-java-modules/core-java-arrays-multidimensional/pom.xml @@ -5,7 +5,7 @@ core-java-modules com.baeldung.core-java-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT 4.0.0 diff --git a/core-java-modules/core-java-arrays-operations-advanced/pom.xml b/core-java-modules/core-java-arrays-operations-advanced/pom.xml index 8989e91189..d73fdcee28 100644 --- a/core-java-modules/core-java-arrays-operations-advanced/pom.xml +++ b/core-java-modules/core-java-arrays-operations-advanced/pom.xml @@ -5,7 +5,7 @@ core-java-modules com.baeldung.core-java-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT 4.0.0 diff --git a/core-java-modules/core-java-arrays-operations-basic/pom.xml b/core-java-modules/core-java-arrays-operations-basic/pom.xml index 4480c14bb2..73588d662a 100644 --- a/core-java-modules/core-java-arrays-operations-basic/pom.xml +++ b/core-java-modules/core-java-arrays-operations-basic/pom.xml @@ -5,7 +5,7 @@ core-java-modules com.baeldung.core-java-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT 4.0.0 diff --git a/core-java-modules/core-java-arrays-sorting/pom.xml b/core-java-modules/core-java-arrays-sorting/pom.xml index 127d921b2a..d5e2beaac4 100644 --- a/core-java-modules/core-java-arrays-sorting/pom.xml +++ b/core-java-modules/core-java-arrays-sorting/pom.xml @@ -5,8 +5,8 @@ core-java-modules com.baeldung.core-java-modules - 1.0.0-SNAPSHOT - ../pom.xml + 0.0.1-SNAPSHOT + ../ 4.0.0 diff --git a/core-java-modules/core-java-collections-2/pom.xml b/core-java-modules/core-java-collections-2/pom.xml index 3a7c70b1a2..d163aabdbc 100644 --- a/core-java-modules/core-java-collections-2/pom.xml +++ b/core-java-modules/core-java-collections-2/pom.xml @@ -7,12 +7,11 @@ core-java-collections-2 core-java-collections-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-collections-3/pom.xml b/core-java-modules/core-java-collections-3/pom.xml index 1e1695c8bc..bd991bfefa 100644 --- a/core-java-modules/core-java-collections-3/pom.xml +++ b/core-java-modules/core-java-collections-3/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-collections-3 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-collections-array-list/pom.xml b/core-java-modules/core-java-collections-array-list/pom.xml index 74a6513cac..81ee4eff55 100644 --- a/core-java-modules/core-java-collections-array-list/pom.xml +++ b/core-java-modules/core-java-collections-array-list/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-collections-array-list jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-collections-list-2/pom.xml b/core-java-modules/core-java-collections-list-2/pom.xml index 3184da1294..230787d14d 100644 --- a/core-java-modules/core-java-collections-list-2/pom.xml +++ b/core-java-modules/core-java-collections-list-2/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-collections-list-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-collections-list-3/pom.xml b/core-java-modules/core-java-collections-list-3/pom.xml index 090e756ac6..373190a130 100644 --- a/core-java-modules/core-java-collections-list-3/pom.xml +++ b/core-java-modules/core-java-collections-list-3/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-collections-list-3 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-collections-list/pom.xml b/core-java-modules/core-java-collections-list/pom.xml index e6dce5a0db..509f58ea61 100644 --- a/core-java-modules/core-java-collections-list/pom.xml +++ b/core-java-modules/core-java-collections-list/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-collections-list jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-collections-maps-2/pom.xml b/core-java-modules/core-java-collections-maps-2/pom.xml index a08a4ac072..a64a11c6ea 100644 --- a/core-java-modules/core-java-collections-maps-2/pom.xml +++ b/core-java-modules/core-java-collections-maps-2/pom.xml @@ -7,12 +7,11 @@ 0.1.0-SNAPSHOT core-java-collections-maps-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-collections-maps-3/pom.xml b/core-java-modules/core-java-collections-maps-3/pom.xml index 95414c12c2..f547968b22 100644 --- a/core-java-modules/core-java-collections-maps-3/pom.xml +++ b/core-java-modules/core-java-collections-maps-3/pom.xml @@ -7,12 +7,11 @@ 0.1.0-SNAPSHOT core-java-collections-maps-3 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-collections-maps/pom.xml b/core-java-modules/core-java-collections-maps/pom.xml index c0dd705c1c..742e264504 100644 --- a/core-java-modules/core-java-collections-maps/pom.xml +++ b/core-java-modules/core-java-collections-maps/pom.xml @@ -6,12 +6,11 @@ 0.1.0-SNAPSHOT core-java-collections-maps jar - - - com.baeldung - parent-java + + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-collections-set/pom.xml b/core-java-modules/core-java-collections-set/pom.xml index c89ba0c091..7c55f2ff2a 100644 --- a/core-java-modules/core-java-collections-set/pom.xml +++ b/core-java-modules/core-java-collections-set/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-collections-set jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-collections/pom.xml b/core-java-modules/core-java-collections/pom.xml index 515d19d7fb..e1219c4713 100644 --- a/core-java-modules/core-java-collections/pom.xml +++ b/core-java-modules/core-java-collections/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-collections jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-concurrency-2/pom.xml b/core-java-modules/core-java-concurrency-2/pom.xml index dfb5674c8e..75fd3890b3 100644 --- a/core-java-modules/core-java-concurrency-2/pom.xml +++ b/core-java-modules/core-java-concurrency-2/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-concurrency-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-concurrency-advanced-2/pom.xml b/core-java-modules/core-java-concurrency-advanced-2/pom.xml index 8752e7b7db..2f374bffac 100644 --- a/core-java-modules/core-java-concurrency-advanced-2/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced-2/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-concurrency-advanced-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-concurrency-advanced-3/pom.xml b/core-java-modules/core-java-concurrency-advanced-3/pom.xml index cf81214125..32267fb800 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced-3/pom.xml @@ -9,12 +9,11 @@ 0.1.0-SNAPSHOT core-java-concurrency-advanced-3 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-concurrency-advanced/pom.xml b/core-java-modules/core-java-concurrency-advanced/pom.xml index d39712468f..67db486121 100644 --- a/core-java-modules/core-java-concurrency-advanced/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-concurrency-advanced jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-concurrency-basic-2/pom.xml b/core-java-modules/core-java-concurrency-basic-2/pom.xml index 8c9bbef54c..adc4fd33e3 100644 --- a/core-java-modules/core-java-concurrency-basic-2/pom.xml +++ b/core-java-modules/core-java-concurrency-basic-2/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-concurrency-basic-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-concurrency-basic/pom.xml b/core-java-modules/core-java-concurrency-basic/pom.xml index c15200da1f..29d393805b 100644 --- a/core-java-modules/core-java-concurrency-basic/pom.xml +++ b/core-java-modules/core-java-concurrency-basic/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-concurrency-basic jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-concurrency-collections/pom.xml b/core-java-modules/core-java-concurrency-collections/pom.xml index 5c038639a7..31f5a0fca8 100644 --- a/core-java-modules/core-java-concurrency-collections/pom.xml +++ b/core-java-modules/core-java-concurrency-collections/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-concurrency-collections jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-date-operations-1/pom.xml b/core-java-modules/core-java-date-operations-1/pom.xml index 54cbc79678..e12e4aa4ee 100644 --- a/core-java-modules/core-java-date-operations-1/pom.xml +++ b/core-java-modules/core-java-date-operations-1/pom.xml @@ -8,12 +8,11 @@ ${project.parent.version} core-java-date-operations-1 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-date-operations-2/pom.xml b/core-java-modules/core-java-date-operations-2/pom.xml index ea5f852b0d..5861a9ab98 100644 --- a/core-java-modules/core-java-date-operations-2/pom.xml +++ b/core-java-modules/core-java-date-operations-2/pom.xml @@ -8,12 +8,11 @@ ${project.parent.version} core-java-date-operations-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-datetime-conversion/pom.xml b/core-java-modules/core-java-datetime-conversion/pom.xml index e2dd579335..79d1394576 100644 --- a/core-java-modules/core-java-datetime-conversion/pom.xml +++ b/core-java-modules/core-java-datetime-conversion/pom.xml @@ -8,12 +8,11 @@ ${project.parent.version} core-java-datetime-conversion jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-datetime-string/pom.xml b/core-java-modules/core-java-datetime-string/pom.xml index ceb7641320..c1181f670a 100644 --- a/core-java-modules/core-java-datetime-string/pom.xml +++ b/core-java-modules/core-java-datetime-string/pom.xml @@ -8,12 +8,11 @@ ${project.parent.version} core-java-datetime-string jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-exceptions-2/pom.xml b/core-java-modules/core-java-exceptions-2/pom.xml index 915ec1da69..a53bf37b77 100644 --- a/core-java-modules/core-java-exceptions-2/pom.xml +++ b/core-java-modules/core-java-exceptions-2/pom.xml @@ -7,12 +7,11 @@ core-java-exceptions-2 core-java-exceptions-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-exceptions/pom.xml b/core-java-modules/core-java-exceptions/pom.xml index 0778b6b5a3..b708aff6b9 100644 --- a/core-java-modules/core-java-exceptions/pom.xml +++ b/core-java-modules/core-java-exceptions/pom.xml @@ -9,12 +9,11 @@ 0.1.0-SNAPSHOT core-java-exceptions jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-function/pom.xml b/core-java-modules/core-java-function/pom.xml index 1a853d5580..0eb34bed7b 100644 --- a/core-java-modules/core-java-function/pom.xml +++ b/core-java-modules/core-java-function/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-function jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-io-2/pom.xml b/core-java-modules/core-java-io-2/pom.xml index ec27c76435..bdc2ee37f5 100644 --- a/core-java-modules/core-java-io-2/pom.xml +++ b/core-java-modules/core-java-io-2/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-io-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-io-apis/pom.xml b/core-java-modules/core-java-io-apis/pom.xml index 9628027309..9350e4b527 100644 --- a/core-java-modules/core-java-io-apis/pom.xml +++ b/core-java-modules/core-java-io-apis/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-io-apis jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-io-conversions-2/pom.xml b/core-java-modules/core-java-io-conversions-2/pom.xml index e95d1f4b67..5312ad645d 100644 --- a/core-java-modules/core-java-io-conversions-2/pom.xml +++ b/core-java-modules/core-java-io-conversions-2/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-io-conversions-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-io-conversions/pom.xml b/core-java-modules/core-java-io-conversions/pom.xml index f5ccaa45a3..0012b02d7e 100644 --- a/core-java-modules/core-java-io-conversions/pom.xml +++ b/core-java-modules/core-java-io-conversions/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-io-conversions jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-io/pom.xml b/core-java-modules/core-java-io/pom.xml index 103a809f90..ccfb57e909 100644 --- a/core-java-modules/core-java-io/pom.xml +++ b/core-java-modules/core-java-io/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-io jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-jar/pom.xml b/core-java-modules/core-java-jar/pom.xml index 1d87bcda5f..6e9d713d7c 100644 --- a/core-java-modules/core-java-jar/pom.xml +++ b/core-java-modules/core-java-jar/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-jar jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-jndi/pom.xml b/core-java-modules/core-java-jndi/pom.xml index 4a491a1a47..030a5f5d50 100644 --- a/core-java-modules/core-java-jndi/pom.xml +++ b/core-java-modules/core-java-jndi/pom.xml @@ -12,7 +12,7 @@ com.baeldung.core-java-modules core-java-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT diff --git a/core-java-modules/core-java-jpms/pom.xml b/core-java-modules/core-java-jpms/pom.xml index 4610baab49..5809c0f579 100644 --- a/core-java-modules/core-java-jpms/pom.xml +++ b/core-java-modules/core-java-jpms/pom.xml @@ -12,7 +12,7 @@ com.baeldung.core-java-modules core-java-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT diff --git a/core-java-modules/core-java-jvm/pom.xml b/core-java-modules/core-java-jvm/pom.xml index edf7a4f3c5..f3e5470a61 100644 --- a/core-java-modules/core-java-jvm/pom.xml +++ b/core-java-modules/core-java-jvm/pom.xml @@ -10,10 +10,10 @@ jar - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + ../ diff --git a/core-java-modules/core-java-lambdas/pom.xml b/core-java-modules/core-java-lambdas/pom.xml index 421ca2f394..318b04fcf5 100644 --- a/core-java-modules/core-java-lambdas/pom.xml +++ b/core-java-modules/core-java-lambdas/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-lambdas jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-lang-2/pom.xml b/core-java-modules/core-java-lang-2/pom.xml index 21a63d8091..5f2d4ec901 100644 --- a/core-java-modules/core-java-lang-2/pom.xml +++ b/core-java-modules/core-java-lang-2/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-lang-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-lang-math-2/pom.xml b/core-java-modules/core-java-lang-math-2/pom.xml index 92ebcc6a94..e2cced4fbf 100644 --- a/core-java-modules/core-java-lang-math-2/pom.xml +++ b/core-java-modules/core-java-lang-math-2/pom.xml @@ -5,12 +5,11 @@ core-java-lang-math-2 0.0.1-SNAPSHOT core-java-lang-math-2 - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-lang-math/pom.xml b/core-java-modules/core-java-lang-math/pom.xml index bcb5cf39d2..81ff0d43ea 100644 --- a/core-java-modules/core-java-lang-math/pom.xml +++ b/core-java-modules/core-java-lang-math/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-lang-math jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-lang-oop-constructors/pom.xml b/core-java-modules/core-java-lang-oop-constructors/pom.xml index 76507103ea..e54286a822 100644 --- a/core-java-modules/core-java-lang-oop-constructors/pom.xml +++ b/core-java-modules/core-java-lang-oop-constructors/pom.xml @@ -5,7 +5,7 @@ core-java-modules com.baeldung.core-java-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT 4.0.0 diff --git a/core-java-modules/core-java-lang-oop-generics/pom.xml b/core-java-modules/core-java-lang-oop-generics/pom.xml index ae141ecda2..65a0aeac59 100644 --- a/core-java-modules/core-java-lang-oop-generics/pom.xml +++ b/core-java-modules/core-java-lang-oop-generics/pom.xml @@ -5,7 +5,7 @@ core-java-modules com.baeldung.core-java-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT 4.0.0 diff --git a/core-java-modules/core-java-lang-oop-inheritance/pom.xml b/core-java-modules/core-java-lang-oop-inheritance/pom.xml index a48b28a289..ca828279db 100644 --- a/core-java-modules/core-java-lang-oop-inheritance/pom.xml +++ b/core-java-modules/core-java-lang-oop-inheritance/pom.xml @@ -5,7 +5,7 @@ core-java-modules com.baeldung.core-java-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT 4.0.0 diff --git a/core-java-modules/core-java-lang-oop-methods/pom.xml b/core-java-modules/core-java-lang-oop-methods/pom.xml index 3590b85454..bcf561a6c2 100644 --- a/core-java-modules/core-java-lang-oop-methods/pom.xml +++ b/core-java-modules/core-java-lang-oop-methods/pom.xml @@ -5,7 +5,7 @@ core-java-modules com.baeldung.core-java-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT 4.0.0 diff --git a/core-java-modules/core-java-lang-oop-modifiers/pom.xml b/core-java-modules/core-java-lang-oop-modifiers/pom.xml index 615e20690f..5f0be4545f 100644 --- a/core-java-modules/core-java-lang-oop-modifiers/pom.xml +++ b/core-java-modules/core-java-lang-oop-modifiers/pom.xml @@ -5,7 +5,7 @@ core-java-modules com.baeldung.core-java-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT 4.0.0 diff --git a/core-java-modules/core-java-lang-oop-others/pom.xml b/core-java-modules/core-java-lang-oop-others/pom.xml index 8eab301748..ad5699d592 100644 --- a/core-java-modules/core-java-lang-oop-others/pom.xml +++ b/core-java-modules/core-java-lang-oop-others/pom.xml @@ -5,7 +5,7 @@ core-java-modules com.baeldung.core-java-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT 4.0.0 diff --git a/core-java-modules/core-java-lang-oop-patterns/pom.xml b/core-java-modules/core-java-lang-oop-patterns/pom.xml index 0102ef2653..0829295250 100644 --- a/core-java-modules/core-java-lang-oop-patterns/pom.xml +++ b/core-java-modules/core-java-lang-oop-patterns/pom.xml @@ -5,7 +5,7 @@ core-java-modules com.baeldung.core-java-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT 4.0.0 diff --git a/core-java-modules/core-java-lang-oop-types/pom.xml b/core-java-modules/core-java-lang-oop-types/pom.xml index f73434a9ff..5555df4818 100644 --- a/core-java-modules/core-java-lang-oop-types/pom.xml +++ b/core-java-modules/core-java-lang-oop-types/pom.xml @@ -5,7 +5,7 @@ core-java-modules com.baeldung.core-java-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT 4.0.0 diff --git a/core-java-modules/core-java-lang-operators/pom.xml b/core-java-modules/core-java-lang-operators/pom.xml index 09fbce4b3c..5b4c2fecaa 100644 --- a/core-java-modules/core-java-lang-operators/pom.xml +++ b/core-java-modules/core-java-lang-operators/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-lang-operators jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-lang-syntax-2/pom.xml b/core-java-modules/core-java-lang-syntax-2/pom.xml index b6da37b736..b88c86b047 100644 --- a/core-java-modules/core-java-lang-syntax-2/pom.xml +++ b/core-java-modules/core-java-lang-syntax-2/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-lang-syntax-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-lang-syntax/pom.xml b/core-java-modules/core-java-lang-syntax/pom.xml index 106074bba6..c8f6524e0b 100644 --- a/core-java-modules/core-java-lang-syntax/pom.xml +++ b/core-java-modules/core-java-lang-syntax/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-lang-syntax jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-lang/pom.xml b/core-java-modules/core-java-lang/pom.xml index 44d7812c15..807d5f34d4 100644 --- a/core-java-modules/core-java-lang/pom.xml +++ b/core-java-modules/core-java-lang/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-lang jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-networking-2/pom.xml b/core-java-modules/core-java-networking-2/pom.xml index 938635b8d4..d79320eaef 100644 --- a/core-java-modules/core-java-networking-2/pom.xml +++ b/core-java-modules/core-java-networking-2/pom.xml @@ -7,12 +7,11 @@ core-java-networking-2 core-java-networking-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-networking/pom.xml b/core-java-modules/core-java-networking/pom.xml index c22b62118d..b81be2751a 100644 --- a/core-java-modules/core-java-networking/pom.xml +++ b/core-java-modules/core-java-networking/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-networking jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-nio-2/pom.xml b/core-java-modules/core-java-nio-2/pom.xml index 2e67bff30a..0c7c079406 100644 --- a/core-java-modules/core-java-nio-2/pom.xml +++ b/core-java-modules/core-java-nio-2/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-nio-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ \ No newline at end of file diff --git a/core-java-modules/core-java-nio/pom.xml b/core-java-modules/core-java-nio/pom.xml index e7605763bb..5b8baf6a70 100644 --- a/core-java-modules/core-java-nio/pom.xml +++ b/core-java-modules/core-java-nio/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-nio jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ \ No newline at end of file diff --git a/core-java-modules/core-java-optional/pom.xml b/core-java-modules/core-java-optional/pom.xml index 57e85109e6..575ccb0759 100644 --- a/core-java-modules/core-java-optional/pom.xml +++ b/core-java-modules/core-java-optional/pom.xml @@ -12,7 +12,7 @@ com.baeldung.core-java-modules core-java-modules - 1.0.0-SNAPSHOT + 0.0.1-SNAPSHOT diff --git a/core-java-modules/core-java-os/pom.xml b/core-java-modules/core-java-os/pom.xml index d8941cb494..e17ddf9b37 100644 --- a/core-java-modules/core-java-os/pom.xml +++ b/core-java-modules/core-java-os/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-os jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-perf/pom.xml b/core-java-modules/core-java-perf/pom.xml index c1970346b5..3956c7e9fb 100644 --- a/core-java-modules/core-java-perf/pom.xml +++ b/core-java-modules/core-java-perf/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-perf jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-reflection/pom.xml b/core-java-modules/core-java-reflection/pom.xml index dca446b268..4ae7b26745 100644 --- a/core-java-modules/core-java-reflection/pom.xml +++ b/core-java-modules/core-java-reflection/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-reflection jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-regex/pom.xml b/core-java-modules/core-java-regex/pom.xml index df2382a732..9e2d91d5d9 100644 --- a/core-java-modules/core-java-regex/pom.xml +++ b/core-java-modules/core-java-regex/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-regex jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-security-2/pom.xml b/core-java-modules/core-java-security-2/pom.xml index 5db3b67c04..85aa3869b3 100644 --- a/core-java-modules/core-java-security-2/pom.xml +++ b/core-java-modules/core-java-security-2/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-security-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-security/pom.xml b/core-java-modules/core-java-security/pom.xml index 96024a73a1..8ad120c8fc 100644 --- a/core-java-modules/core-java-security/pom.xml +++ b/core-java-modules/core-java-security/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-security jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-streams-2/pom.xml b/core-java-modules/core-java-streams-2/pom.xml index 1f47df63a0..2a0a4348b0 100644 --- a/core-java-modules/core-java-streams-2/pom.xml +++ b/core-java-modules/core-java-streams-2/pom.xml @@ -8,12 +8,11 @@ 1.0 core-java-streams-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-streams-3/pom.xml b/core-java-modules/core-java-streams-3/pom.xml index ae27e28918..cbb7366a7d 100644 --- a/core-java-modules/core-java-streams-3/pom.xml +++ b/core-java-modules/core-java-streams-3/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-streams-3 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-streams/pom.xml b/core-java-modules/core-java-streams/pom.xml index 272a2be540..f713fe7499 100644 --- a/core-java-modules/core-java-streams/pom.xml +++ b/core-java-modules/core-java-streams/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-streams jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-string-algorithms-2/pom.xml b/core-java-modules/core-java-string-algorithms-2/pom.xml index f05674034a..a635cd8022 100644 --- a/core-java-modules/core-java-string-algorithms-2/pom.xml +++ b/core-java-modules/core-java-string-algorithms-2/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-string-algorithms-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml index 583fa99afd..2725ba84c6 100644 --- a/core-java-modules/core-java-string-algorithms-3/pom.xml +++ b/core-java-modules/core-java-string-algorithms-3/pom.xml @@ -7,12 +7,11 @@ 0.1.0-SNAPSHOT jar core-java-string-algorithms-3 - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ @@ -31,8 +30,7 @@ org.junit.jupiter - junit-jupiter-api - ${junit-jupiter-api.version} + junit-jupiter test @@ -64,7 +62,6 @@ 3.8.1 3.6.1 28.1-jre - 5.3.1 diff --git a/core-java-modules/core-java-string-algorithms/pom.xml b/core-java-modules/core-java-string-algorithms/pom.xml index cb1a25c11b..85879d74e2 100644 --- a/core-java-modules/core-java-string-algorithms/pom.xml +++ b/core-java-modules/core-java-string-algorithms/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-string-algorithms jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-string-apis/pom.xml b/core-java-modules/core-java-string-apis/pom.xml index c1cd439386..449092bacb 100644 --- a/core-java-modules/core-java-string-apis/pom.xml +++ b/core-java-modules/core-java-string-apis/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-string-apis jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-string-conversions-2/pom.xml b/core-java-modules/core-java-string-conversions-2/pom.xml index 53680e4fce..cd7381d822 100644 --- a/core-java-modules/core-java-string-conversions-2/pom.xml +++ b/core-java-modules/core-java-string-conversions-2/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-string-conversions-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-string-conversions/pom.xml b/core-java-modules/core-java-string-conversions/pom.xml index 302e73e691..7d8977d2a5 100644 --- a/core-java-modules/core-java-string-conversions/pom.xml +++ b/core-java-modules/core-java-string-conversions/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-string-conversions jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-string-operations-2/pom.xml b/core-java-modules/core-java-string-operations-2/pom.xml index a00ae80f13..db32bf97a1 100644 --- a/core-java-modules/core-java-string-operations-2/pom.xml +++ b/core-java-modules/core-java-string-operations-2/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-string-operations-2 jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-string-operations/pom.xml b/core-java-modules/core-java-string-operations/pom.xml index a46b8ac129..c5791e929e 100644 --- a/core-java-modules/core-java-string-operations/pom.xml +++ b/core-java-modules/core-java-string-operations/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-string-operations jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-strings/pom.xml b/core-java-modules/core-java-strings/pom.xml index 9e9bf0748b..b09dc3f8a4 100644 --- a/core-java-modules/core-java-strings/pom.xml +++ b/core-java-modules/core-java-strings/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-strings jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-sun/pom.xml b/core-java-modules/core-java-sun/pom.xml index d60ab71db0..0f53407ec1 100644 --- a/core-java-modules/core-java-sun/pom.xml +++ b/core-java-modules/core-java-sun/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java-sun jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java-time-measurements/pom.xml b/core-java-modules/core-java-time-measurements/pom.xml index b751cc0d74..67b8d7179a 100644 --- a/core-java-modules/core-java-time-measurements/pom.xml +++ b/core-java-modules/core-java-time-measurements/pom.xml @@ -9,12 +9,11 @@ 0.0.1-SNAPSHOT core-java-time-measurements jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/core-java/pom.xml b/core-java-modules/core-java/pom.xml index 9b89fffd40..b8d75058eb 100644 --- a/core-java-modules/core-java/pom.xml +++ b/core-java-modules/core-java/pom.xml @@ -8,12 +8,11 @@ 0.1.0-SNAPSHOT core-java jar - - com.baeldung - parent-java + com.baeldung.core-java-modules + core-java-modules 0.0.1-SNAPSHOT - ../../parent-java + ../ diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index c6cc3726e1..26c374b51d 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -11,8 +11,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-java + 0.0.1-SNAPSHOT + ../parent-java @@ -132,4 +133,37 @@ pre-jpms + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + + + + + + org.junit.jupiter + junit-jupiter + ${junit-jupiter.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit-jupiter.version} + test + + + + + + 2.22.2 + 5.6.2 + diff --git a/core-java-modules/pre-jpms/pom.xml b/core-java-modules/pre-jpms/pom.xml index 18a2566e92..9032c9475b 100644 --- a/core-java-modules/pre-jpms/pom.xml +++ b/core-java-modules/pre-jpms/pom.xml @@ -10,10 +10,10 @@ jar - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + ../