From 91da58e880b411d0a99000d555359c41d5af59f2 Mon Sep 17 00:00:00 2001 From: ajay74984 <51405689+ajay74984@users.noreply.github.com> Date: Wed, 12 Feb 2020 16:06:47 +0100 Subject: [PATCH 01/59] initial commit of Hexagonal Architecture --- spring-boot-modules/pom.xml | 1 + .../spring-boot-hexagonal/README.md | 4 + .../spring-boot-hexagonal/pom.xml | 76 +++++++++++++++++++ .../main/java/com/baeldung/Application.java | 13 ++++ .../adapter/DocumentRepositoryImpl.java | 24 ++++++ .../baeldung/adapter/DocumentRestAdapter.java | 24 ++++++ .../java/com/baeldung/domain/Document.java | 13 ++++ .../java/com/baeldung/port/DocumentRepo.java | 11 +++ .../com/baeldung/port/DocumentService.java | 11 +++ .../port/impl/DocumentServiceImpl.java | 24 ++++++ .../src/main/resources/application.properties | 1 + .../java/com/baeldung/ApplicationTests.java | 16 ++++ 12 files changed, 218 insertions(+) create mode 100644 spring-boot-modules/spring-boot-hexagonal/README.md create mode 100644 spring-boot-modules/spring-boot-hexagonal/pom.xml create mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java create mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java create mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java create mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java create mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentRepo.java create mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentService.java create mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/impl/DocumentServiceImpl.java create mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/resources/application.properties create mode 100644 spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationTests.java diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 234c52f638..3a503bf837 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -49,6 +49,7 @@ spring-boot-springdoc spring-boot-testing spring-boot-vue + spring-boot-hexagonal diff --git a/spring-boot-modules/spring-boot-hexagonal/README.md b/spring-boot-modules/spring-boot-hexagonal/README.md new file mode 100644 index 0000000000..44728b185e --- /dev/null +++ b/spring-boot-modules/spring-boot-hexagonal/README.md @@ -0,0 +1,4 @@ +## HEXAGONAL Architecture + +This module contains articles about Hexagonal Architecture implemented via Spring Boot. + diff --git a/spring-boot-modules/spring-boot-hexagonal/pom.xml b/spring-boot-modules/spring-boot-hexagonal/pom.xml new file mode 100644 index 0000000000..4d6109d24f --- /dev/null +++ b/spring-boot-modules/spring-boot-hexagonal/pom.xml @@ -0,0 +1,76 @@ + + + 4.0.0 + spring-boot-hexagonal + spring-boot-hexagonal + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + + + + org.projectlombok + lombok + 1.18.12 + + + + + + spring-boot-hexagonal + + + src/main/resources + true + + + + + org.springframework.boot + spring-boot-maven-plugin + + exec + + + + org.apache.maven.plugins + maven-assembly-plugin + + + jar-with-dependencies + + + + + make-assembly + package + + single + + + + + + + + + UTF-8 + + + diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..17be2b0d79 --- /dev/null +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java @@ -0,0 +1,13 @@ +package com.ajay.documentservice; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DocumentserviceApplication { + + public static void main(String[] args) { + SpringApplication.run(DocumentserviceApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java new file mode 100644 index 0000000000..e22ccb5cbf --- /dev/null +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java @@ -0,0 +1,24 @@ +package com.ajay.documentservice.adapter; + +import com.ajay.documentservice.domain.Document; +import com.ajay.documentservice.port.DocumentRepo; +import org.springframework.stereotype.Repository; + +import java.util.HashMap; +import java.util.Map; + +@Repository +public class DocumentRepositoryImpl implements DocumentRepo { + + private Map documentMap = new HashMap<>(); + + @Override + public void storeDocument(Document document) { + documentMap.put(document.getId(), document); + } + + @Override + public Document findDocumentById(String id) { + return documentMap.get(id); + } +} diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java new file mode 100644 index 0000000000..2a3cffb0e8 --- /dev/null +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java @@ -0,0 +1,24 @@ +package com.ajay.documentservice.adapter; + +import com.ajay.documentservice.domain.Document; +import com.ajay.documentservice.port.DocumentService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/doc") +public class DocumentRestAdapter { + @Autowired + private DocumentService documentService; + + @PostMapping + public void createDocument(@RequestBody Document document) { + documentService.createDocument(document); + } + + @GetMapping("/{id}") + public Document findById(@PathVariable String id) { + return documentService.findById(id); + } + +} diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java new file mode 100644 index 0000000000..14ab4900e2 --- /dev/null +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java @@ -0,0 +1,13 @@ +package com.ajay.documentservice.domain; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; + +@Data +@AllArgsConstructor +@Builder +public class Document { + private String id; + private String data; +} diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentRepo.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentRepo.java new file mode 100644 index 0000000000..2e18dd92ee --- /dev/null +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentRepo.java @@ -0,0 +1,11 @@ +package com.ajay.documentservice.port; + + +import com.ajay.documentservice.domain.Document; + +public interface DocumentRepo { + void storeDocument(Document document); + + Document findDocumentById(String id); +} + diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentService.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentService.java new file mode 100644 index 0000000000..6ed9edaf2c --- /dev/null +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentService.java @@ -0,0 +1,11 @@ +package com.ajay.documentservice.port; + +import com.ajay.documentservice.domain.Document; + +public interface DocumentService { + + void createDocument(Document document); + + Document findById(String id); + +} diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/impl/DocumentServiceImpl.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/impl/DocumentServiceImpl.java new file mode 100644 index 0000000000..2549ca834c --- /dev/null +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/impl/DocumentServiceImpl.java @@ -0,0 +1,24 @@ +package com.ajay.documentservice.port.impl; + +import com.ajay.documentservice.domain.Document; +import com.ajay.documentservice.port.DocumentRepo; +import com.ajay.documentservice.port.DocumentService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class DocumentServiceImpl implements DocumentService { + + @Autowired + private DocumentRepo documentRepo; + + @Override + public void createDocument(Document document) { + documentRepo.storeDocument(document); + } + + @Override + public Document findById(String id) { + return documentRepo.findDocumentById(id); + } +} diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/resources/application.properties b/spring-boot-modules/spring-boot-hexagonal/src/main/resources/application.properties new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationTests.java b/spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationTests.java new file mode 100644 index 0000000000..ce3b754df3 --- /dev/null +++ b/spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationTests.java @@ -0,0 +1,16 @@ +package com.ajay.documentservice.documentservice; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@SpringBootTest +@RunWith(SpringRunner.class) +class ApplicationTests { + + @Test + public void contextLoads() { + } + +} From 563b6b7a89896bc643a22d227b4318529360a67a Mon Sep 17 00:00:00 2001 From: ajay74984 <51405689+ajay74984@users.noreply.github.com> Date: Wed, 12 Feb 2020 16:10:36 +0100 Subject: [PATCH 02/59] updated package name --- .../src/main/java/com/baeldung/Application.java | 2 +- .../main/java/com/baeldung/adapter/DocumentRepositoryImpl.java | 2 +- .../src/main/java/com/baeldung/adapter/DocumentRestAdapter.java | 2 +- .../src/main/java/com/baeldung/domain/Document.java | 2 +- .../src/main/java/com/baeldung/port/DocumentRepo.java | 2 +- .../src/main/java/com/baeldung/port/DocumentService.java | 2 +- .../main/java/com/baeldung/port/impl/DocumentServiceImpl.java | 2 +- .../src/test/java/com/baeldung/ApplicationTests.java | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java index 17be2b0d79..5e4bcc0435 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java @@ -1,4 +1,4 @@ -package com.ajay.documentservice; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java index e22ccb5cbf..eabdaa63b8 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java @@ -1,4 +1,4 @@ -package com.ajay.documentservice.adapter; +package com.baeldung.adapter; import com.ajay.documentservice.domain.Document; import com.ajay.documentservice.port.DocumentRepo; diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java index 2a3cffb0e8..d8c89d5c6e 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java @@ -1,4 +1,4 @@ -package com.ajay.documentservice.adapter; +package com.baeldung.adapter; import com.ajay.documentservice.domain.Document; import com.ajay.documentservice.port.DocumentService; diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java index 14ab4900e2..77c1079cdc 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java @@ -1,4 +1,4 @@ -package com.ajay.documentservice.domain; +package com.baeldung.domain; import lombok.AllArgsConstructor; import lombok.Builder; diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentRepo.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentRepo.java index 2e18dd92ee..d5591f9aa4 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentRepo.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentRepo.java @@ -1,4 +1,4 @@ -package com.ajay.documentservice.port; +package com.baeldung.port; import com.ajay.documentservice.domain.Document; diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentService.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentService.java index 6ed9edaf2c..5df49efa88 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentService.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentService.java @@ -1,4 +1,4 @@ -package com.ajay.documentservice.port; +package com.baeldung.port; import com.ajay.documentservice.domain.Document; diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/impl/DocumentServiceImpl.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/impl/DocumentServiceImpl.java index 2549ca834c..a2942b2d59 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/impl/DocumentServiceImpl.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/impl/DocumentServiceImpl.java @@ -1,4 +1,4 @@ -package com.ajay.documentservice.port.impl; +package com.baeldung.port.impl; import com.ajay.documentservice.domain.Document; import com.ajay.documentservice.port.DocumentRepo; diff --git a/spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationTests.java b/spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationTests.java index ce3b754df3..f531a9fba0 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationTests.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationTests.java @@ -1,4 +1,4 @@ -package com.ajay.documentservice.documentservice; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; From 7feb7bf9d8d22dfc015b969eda13e5c76e3e6426 Mon Sep 17 00:00:00 2001 From: ajay74984 <51405689+ajay74984@users.noreply.github.com> Date: Wed, 12 Feb 2020 17:15:44 +0100 Subject: [PATCH 03/59] renamed packages. --- .../spring-boot-hexagonal/pom.xml | 6 ----- .../main/java/com/baeldung/Application.java | 4 ++-- .../adapter/DocumentRepositoryImpl.java | 5 +++-- .../baeldung/adapter/DocumentRestAdapter.java | 6 +++-- .../java/com/baeldung/domain/Document.java | 22 +++++++++++++------ .../java/com/baeldung/port/DocumentRepo.java | 3 +-- .../com/baeldung/port/DocumentService.java | 2 +- .../port/impl/DocumentServiceImpl.java | 7 +++--- ...ionTests.java => ApplicationUnitTest.java} | 2 +- 9 files changed, 31 insertions(+), 26 deletions(-) rename spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/{ApplicationTests.java => ApplicationUnitTest.java} (91%) diff --git a/spring-boot-modules/spring-boot-hexagonal/pom.xml b/spring-boot-modules/spring-boot-hexagonal/pom.xml index 4d6109d24f..54d61fa806 100644 --- a/spring-boot-modules/spring-boot-hexagonal/pom.xml +++ b/spring-boot-modules/spring-boot-hexagonal/pom.xml @@ -24,12 +24,6 @@ spring-boot-starter-test - - org.projectlombok - lombok - 1.18.12 - - diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java index 5e4bcc0435..a898f9cf05 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java @@ -4,10 +4,10 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication -public class DocumentserviceApplication { +public class Application { public static void main(String[] args) { - SpringApplication.run(DocumentserviceApplication.class, args); + SpringApplication.run(Application.class, args); } } diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java index eabdaa63b8..1248133665 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java @@ -1,9 +1,10 @@ package com.baeldung.adapter; -import com.ajay.documentservice.domain.Document; -import com.ajay.documentservice.port.DocumentRepo; import org.springframework.stereotype.Repository; +import com.baeldung.domain.Document; +import com.baeldung.port.DocumentRepo; + import java.util.HashMap; import java.util.Map; diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java index d8c89d5c6e..e7fa5d0b42 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java @@ -1,10 +1,12 @@ package com.baeldung.adapter; -import com.ajay.documentservice.domain.Document; -import com.ajay.documentservice.port.DocumentService; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; +import com.baeldung.domain.Document; +import com.baeldung.port.DocumentService; + @RestController @RequestMapping("/doc") public class DocumentRestAdapter { diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java index 77c1079cdc..58381d536d 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java @@ -1,13 +1,21 @@ package com.baeldung.domain; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; - -@Data -@AllArgsConstructor -@Builder public class Document { private String id; private String data; + + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public String getData() { + return data; + } + public void setData(String data) { + this.data = data; + } + + } diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentRepo.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentRepo.java index d5591f9aa4..96dba3d954 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentRepo.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentRepo.java @@ -1,7 +1,6 @@ package com.baeldung.port; - -import com.ajay.documentservice.domain.Document; +import com.baeldung.domain.Document; public interface DocumentRepo { void storeDocument(Document document); diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentService.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentService.java index 5df49efa88..5d5bfb2035 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentService.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentService.java @@ -1,6 +1,6 @@ package com.baeldung.port; -import com.ajay.documentservice.domain.Document; +import com.baeldung.domain.Document; public interface DocumentService { diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/impl/DocumentServiceImpl.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/impl/DocumentServiceImpl.java index a2942b2d59..1b50e1efe2 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/impl/DocumentServiceImpl.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/impl/DocumentServiceImpl.java @@ -1,11 +1,12 @@ package com.baeldung.port.impl; -import com.ajay.documentservice.domain.Document; -import com.ajay.documentservice.port.DocumentRepo; -import com.ajay.documentservice.port.DocumentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import com.baeldung.domain.Document; +import com.baeldung.port.DocumentRepo; +import com.baeldung.port.DocumentService; + @Service public class DocumentServiceImpl implements DocumentService { diff --git a/spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationTests.java b/spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationUnitTest.java similarity index 91% rename from spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationTests.java rename to spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationUnitTest.java index f531a9fba0..f7592c0cc8 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationTests.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationUnitTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest @RunWith(SpringRunner.class) -class ApplicationTests { +class ApplicationUnitTest { @Test public void contextLoads() { From d868eda952f0698e0568dfbab26134a06f47c001 Mon Sep 17 00:00:00 2001 From: ajay74984 <51405689+ajay74984@users.noreply.github.com> Date: Sat, 15 Feb 2020 09:32:50 +0100 Subject: [PATCH 04/59] reformatted as per standard formatter and incorporated review comments. --- .../spring-boot-hexagonal/pom.xml | 102 ++++++++---------- .../main/java/com/baeldung/Application.java | 10 +- .../adapter/DocumentRepositoryImpl.java | 26 ++--- .../baeldung/adapter/DocumentRestAdapter.java | 29 +++-- .../java/com/baeldung/domain/Document.java | 36 ++++--- .../baeldung/domain/port/DocumentRepo.java | 9 ++ .../baeldung/domain/port/DocumentService.java | 11 ++ .../domain/port/impl/DocumentServiceImpl.java | 25 +++++ .../java/com/baeldung/port/DocumentRepo.java | 10 -- .../com/baeldung/port/DocumentService.java | 11 -- .../port/impl/DocumentServiceImpl.java | 25 ----- .../com/baeldung/ApplicationUnitTest.java | 10 +- 12 files changed, 143 insertions(+), 161 deletions(-) create mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/DocumentRepo.java create mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/DocumentService.java create mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/impl/DocumentServiceImpl.java delete mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentRepo.java delete mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentService.java delete mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/impl/DocumentServiceImpl.java diff --git a/spring-boot-modules/spring-boot-hexagonal/pom.xml b/spring-boot-modules/spring-boot-hexagonal/pom.xml index 54d61fa806..c4ff36c2cf 100644 --- a/spring-boot-modules/spring-boot-hexagonal/pom.xml +++ b/spring-boot-modules/spring-boot-hexagonal/pom.xml @@ -1,70 +1,52 @@ - 4.0.0 - spring-boot-hexagonal - spring-boot-hexagonal + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + 4.0.0 + spring-boot-hexagonal + spring-boot-hexagonal - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - + + 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-web + - - org.springframework.boot - spring-boot-starter-test - + + org.springframework.boot + spring-boot-starter-test + - + - - spring-boot-hexagonal - - - src/main/resources - true - - - - - org.springframework.boot - spring-boot-maven-plugin - - exec - - - - org.apache.maven.plugins - maven-assembly-plugin - - - jar-with-dependencies - - - - - make-assembly - package - - single - - - - - - + + spring-boot-hexagonal + + + src/main/resources + true + + + + + org.springframework.boot + spring-boot-maven-plugin + + exec + + + + - - UTF-8 - + + UTF-8 + diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java index a898f9cf05..37dbe7dab8 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java @@ -5,9 +5,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + } diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java index 1248133665..32414442ef 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java @@ -3,23 +3,23 @@ package com.baeldung.adapter; import org.springframework.stereotype.Repository; import com.baeldung.domain.Document; -import com.baeldung.port.DocumentRepo; +import com.baeldung.domain.port.DocumentRepo; import java.util.HashMap; import java.util.Map; @Repository public class DocumentRepositoryImpl implements DocumentRepo { - - private Map documentMap = new HashMap<>(); - - @Override - public void storeDocument(Document document) { - documentMap.put(document.getId(), document); - } - - @Override - public Document findDocumentById(String id) { - return documentMap.get(id); - } + + private Map documentMap = new HashMap<>(); + + @Override + public void storeDocument(Document document) { + documentMap.put(document.getId(), document); + } + + @Override + public Document findDocumentById(String id) { + return documentMap.get(id); + } } diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java index e7fa5d0b42..985a5257c0 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java @@ -1,26 +1,25 @@ package com.baeldung.adapter; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.baeldung.domain.Document; -import com.baeldung.port.DocumentService; +import com.baeldung.domain.port.DocumentService; @RestController @RequestMapping("/doc") public class DocumentRestAdapter { - @Autowired - private DocumentService documentService; - - @PostMapping - public void createDocument(@RequestBody Document document) { - documentService.createDocument(document); - } - - @GetMapping("/{id}") - public Document findById(@PathVariable String id) { - return documentService.findById(id); - } - + @Autowired + private DocumentService documentService; + + @PostMapping + public void createDocument(@RequestBody Document document) { + documentService.createDocument(document); + } + + @GetMapping("/{id}") + public Document findById(@PathVariable String id) { + return documentService.findById(id); + } + } diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java index 58381d536d..24d0a95071 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java @@ -1,21 +1,23 @@ package com.baeldung.domain; public class Document { - private String id; - private String data; - - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - public String getData() { - return data; - } - public void setData(String data) { - this.data = data; - } - - + private String id; + private String data; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + } diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/DocumentRepo.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/DocumentRepo.java new file mode 100644 index 0000000000..001e3251e4 --- /dev/null +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/DocumentRepo.java @@ -0,0 +1,9 @@ +package com.baeldung.domain.port; + +import com.baeldung.domain.Document; + +public interface DocumentRepo { + void storeDocument(Document document); + + Document findDocumentById(String id); +} diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/DocumentService.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/DocumentService.java new file mode 100644 index 0000000000..009c26c01f --- /dev/null +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/DocumentService.java @@ -0,0 +1,11 @@ +package com.baeldung.domain.port; + +import com.baeldung.domain.Document; + +public interface DocumentService { + + void createDocument(Document document); + + Document findById(String id); + +} diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/impl/DocumentServiceImpl.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/impl/DocumentServiceImpl.java new file mode 100644 index 0000000000..f5c351406e --- /dev/null +++ b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/impl/DocumentServiceImpl.java @@ -0,0 +1,25 @@ +package com.baeldung.domain.port.impl; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.baeldung.domain.Document; +import com.baeldung.domain.port.DocumentRepo; +import com.baeldung.domain.port.DocumentService; + +@Service +public class DocumentServiceImpl implements DocumentService { + + @Autowired + private DocumentRepo documentRepo; + + @Override + public void createDocument(Document document) { + documentRepo.storeDocument(document); + } + + @Override + public Document findById(String id) { + return documentRepo.findDocumentById(id); + } +} diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentRepo.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentRepo.java deleted file mode 100644 index 96dba3d954..0000000000 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentRepo.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.port; - -import com.baeldung.domain.Document; - -public interface DocumentRepo { - void storeDocument(Document document); - - Document findDocumentById(String id); -} - diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentService.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentService.java deleted file mode 100644 index 5d5bfb2035..0000000000 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/DocumentService.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.port; - -import com.baeldung.domain.Document; - -public interface DocumentService { - - void createDocument(Document document); - - Document findById(String id); - -} diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/impl/DocumentServiceImpl.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/impl/DocumentServiceImpl.java deleted file mode 100644 index 1b50e1efe2..0000000000 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/port/impl/DocumentServiceImpl.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.port.impl; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.baeldung.domain.Document; -import com.baeldung.port.DocumentRepo; -import com.baeldung.port.DocumentService; - -@Service -public class DocumentServiceImpl implements DocumentService { - - @Autowired - private DocumentRepo documentRepo; - - @Override - public void createDocument(Document document) { - documentRepo.storeDocument(document); - } - - @Override - public Document findById(String id) { - return documentRepo.findDocumentById(id); - } -} diff --git a/spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationUnitTest.java b/spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationUnitTest.java index f7592c0cc8..2ce9b1cf24 100644 --- a/spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationUnitTest.java +++ b/spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationUnitTest.java @@ -8,9 +8,9 @@ import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest @RunWith(SpringRunner.class) class ApplicationUnitTest { - - @Test - public void contextLoads() { - } - + + @Test + public void contextLoads() { + } + } From 523ad7f7767fa6f17f7e468e19ec78e7e5860518 Mon Sep 17 00:00:00 2001 From: ajay74984 <51405689+ajay74984@users.noreply.github.com> Date: Sat, 7 Mar 2020 15:21:12 +0100 Subject: [PATCH 05/59] java abstract number class --- .../AbstractNumberUnitTest.java | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 java-numbers-3/src/test/java/com/baeldung/abstractnumber/AbstractNumberUnitTest.java diff --git a/java-numbers-3/src/test/java/com/baeldung/abstractnumber/AbstractNumberUnitTest.java b/java-numbers-3/src/test/java/com/baeldung/abstractnumber/AbstractNumberUnitTest.java new file mode 100644 index 0000000000..521f2d37a6 --- /dev/null +++ b/java-numbers-3/src/test/java/com/baeldung/abstractnumber/AbstractNumberUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.abstractnumber; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class AbstractNumberUnitTest { + + private final static double DOUBLE_VALUE = 9999.999; + private final static float FLOAT_VALUE = 101.99F; + private final static long LONG_VALUE = 1000L; + private final static int INTEGER_VALUE = 100; + private final static short SHORT_VALUE = 127; + private final static byte BYTE_VALUE = 120; + + @Test + public void givenDoubleValue_whenShortValueUsed_thenShortValueReturned() { + Double doubleValue = Double.valueOf(DOUBLE_VALUE); + assertEquals(9999, doubleValue.shortValue()); + } + + @Test + public void givenFloatValue_whenByteValueUsed_thenByteValueReturned() { + Float floatValue = Float.valueOf(FLOAT_VALUE); + assertEquals(101, floatValue.byteValue()); + } + + @Test + public void givenLongValue_whenInitValueUsed_thenInitValueReturned() { + Long longValue = Long.valueOf(LONG_VALUE); + assertEquals(1000, longValue.intValue()); + } + + @Test + public void givenIntegerValue_whenLongValueUsed_thenLongValueReturned() { + Integer integerValue = Integer.valueOf(INTEGER_VALUE); + assertEquals(100, integerValue.longValue()); + } + + @Test + public void givenShortValue_whenFloatValueUsed_thenFloatValueReturned() { + Short shortValue = Short.valueOf(SHORT_VALUE); + assertEquals(127.0F, shortValue.floatValue(), 0); + } + + @Test + public void givenByteValue_whenDoubleValueUsed_thenDoubleValueReturned() { + Byte byteValue = Byte.valueOf(BYTE_VALUE); + assertEquals(120.0, byteValue.doubleValue(), 0); + } + +} From 9860318a485ac6705f4457f2d49d4460df331975 Mon Sep 17 00:00:00 2001 From: ramkumarvenkat Date: Tue, 10 Mar 2020 16:35:00 +0530 Subject: [PATCH 06/59] Guava MapMaker --- .../guava/mapmaker/GuavaMapMakerUnitTest.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java diff --git a/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java b/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java new file mode 100644 index 0000000000..36c0cd8493 --- /dev/null +++ b/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.guava.mapmaker; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertEquals; + +import com.google.common.collect.MapMaker; +import org.junit.Test; + +import java.util.concurrent.ConcurrentMap; + +public class GuavaMapMakerUnitTest { + @Test + public void whenMakeMap_thenCreated() { + ConcurrentMap m = new MapMaker() + .makeMap(); + assertNotNull(m); + } + + @Test + public void whenMakeMapWithWeakKeys_thenCreated() { + ConcurrentMap m = new MapMaker() + .weakKeys() + .makeMap(); + assertNotNull(m); + } + + @Test + public void whenMakeMapWithWeakValues_thenCreated() { + ConcurrentMap m = new MapMaker() + .weakValues() + .makeMap(); + assertNotNull(m); + } + + @Test + public void whenMakeMapWithInitialCapacity_thenCreated() { + ConcurrentMap m = new MapMaker() + .initialCapacity(10) + .makeMap(); + assertNotNull(m); + } + + @Test + public void whenMakeMapWithConcurrencyLevel_thenCreated() { + ConcurrentMap m = new MapMaker() + .concurrencyLevel(10) + .makeMap(); + assertNotNull(m); + } +} From 79433c0396ed3a147fecf0aa3d531486ba5b00c8 Mon Sep 17 00:00:00 2001 From: ramkumarvenkat Date: Thu, 12 Mar 2020 07:35:47 +0530 Subject: [PATCH 07/59] Fixed comments --- .../guava/mapmaker/GuavaMapMakerUnitTest.java | 49 +++++++------------ 1 file changed, 17 insertions(+), 32 deletions(-) diff --git a/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java b/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java index 36c0cd8493..d9a5fc6cd8 100644 --- a/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java +++ b/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java @@ -1,50 +1,35 @@ package com.baeldung.guava.mapmaker; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertEquals; - import com.google.common.collect.MapMaker; import org.junit.Test; import java.util.concurrent.ConcurrentMap; +import static org.junit.Assert.assertNotNull; + public class GuavaMapMakerUnitTest { - @Test - public void whenMakeMap_thenCreated() { - ConcurrentMap m = new MapMaker() - .makeMap(); - assertNotNull(m); + @Test public void whenMakeMap_thenCreated() { + ConcurrentMap concurrentMap = new MapMaker().makeMap(); + assertNotNull(concurrentMap); } - @Test - public void whenMakeMapWithWeakKeys_thenCreated() { - ConcurrentMap m = new MapMaker() - .weakKeys() - .makeMap(); - assertNotNull(m); + @Test public void whenMakeMapWithWeakKeys_thenCreated() { + ConcurrentMap concurrentMap = new MapMaker().weakKeys().makeMap(); + assertNotNull(concurrentMap); } - @Test - public void whenMakeMapWithWeakValues_thenCreated() { - ConcurrentMap m = new MapMaker() - .weakValues() - .makeMap(); - assertNotNull(m); + @Test public void whenMakeMapWithWeakValues_thenCreated() { + ConcurrentMap concurrentMap = new MapMaker().weakValues().makeMap(); + assertNotNull(concurrentMap); } - @Test - public void whenMakeMapWithInitialCapacity_thenCreated() { - ConcurrentMap m = new MapMaker() - .initialCapacity(10) - .makeMap(); - assertNotNull(m); + @Test public void whenMakeMapWithInitialCapacity_thenCreated() { + ConcurrentMap concurrentMap = new MapMaker().initialCapacity(10).makeMap(); + assertNotNull(concurrentMap); } - @Test - public void whenMakeMapWithConcurrencyLevel_thenCreated() { - ConcurrentMap m = new MapMaker() - .concurrencyLevel(10) - .makeMap(); - assertNotNull(m); + @Test public void whenMakeMapWithConcurrencyLevel_thenCreated() { + ConcurrentMap concurrentMap = new MapMaker().concurrencyLevel(10).makeMap(); + assertNotNull(concurrentMap); } } From 20ef5cc79928cbc51ed4ff1e4a2f35047c03ee18 Mon Sep 17 00:00:00 2001 From: ajay74984 <51405689+ajay74984@users.noreply.github.com> Date: Sat, 14 Mar 2020 11:52:42 +0100 Subject: [PATCH 08/59] added new section --- java-numbers-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/java-numbers-3/README.md b/java-numbers-3/README.md index 08e8dae8ef..a331a979ad 100644 --- a/java-numbers-3/README.md +++ b/java-numbers-3/README.md @@ -2,3 +2,4 @@ - [Generating Random Numbers](https://www.baeldung.com/java-generating-random-numbers) - [Convert Double to Long in Java](https://www.baeldung.com/java-convert-double-long) +- [Guide to the Java Number Class](http://inprogress.baeldung.com/?p=180694&preview=true) From 6c78ed9be0dc47684cfb9716b50f405304148258 Mon Sep 17 00:00:00 2001 From: ajay74984 <51405689+ajay74984@users.noreply.github.com> Date: Sat, 14 Mar 2020 12:25:31 +0100 Subject: [PATCH 09/59] REmoved files --- .../spring-boot-hexagonal/README.md | 4 -- .../spring-boot-hexagonal/pom.xml | 52 ------------------- .../main/java/com/baeldung/Application.java | 13 ----- .../adapter/DocumentRepositoryImpl.java | 25 --------- .../baeldung/adapter/DocumentRestAdapter.java | 25 --------- .../java/com/baeldung/domain/Document.java | 23 -------- .../baeldung/domain/port/DocumentRepo.java | 9 ---- .../baeldung/domain/port/DocumentService.java | 11 ---- .../domain/port/impl/DocumentServiceImpl.java | 25 --------- .../src/main/resources/application.properties | 1 - .../com/baeldung/ApplicationUnitTest.java | 16 ------ 11 files changed, 204 deletions(-) delete mode 100644 spring-boot-modules/spring-boot-hexagonal/README.md delete mode 100644 spring-boot-modules/spring-boot-hexagonal/pom.xml delete mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java delete mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java delete mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java delete mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java delete mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/DocumentRepo.java delete mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/DocumentService.java delete mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/impl/DocumentServiceImpl.java delete mode 100644 spring-boot-modules/spring-boot-hexagonal/src/main/resources/application.properties delete mode 100644 spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationUnitTest.java diff --git a/spring-boot-modules/spring-boot-hexagonal/README.md b/spring-boot-modules/spring-boot-hexagonal/README.md deleted file mode 100644 index 44728b185e..0000000000 --- a/spring-boot-modules/spring-boot-hexagonal/README.md +++ /dev/null @@ -1,4 +0,0 @@ -## HEXAGONAL Architecture - -This module contains articles about Hexagonal Architecture implemented via Spring Boot. - diff --git a/spring-boot-modules/spring-boot-hexagonal/pom.xml b/spring-boot-modules/spring-boot-hexagonal/pom.xml deleted file mode 100644 index c4ff36c2cf..0000000000 --- a/spring-boot-modules/spring-boot-hexagonal/pom.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - 4.0.0 - spring-boot-hexagonal - spring-boot-hexagonal - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-test - - - - - - spring-boot-hexagonal - - - src/main/resources - true - - - - - org.springframework.boot - spring-boot-maven-plugin - - exec - - - - - - - UTF-8 - - - diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java deleted file mode 100644 index 37dbe7dab8..0000000000 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/Application.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java deleted file mode 100644 index 32414442ef..0000000000 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRepositoryImpl.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.adapter; - -import org.springframework.stereotype.Repository; - -import com.baeldung.domain.Document; -import com.baeldung.domain.port.DocumentRepo; - -import java.util.HashMap; -import java.util.Map; - -@Repository -public class DocumentRepositoryImpl implements DocumentRepo { - - private Map documentMap = new HashMap<>(); - - @Override - public void storeDocument(Document document) { - documentMap.put(document.getId(), document); - } - - @Override - public Document findDocumentById(String id) { - return documentMap.get(id); - } -} diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java deleted file mode 100644 index 985a5257c0..0000000000 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/adapter/DocumentRestAdapter.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.adapter; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -import com.baeldung.domain.Document; -import com.baeldung.domain.port.DocumentService; - -@RestController -@RequestMapping("/doc") -public class DocumentRestAdapter { - @Autowired - private DocumentService documentService; - - @PostMapping - public void createDocument(@RequestBody Document document) { - documentService.createDocument(document); - } - - @GetMapping("/{id}") - public Document findById(@PathVariable String id) { - return documentService.findById(id); - } - -} diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java deleted file mode 100644 index 24d0a95071..0000000000 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/Document.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.domain; - -public class Document { - private String id; - private String data; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getData() { - return data; - } - - public void setData(String data) { - this.data = data; - } - -} diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/DocumentRepo.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/DocumentRepo.java deleted file mode 100644 index 001e3251e4..0000000000 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/DocumentRepo.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.domain.port; - -import com.baeldung.domain.Document; - -public interface DocumentRepo { - void storeDocument(Document document); - - Document findDocumentById(String id); -} diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/DocumentService.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/DocumentService.java deleted file mode 100644 index 009c26c01f..0000000000 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/DocumentService.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.domain.port; - -import com.baeldung.domain.Document; - -public interface DocumentService { - - void createDocument(Document document); - - Document findById(String id); - -} diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/impl/DocumentServiceImpl.java b/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/impl/DocumentServiceImpl.java deleted file mode 100644 index f5c351406e..0000000000 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/java/com/baeldung/domain/port/impl/DocumentServiceImpl.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.domain.port.impl; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.baeldung.domain.Document; -import com.baeldung.domain.port.DocumentRepo; -import com.baeldung.domain.port.DocumentService; - -@Service -public class DocumentServiceImpl implements DocumentService { - - @Autowired - private DocumentRepo documentRepo; - - @Override - public void createDocument(Document document) { - documentRepo.storeDocument(document); - } - - @Override - public Document findById(String id) { - return documentRepo.findDocumentById(id); - } -} diff --git a/spring-boot-modules/spring-boot-hexagonal/src/main/resources/application.properties b/spring-boot-modules/spring-boot-hexagonal/src/main/resources/application.properties deleted file mode 100644 index 8b13789179..0000000000 --- a/spring-boot-modules/spring-boot-hexagonal/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ - diff --git a/spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationUnitTest.java b/spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationUnitTest.java deleted file mode 100644 index 2ce9b1cf24..0000000000 --- a/spring-boot-modules/spring-boot-hexagonal/src/test/java/com/baeldung/ApplicationUnitTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@SpringBootTest -@RunWith(SpringRunner.class) -class ApplicationUnitTest { - - @Test - public void contextLoads() { - } - -} From 2fca6d60de37440c3e632c61f796134c410dd99d Mon Sep 17 00:00:00 2001 From: ajay74984 <51405689+ajay74984@users.noreply.github.com> Date: Sat, 14 Mar 2020 12:29:22 +0100 Subject: [PATCH 10/59] cleanup --- spring-boot-modules/pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 16541408a4..c8d153d4bb 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -53,7 +53,6 @@ spring-boot-springdoc spring-boot-testing spring-boot-vue - spring-boot-hexagonal From 2c0cf3e2e02de86f36e65212248f8625657c8c28 Mon Sep 17 00:00:00 2001 From: mike b Date: Sun, 15 Mar 2020 14:14:46 -0400 Subject: [PATCH 11/59] [BAEL-3646] Conditional Flow in Spring Batch --- .../ConditionalFlowApplication.java | 18 ++++ .../conditionalflow/NumberInfoDecider.java | 19 +++++ .../config/NumberInfoConfig.java | 85 +++++++++++++++++++ .../conditionalflow/model/NumberInfo.java | 47 ++++++++++ .../conditionalflow/step/NotifierTasklet.java | 14 +++ .../step/NumberInfoClassifier.java | 31 +++++++ .../step/NumberInfoClassifierWithDecider.java | 15 ++++ .../step/NumberInfoGenerator.java | 23 +++++ .../step/NumberInfoProcessor.java | 17 ++++ .../step/PrependingStdoutWriter.java | 30 +++++++ .../model/NumberInfoUnitTest.java | 44 ++++++++++ .../step/NumberInfoClassifierUnitTest.java | 17 ++++ .../step/NumberInfoGeneratorUnitTest.java | 20 +++++ 13 files changed, 380 insertions(+) create mode 100644 spring-batch/src/main/java/org/baeldung/conditionalflow/ConditionalFlowApplication.java create mode 100644 spring-batch/src/main/java/org/baeldung/conditionalflow/NumberInfoDecider.java create mode 100644 spring-batch/src/main/java/org/baeldung/conditionalflow/config/NumberInfoConfig.java create mode 100644 spring-batch/src/main/java/org/baeldung/conditionalflow/model/NumberInfo.java create mode 100644 spring-batch/src/main/java/org/baeldung/conditionalflow/step/NotifierTasklet.java create mode 100644 spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java create mode 100644 spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java create mode 100644 spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoGenerator.java create mode 100644 spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoProcessor.java create mode 100644 spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java create mode 100644 spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java create mode 100644 spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java create mode 100644 spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/ConditionalFlowApplication.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/ConditionalFlowApplication.java new file mode 100644 index 0000000000..8b6c841b6e --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/ConditionalFlowApplication.java @@ -0,0 +1,18 @@ +package org.baeldung.conditionalflow; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ConditionalFlowApplication implements CommandLineRunner { + + public static void main(String[] args) { + SpringApplication.run(ConditionalFlowApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + System.out.println("Running and exiting"); + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/NumberInfoDecider.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/NumberInfoDecider.java new file mode 100644 index 0000000000..017980f1a4 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/NumberInfoDecider.java @@ -0,0 +1,19 @@ +package org.baeldung.conditionalflow; + +import org.springframework.batch.core.ExitStatus; +import org.springframework.batch.core.JobExecution; +import org.springframework.batch.core.StepExecution; +import org.springframework.batch.core.job.flow.FlowExecutionStatus; +import org.springframework.batch.core.job.flow.JobExecutionDecider; + +public class NumberInfoDecider implements JobExecutionDecider { + + @Override + public FlowExecutionStatus decide(JobExecution jobExecution, StepExecution stepExecution) { + if(jobExecution.getExitStatus().equals("UNKNOWN")) { + return new FlowExecutionStatus("NOTIFY"); + } else { + return null; + } + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/config/NumberInfoConfig.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/config/NumberInfoConfig.java new file mode 100644 index 0000000000..fd28c2291f --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/config/NumberInfoConfig.java @@ -0,0 +1,85 @@ +package org.baeldung.conditionalflow.config; + +import org.baeldung.conditionalflow.NumberInfoDecider; +import org.baeldung.conditionalflow.model.NumberInfo; +import org.baeldung.conditionalflow.step.*; +import org.springframework.batch.core.Job; +import org.springframework.batch.core.Step; +import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; +import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; +import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableBatchProcessing +public class NumberInfoConfig { + + @Bean + @Qualifier("NotificationStep") + public Step notificationStep(StepBuilderFactory sbf) { + return sbf.get("Billing step").tasklet(new NotifierTasklet()).build(); + } + + public Step numberGeneratorStep(StepBuilderFactory sbf, int[] values, String prepend) { + return sbf.get("Number generator") + .chunk(1) + .reader(new NumberInfoGenerator(values)) + .processor(new NumberInfoClassifier()) + .writer(new PrependingStdoutWriter<>(prepend)) + .build(); + } + + public Step numberGeneratorStepDecider(StepBuilderFactory sbf, int[] values, String prepend) { + return sbf.get("Number generator") + .chunk(1) + .reader(new NumberInfoGenerator(values)) + .processor(new NumberInfoClassifierWithDecider()) + .writer(new PrependingStdoutWriter<>(prepend)) + .build(); + } + + @Bean + public Job numberGeneratorNonNotifierJob(JobBuilderFactory jobBuilderFactory, + StepBuilderFactory stepBuilderFactory, + @Qualifier("NotificationStep") Step notificationStep + ) { + int[] nonNotifierData = {-1, -2, -3}; + Step step = numberGeneratorStep(stepBuilderFactory, nonNotifierData, "First Dataset Processor"); + return jobBuilderFactory.get("Number generator - first dataset") + .start(step) + .on("NOTIFY").to(notificationStep) + .from(step).on("*").stop() + .end() + .build(); + } + + @Bean + public Job numberGeneratorNotifierJob(JobBuilderFactory jobBuilderFactory, + StepBuilderFactory stepBuilderFactory, + @Qualifier("NotificationStep") Step notificationStep + ) { + int[] billableData = {11, -2, -3}; + Step dataProviderStep = numberGeneratorStep(stepBuilderFactory, billableData, "Second Dataset Processor"); + return jobBuilderFactory.get("Number generator - second dataset") + .start(dataProviderStep) + .on("NOTIFY").to(notificationStep) + .end() + .build(); + } + + @Bean + public Job numberGeneratorNotifierJobWithDecider(JobBuilderFactory jobBuilderFactory, + StepBuilderFactory stepBuilderFactory, + @Qualifier("NotificationStep") Step notificationStep + ) { + int[] billableData = {11, -2, -3}; + Step dataProviderStep = numberGeneratorStepDecider(stepBuilderFactory, billableData, "Third Dataset Processor"); + return jobBuilderFactory.get("Number generator - third dataset") + .start(dataProviderStep) + .next(new NumberInfoDecider()).on("NOTIFY").to(notificationStep) + .end() + .build(); + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/model/NumberInfo.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/model/NumberInfo.java new file mode 100644 index 0000000000..81bd67d2a1 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/model/NumberInfo.java @@ -0,0 +1,47 @@ +package org.baeldung.conditionalflow.model; + +import java.util.Objects; + +public class NumberInfo { + private int number; + + public static NumberInfo from(int number){ + return new NumberInfo(number); + } + + public NumberInfo(int number) { + this.number = number; + } + + public boolean isPositive() { + return number > 0; + } + + public boolean isEven() { + return number % 2 == 0; + } + + public int getNumber() { + return number; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + NumberInfo that = (NumberInfo) o; + return number == that.number; + } + + @Override + public int hashCode() { + return Objects.hash(number); + } + + @Override + public String toString() { + return "NumberInfo{" + + "number=" + number + + '}'; + } +} \ No newline at end of file diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NotifierTasklet.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NotifierTasklet.java new file mode 100644 index 0000000000..6a88edcbbe --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NotifierTasklet.java @@ -0,0 +1,14 @@ +package org.baeldung.conditionalflow.step; + +import org.springframework.batch.core.StepContribution; +import org.springframework.batch.core.scope.context.ChunkContext; +import org.springframework.batch.core.step.tasklet.Tasklet; +import org.springframework.batch.repeat.RepeatStatus; + +public class NotifierTasklet implements Tasklet { + @Override + public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception { + System.err.println("[" + chunkContext.getStepContext().getJobName() + "] contains interesting data!!"); + return RepeatStatus.FINISHED; + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java new file mode 100644 index 0000000000..95b1e4d155 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java @@ -0,0 +1,31 @@ +package org.baeldung.conditionalflow.step; + +import org.baeldung.conditionalflow.model.NumberInfo; +import org.springframework.batch.core.ExitStatus; +import org.springframework.batch.core.StepExecution; +import org.springframework.batch.core.annotation.BeforeStep; +import org.springframework.batch.core.listener.ItemListenerSupport; +import org.springframework.batch.item.ItemProcessor; + +public class NumberInfoClassifier extends ItemListenerSupport + implements ItemProcessor { + private StepExecution stepExecution; + + @BeforeStep + public void beforeStep(StepExecution stepExecution) { + this.stepExecution = stepExecution; + } + + @Override + public void afterProcess(NumberInfo item, Integer result) { + super.afterProcess(item, result); + if (item.isPositive()) { + stepExecution.setExitStatus(new ExitStatus("NOTIFY")); + } + } + + @Override + public Integer process(NumberInfo numberInfo) throws Exception { + return Integer.valueOf(numberInfo.getNumber()); + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java new file mode 100644 index 0000000000..0ba7fde279 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java @@ -0,0 +1,15 @@ +package org.baeldung.conditionalflow.step; + +import org.baeldung.conditionalflow.model.NumberInfo; +import org.springframework.batch.core.StepExecution; +import org.springframework.batch.item.ItemProcessor; + +public class NumberInfoClassifierWithDecider + implements ItemProcessor { + private StepExecution stepExecution; + + @Override + public Integer process(NumberInfo numberInfo) throws Exception { + return Integer.valueOf(numberInfo.getNumber()); + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoGenerator.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoGenerator.java new file mode 100644 index 0000000000..35f6c39778 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoGenerator.java @@ -0,0 +1,23 @@ +package org.baeldung.conditionalflow.step; + +import org.baeldung.conditionalflow.model.NumberInfo; +import org.springframework.batch.item.ItemReader; + +public class NumberInfoGenerator implements ItemReader { + private int[] values; + private int counter; + + public NumberInfoGenerator(int[] values){ + this.values = values; + counter = 0; + } + + @Override + public NumberInfo read() { + if(counter == values.length){ + return null; + } else { + return new NumberInfo(values[counter++]); + } + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoProcessor.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoProcessor.java new file mode 100644 index 0000000000..fe566221de --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoProcessor.java @@ -0,0 +1,17 @@ +package org.baeldung.conditionalflow.step; + +import org.baeldung.conditionalflow.model.NumberInfo; +import org.springframework.batch.core.ExitStatus; +import org.springframework.batch.core.StepExecution; +import org.springframework.batch.core.annotation.BeforeStep; +import org.springframework.batch.core.listener.ItemListenerSupport; +import org.springframework.batch.item.ItemProcessor; + +public class NumberInfoProcessor implements ItemProcessor { + private StepExecution stepExecution; + + @Override + public Integer process(NumberInfo numberInfo) throws Exception { + return Integer.valueOf(numberInfo.getNumber()); + } +} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java new file mode 100644 index 0000000000..8b8959d249 --- /dev/null +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java @@ -0,0 +1,30 @@ +package org.baeldung.conditionalflow.step; + +import org.springframework.batch.item.ItemWriter; + +import java.io.OutputStream; +import java.util.List; + +public class PrependingStdoutWriter implements ItemWriter { + private String prependText; + private OutputStream writeTo; + + private PrependingStdoutWriter() { + } + + public PrependingStdoutWriter(String prependText, OutputStream os){ + this.prependText = prependText; + this.writeTo = os; + } + + public PrependingStdoutWriter(String prependText) { + this(prependText, System.out); + } + + @Override + public void write(List list) throws Exception { + for (T listItem : list) { + System.out.println(prependText + " " + listItem.toString()); + } + } +} diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java new file mode 100644 index 0000000000..cf3d361412 --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java @@ -0,0 +1,44 @@ +package org.baeldung.conditionalflow.model; + +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.junit.jupiter.api.Assertions.*; + +@RunWith(SpringJUnit4ClassRunner.class) +class NumberInfoUnitTest { + + @Test + void isPositive() { + assertTrue(NumberInfo.from(1).isPositive()); + assertTrue(NumberInfo.from(11).isPositive()); + assertFalse(NumberInfo.from(0).isPositive()); + assertFalse(NumberInfo.from(-1).isPositive()); + assertFalse(NumberInfo.from(-10).isPositive()); + } + + @Test + void isEven() { + assertTrue(NumberInfo.from(0).isEven()); + assertTrue(NumberInfo.from(-2).isEven()); + assertTrue(NumberInfo.from(2).isEven()); + assertTrue(NumberInfo.from(-22).isEven()); + assertTrue(NumberInfo.from(22).isEven()); + + assertFalse(NumberInfo.from(1).isEven()); + assertFalse(NumberInfo.from(-1).isEven()); + + assertFalse(NumberInfo.from(13).isEven()); + assertFalse(NumberInfo.from(-13).isEven()); + assertFalse(NumberInfo.from(31).isEven()); + assertFalse(NumberInfo.from(-51).isEven()); + } + + @Test + void getNumber() { + for(int i = -100 ; i < 100 ; i++){ + assertEquals(i, NumberInfo.from(i).getNumber()); + } + } +} \ No newline at end of file diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java new file mode 100644 index 0000000000..c195740caa --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java @@ -0,0 +1,17 @@ +package org.baeldung.conditionalflow.step; + +import org.baeldung.conditionalflow.model.NumberInfo; +import org.baeldung.conditionalflow.step.NumberInfoClassifier; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class NumberInfoClassifierUnitTest { + + @Test + void process() throws Exception { + NumberInfoClassifier nic = new NumberInfoClassifier(); + assertEquals(Integer.valueOf(4), nic.process(NumberInfo.from(4))); + assertEquals(Integer.valueOf(-4), nic.process(NumberInfo.from(-4))); + } +} \ No newline at end of file diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java new file mode 100644 index 0000000000..3fc240bcbf --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java @@ -0,0 +1,20 @@ +package org.baeldung.conditionalflow.step; + +import org.baeldung.conditionalflow.model.NumberInfo; +import org.junit.jupiter.api.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +public class NumberInfoGeneratorUnitTest { + @Test + public void testGenerateNumbers() { + int[] numbers = new int[]{1, -2, 4, -10}; + NumberInfoGenerator numberGenerator = new NumberInfoGenerator(numbers); + assertEquals(new NumberInfo(numbers[0]), numberGenerator.read()); + assertEquals(new NumberInfo(numbers[1]), numberGenerator.read()); + assertEquals(new NumberInfo(numbers[2]), numberGenerator.read()); + assertEquals(new NumberInfo(numbers[3]), numberGenerator.read()); + assertNull(numberGenerator.read()); + } +} \ No newline at end of file From d3b351e27f4e21857ffa92d8acb5f5a5efba86eb Mon Sep 17 00:00:00 2001 From: ramkumarvenkat Date: Mon, 16 Mar 2020 08:30:23 +0530 Subject: [PATCH 12/59] fix formatting --- .../guava/mapmaker/GuavaMapMakerUnitTest.java | 45 ++++++++++--------- 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java b/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java index d9a5fc6cd8..8da459f22e 100644 --- a/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java +++ b/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java @@ -8,28 +8,33 @@ import java.util.concurrent.ConcurrentMap; import static org.junit.Assert.assertNotNull; public class GuavaMapMakerUnitTest { - @Test public void whenMakeMap_thenCreated() { - ConcurrentMap concurrentMap = new MapMaker().makeMap(); - assertNotNull(concurrentMap); - } + @Test + public void whenMakeMap_thenCreated() { + ConcurrentMap concurrentMap = new MapMaker().makeMap(); + assertNotNull(concurrentMap); + } - @Test public void whenMakeMapWithWeakKeys_thenCreated() { - ConcurrentMap concurrentMap = new MapMaker().weakKeys().makeMap(); - assertNotNull(concurrentMap); - } + @Test + public void whenMakeMapWithWeakKeys_thenCreated() { + ConcurrentMap concurrentMap = new MapMaker().weakKeys().makeMap(); + assertNotNull(concurrentMap); + } - @Test public void whenMakeMapWithWeakValues_thenCreated() { - ConcurrentMap concurrentMap = new MapMaker().weakValues().makeMap(); - assertNotNull(concurrentMap); - } + @Test + public void whenMakeMapWithWeakValues_thenCreated() { + ConcurrentMap concurrentMap = new MapMaker().weakValues().makeMap(); + assertNotNull(concurrentMap); + } - @Test public void whenMakeMapWithInitialCapacity_thenCreated() { - ConcurrentMap concurrentMap = new MapMaker().initialCapacity(10).makeMap(); - assertNotNull(concurrentMap); - } + @Test + public void whenMakeMapWithInitialCapacity_thenCreated() { + ConcurrentMap concurrentMap = new MapMaker().initialCapacity(10).makeMap(); + assertNotNull(concurrentMap); + } - @Test public void whenMakeMapWithConcurrencyLevel_thenCreated() { - ConcurrentMap concurrentMap = new MapMaker().concurrencyLevel(10).makeMap(); - assertNotNull(concurrentMap); - } + @Test + public void whenMakeMapWithConcurrencyLevel_thenCreated() { + ConcurrentMap concurrentMap = new MapMaker().concurrencyLevel(10).makeMap(); + assertNotNull(concurrentMap); + } } From e58683f48b092fc1cf9f28a0dd86050edc0dca32 Mon Sep 17 00:00:00 2001 From: mike b Date: Tue, 17 Mar 2020 10:06:34 -0400 Subject: [PATCH 13/59] [BAEL-3646] Addressing PR comments --- spring-batch/repository.sqlite | Bin 49152 -> 73728 bytes .../ConditionalFlowApplication.java | 5 +- .../conditionalflow/NumberInfoDecider.java | 18 +++- .../config/NumberInfoConfig.java | 86 ++++++++++-------- .../conditionalflow/model/NumberInfo.java | 18 ++-- .../conditionalflow/step/NotifierTasklet.java | 3 +- .../step/NumberInfoClassifier.java | 9 +- .../step/NumberInfoClassifierWithDecider.java | 8 +- .../step/NumberInfoGenerator.java | 4 +- .../step/NumberInfoProcessor.java | 17 ---- .../step/PrependingStdoutWriter.java | 9 +- .../DeciderJobIntegrationTest.java | 56 ++++++++++++ .../model/NumberInfoUnitTest.java | 77 +++++++++++----- .../step/NumberInfoClassifierUnitTest.java | 9 +- .../step/NumberInfoGeneratorUnitTest.java | 8 +- spring-batch/xml/retryOutput.xml | 2 +- 16 files changed, 208 insertions(+), 121 deletions(-) delete mode 100644 spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoProcessor.java create mode 100644 spring-batch/src/test/java/org/baeldung/conditionalflow/DeciderJobIntegrationTest.java diff --git a/spring-batch/repository.sqlite b/spring-batch/repository.sqlite index 4456ef63cc28948e07a545a72ec1b63366e9057b..9d260fa2d1eed9ab00ea099508119d8e44235d87 100644 GIT binary patch literal 73728 zcmeHQTWlLwdY<7$7h4MBWH+ko79J?hio!~>oZ(e8vRj%O*^DVtA*tBfG*CywLx~Z^ z;SPtE)5Si->$X7q)FuV`)YpA)Q51dZLkqNvw&|h|?Mol_ae=l#7gz+@Z6ErdGsEEw zIlL&byRrS#=4f~>|2gM7*Z*?PslHuonnY;m#+hmgaqeY~=egey1dih`a~$^yeES~_ zUPApJ@RxVJk9h?eB7d+P`HZ_9Y;Z3XU;5L?pD(>}>0tg3=F*}62)!5l7jVW8BJi9e z@c#1r%Gw(L;j5;4)FQWXwfvpKx5~E;tIFG+AItfQlB+2~EqAM^2p%sXDipSbLaCmgZM(-sC@A8%j*MujKb@g>uQ8tjBq2 zOa?rGX3xsy%kwL5zR7>M?#fEFrtBSh=vn0)b-(PBnbA-)=jKu2()>z3&p*EE$_=fB zL1yx0!1sP_0Q`v8C7(R`(tvDv-Cea;D%XV4ezEAT#tor*r(CHW+F20Z$yM@qa+Ro@ zjK$W4ehdhuR0_Fb;oHi#6Et5e-x4+iO>cKiLv6NAC*{L@?f&7;T{^sz=5bp%B_9aU z;cTr725At3v^COowK=EgJ`vU*y}dZUqA2|1H(Xc_)r|*Cf4@Z^H2p&YoI@V}pLjY+ z`vU6tTD_~V?SrT{Ow{}HkVaYmox2P3E6F7P`&(l%_3J6~Q!%_ScHSXnLwHB2RAJn3 zMjuyeq@B5x+f|(QDtVjhaAWhOk%M+$D*zGtsMd13drpIgcCD1Qhkdt|o!oxW?nKZh zYPs5e)s=;Hh?Xz!?iOf&+J{lGKW=UaFu>BD<8|CA6l+Rl#Q9#OP*X-+8HMWI!rq9F z72eltuTst{)#{OVlRhWIo_i0>EX=T~w${&#=f)tbGnVJ}z7?N zcoxlig~>q47g#^rfTYC0dn%*-;~R7HEAcr0d-}M#^r^(~ zwA!1g+Qu$)Mn|O$HtiKkFdCHd3XG{vuOEz8R-T53lYu|P9UY5?D)V!WM^Cmd(|!OG z>`vkKekI2ib;WX?y|`OvY<;BHQ+(Kp$G4@p(DRwZXrlcPY*o|Zo$cN`v z?nyk?Y}d&{8#=XT>g@O7Xo(M{QMVv4Tnm)xT83{Z66GTQ82RJKZ^8?H5CKF05kLeG z0Ym^1Km-s0L;w*$1Q3B27y&sH<`&j=4PqJ}+)_>LmQ*<-YeY?FWS-@*(KNbdKaM8X)dtW{ zOIkXuWfJu*DMnIiI+aPJNJ6e(f;tUFHo3?rk+7~*XGsGwP5h3p9hQeS|BL7Jp0=pz^Z}c z0+CN?p%x_C?m;YgX8(_r-TCqz4i{1i-bMhRPXb7J>I@3rdGAv!78`|1NVE5+mM7fabG zOunUdyUj+E82)Kb4#-kZ$7W9)_D7zHJ8G|G*7O!J)V7&F>9tSy3>{8l=<0^M*pq^> zgp;ug6nkpQsz$SL1J0g^PET2Waz(x&iw4p32gI13uAJT)pD@$Xh}~YNqZ_7Jp=O&k za@J|7CJ|56cD+TIoAU5P?Lj-QN4-HTNTmrSo0LFZR~{0rXA(cE@uc+mvQ5U*l%)wY zhkG=ud}bf&Epwl~j~9bOmeS)h?wiP@rUNIHw7c}!sTnGID|5kwt4*kCGSr(oR=EagP(mzH!qKB1Aa=3o`Z>9wwcIDNN|t)Cw&pp>{k9r|G_GY}cV zc^#_tp*f18oSt#8)$|U5$&`^1Y1P>zE2KkI(^G9QN|5g5k+FgnJL zmHo`&1 z=L_3XGLuLoc!ZI03v`0Ohe#X-weLWEw009E!SWwU>}g$b{%y$740%zKfhpW`R%j#OH7!{ zFMK>7_zK6r0gC>s3p|a_^Hkp-pd{#iF-pLa0skwL{{E+>?w<>UQ19=uYM89fci9|F z4#))fsP~^}MKaCc0QLT0px{#2xy=>&Do?Mr-clQ(-oJ0B#9ElIY9ICfU=@XWf45Pa zkH!~9AZk2;djH8rd#LxH&7{$z;_r{(9>*u4_y4bN@vn0H3Ml@sFY?w>5LS}GF0B6~ zw(?Wi^KTsOe=ykB|Gz@@|1UB9KR-9e!T*=Rq5r*NzenIN{nC2?>3x9oy98fqHsF4T zpZGxp5CKF05qS0x_~<<3-8c}U^9KJl_FSXSEB2Ow@d5e3GxR2gaDLJRPkWsXeB@1`O<)eIyTf=0bg(6- z1v!C|3Q<~cD61V}c00!>%7kao_?}oM)o6V0Y!*T$++~+OYBr8cI5OdAeDB>~=p%}G zc8u>~*PgwbjH+DhokjGOTIN$v#^g(h*^T@AA_BNxz)jih%xEU0*|xb1HVjaTgIx{P zrnRbL_Wze(=U)2zANR-|cFh+1c9sZL6<4ZDa`fp~%P z`S5V7-+PpR>(3Cj2}kRUfekKyL)b11TN2DEAD?}RI%)j#bkfWWy)^M8d#Sbm|HoY9 zv&etL4FErWv4?srJtBYzAOeU0B7g`W0*C-2fCwN0hyWt+Y$7lh3UODs?|yGCX#Wk^ ze|hWga^!zGKJppm|37;+ONhBf1P}p401-e05CKF05kLeG0Ym^1Km-thaR>xL0qPY( z{(l@o=#B^=0*C-2fCwN0hyWsh2p|H803v`0Jo^YB|NrdQA(j9UKm-s0L;w*$1P}p4 z01-e05CKF05txR6!~a9TK=?1X$X~+)KZpP#fCwN0Uv32O{y#Xss_NXAXrHnhkI#M- zKE0Aabgn7Lx72R8*=Q2OMHKJ<>$S|94yPEaZIc~dwrA)X>2`JdSmUHTJKpRBv>kOU zMZEtH@BeF`4mB`&YqoQ<>1lN$Yhif*pQ_OV0P*SpW8!tBJ}2+t{eNmUo=#31(((Sk z=i&Z8rKW7t^Z&WOrRV=x0`(JG)KkzK!kWCs zZtbIiE=|5lcqk1i)`x>&2F#L(T!oM{ad7cXyO%w&Ul4# z0K9^5=7|U80MQER5Y=>sE^CNFIl$niyqelQZ4r~+>Sy2gn!JEmvVUJ&p`< zIW`;3!F7I=AiZVKTGgfbC5~T&h2Qn-%dqZaj<2!jZT9?OzP!6vq-?+QV!2cPpAY|n zga7zJ1P}p401YO668Ihp#muNtWeSgL+_b{7UTpo^bnQvylVS-IZx1k$n)1^D8 zgonky=wbqHFk2WGlbu&vts_-C1+h<|?Q%yY{A3{{GT+F2cSN67;F6!Z`rVh2`3B=S z(VEccf+=d5AJJFJnNv?oBaxV$x$lbx-qMfUl-hc|Jw_(?8QPN0*C-2@O&e%8Cv2NfwkwZT?2Wr#mRq-@$+ldTCM_e;Qi9w zQu$uVa{K5!=rtS&Qg`lC_WU^uBTO?Kuy``Yb3Hx&-{In|DXvS52ThHLyG^j)Zy)c& z@3wkIob+c_1R-mjMb;Qu<8*qaMJ32=d>8J>8b@9HzgM0mC1zW&kHuDI@&zV*0MVvN z9-5;92018xn$?rmOQxv%8+YlRZC1>?n!7lWYr zUms}xc}w$8_4IpstEqiJNiY!rzrd!6U$vP3xj^Wbtp7*;|ACrC)p*~~o-NR1X~Ig! zwVvuiqqeq*PukLes&RF;9j-o#JLLb7|DV)&kpGtwQ+L=8w#E7MFy#L=lQPmSrMsKw NenP787l;49_J3-kW;6f* delta 620 zcmZoTz|zpbJV8o`L7#zvfd`0TKzgE%5fg*{#socPMvlpbtm2!OF~{++G4h{b;6Jlj zaKa&eJ0nI`1`c)Kw9KO75~swH>{kvtjxAx*5n2j7FID9W@FCD51EBorI?wmK`e1&Q6^?XPAA6@XODO< zf2Vj)zu*u@KWA3~MrL&+;b7N5kadjw#~JvK10B4V-`<>&hk=okm6cUqo|lz@i7|Em z?HxZs`kV?h-%55oY>Pn zIjY~3$;@){#QtnPCPpR(uwi^B82C;AmF~l#v=|ucKN$FbK-?a{F2u&j!XU^{U5juE SREis6DA0NQe_+BaAiDrUiJ;X0 diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/ConditionalFlowApplication.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/ConditionalFlowApplication.java index 8b6c841b6e..c977d6ecab 100644 --- a/spring-batch/src/main/java/org/baeldung/conditionalflow/ConditionalFlowApplication.java +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/ConditionalFlowApplication.java @@ -1,11 +1,14 @@ package org.baeldung.conditionalflow; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ConditionalFlowApplication implements CommandLineRunner { + private static Logger logger = LoggerFactory.getLogger(ConditionalFlowApplication.class); public static void main(String[] args) { SpringApplication.run(ConditionalFlowApplication.class, args); @@ -13,6 +16,6 @@ public class ConditionalFlowApplication implements CommandLineRunner { @Override public void run(String... args) throws Exception { - System.out.println("Running and exiting"); + logger.info("Running conditional flow application..."); } } diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/NumberInfoDecider.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/NumberInfoDecider.java index 017980f1a4..701011b4d3 100644 --- a/spring-batch/src/main/java/org/baeldung/conditionalflow/NumberInfoDecider.java +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/NumberInfoDecider.java @@ -1,6 +1,5 @@ package org.baeldung.conditionalflow; -import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.job.flow.FlowExecutionStatus; @@ -8,12 +7,23 @@ import org.springframework.batch.core.job.flow.JobExecutionDecider; public class NumberInfoDecider implements JobExecutionDecider { + public static final String NOTIFY = "NOTIFY"; + public static final String QUIET = "QUIET"; + + /** + * Method that determines notification status of job + * @return true if notifications should be sent. + */ + private boolean shouldNotify() { + return true; + } + @Override public FlowExecutionStatus decide(JobExecution jobExecution, StepExecution stepExecution) { - if(jobExecution.getExitStatus().equals("UNKNOWN")) { - return new FlowExecutionStatus("NOTIFY"); + if (shouldNotify()) { + return new FlowExecutionStatus(NOTIFY); } else { - return null; + return new FlowExecutionStatus(QUIET); } } } diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/config/NumberInfoConfig.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/config/NumberInfoConfig.java index fd28c2291f..906a6e1d28 100644 --- a/spring-batch/src/main/java/org/baeldung/conditionalflow/config/NumberInfoConfig.java +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/config/NumberInfoConfig.java @@ -11,6 +11,9 @@ import org.springframework.batch.core.configuration.annotation.StepBuilderFactor import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; + +import static org.baeldung.conditionalflow.NumberInfoDecider.NOTIFY; @Configuration @EnableBatchProcessing @@ -19,67 +22,70 @@ public class NumberInfoConfig { @Bean @Qualifier("NotificationStep") public Step notificationStep(StepBuilderFactory sbf) { - return sbf.get("Billing step").tasklet(new NotifierTasklet()).build(); + return sbf.get("Notify step") + .tasklet(new NotifierTasklet()) + .build(); } public Step numberGeneratorStep(StepBuilderFactory sbf, int[] values, String prepend) { return sbf.get("Number generator") - .chunk(1) - .reader(new NumberInfoGenerator(values)) - .processor(new NumberInfoClassifier()) - .writer(new PrependingStdoutWriter<>(prepend)) - .build(); + . chunk(1) + .reader(new NumberInfoGenerator(values)) + .processor(new NumberInfoClassifier()) + .writer(new PrependingStdoutWriter<>(prepend)) + .build(); } public Step numberGeneratorStepDecider(StepBuilderFactory sbf, int[] values, String prepend) { - return sbf.get("Number generator") - .chunk(1) - .reader(new NumberInfoGenerator(values)) - .processor(new NumberInfoClassifierWithDecider()) - .writer(new PrependingStdoutWriter<>(prepend)) - .build(); + return sbf.get("Number generator decider") + . chunk(1) + .reader(new NumberInfoGenerator(values)) + .processor(new NumberInfoClassifierWithDecider()) + .writer(new PrependingStdoutWriter<>(prepend)) + .build(); } @Bean - public Job numberGeneratorNonNotifierJob(JobBuilderFactory jobBuilderFactory, - StepBuilderFactory stepBuilderFactory, - @Qualifier("NotificationStep") Step notificationStep - ) { - int[] nonNotifierData = {-1, -2, -3}; + @Qualifier("first_job") + public Job numberGeneratorNonNotifierJob(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, @Qualifier("NotificationStep") Step notificationStep) { + int[] nonNotifierData = { -1, -2, -3 }; Step step = numberGeneratorStep(stepBuilderFactory, nonNotifierData, "First Dataset Processor"); return jobBuilderFactory.get("Number generator - first dataset") - .start(step) - .on("NOTIFY").to(notificationStep) - .from(step).on("*").stop() - .end() - .build(); + .start(step) + .on(NOTIFY) + .to(notificationStep) + .from(step) + .on("*") + .stop() + .end() + .build(); } @Bean - public Job numberGeneratorNotifierJob(JobBuilderFactory jobBuilderFactory, - StepBuilderFactory stepBuilderFactory, - @Qualifier("NotificationStep") Step notificationStep - ) { - int[] billableData = {11, -2, -3}; + @Qualifier("second_job") + public Job numberGeneratorNotifierJob(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, @Qualifier("NotificationStep") Step notificationStep) { + int[] billableData = { 11, -2, -3 }; Step dataProviderStep = numberGeneratorStep(stepBuilderFactory, billableData, "Second Dataset Processor"); return jobBuilderFactory.get("Number generator - second dataset") - .start(dataProviderStep) - .on("NOTIFY").to(notificationStep) - .end() - .build(); + .start(dataProviderStep) + .on(NOTIFY) + .to(notificationStep) + .end() + .build(); } @Bean - public Job numberGeneratorNotifierJobWithDecider(JobBuilderFactory jobBuilderFactory, - StepBuilderFactory stepBuilderFactory, - @Qualifier("NotificationStep") Step notificationStep - ) { - int[] billableData = {11, -2, -3}; + @Qualifier("third_job") + @Primary + public Job numberGeneratorNotifierJobWithDecider(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory, @Qualifier("NotificationStep") Step notificationStep) { + int[] billableData = { 11, -2, -3 }; Step dataProviderStep = numberGeneratorStepDecider(stepBuilderFactory, billableData, "Third Dataset Processor"); return jobBuilderFactory.get("Number generator - third dataset") - .start(dataProviderStep) - .next(new NumberInfoDecider()).on("NOTIFY").to(notificationStep) - .end() - .build(); + .start(dataProviderStep) + .next(new NumberInfoDecider()) + .on(NOTIFY) + .to(notificationStep) + .end() + .build(); } } diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/model/NumberInfo.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/model/NumberInfo.java index 81bd67d2a1..4134974386 100644 --- a/spring-batch/src/main/java/org/baeldung/conditionalflow/model/NumberInfo.java +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/model/NumberInfo.java @@ -5,14 +5,14 @@ import java.util.Objects; public class NumberInfo { private int number; - public static NumberInfo from(int number){ - return new NumberInfo(number); - } - public NumberInfo(int number) { this.number = number; } + public static NumberInfo from(int number) { + return new NumberInfo(number); + } + public boolean isPositive() { return number > 0; } @@ -27,8 +27,10 @@ public class NumberInfo { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; NumberInfo that = (NumberInfo) o; return number == that.number; } @@ -40,8 +42,6 @@ public class NumberInfo { @Override public String toString() { - return "NumberInfo{" + - "number=" + number + - '}'; + return "NumberInfo{" + "number=" + number + '}'; } } \ No newline at end of file diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NotifierTasklet.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NotifierTasklet.java index 6a88edcbbe..0d1db66fe9 100644 --- a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NotifierTasklet.java +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NotifierTasklet.java @@ -8,7 +8,8 @@ import org.springframework.batch.repeat.RepeatStatus; public class NotifierTasklet implements Tasklet { @Override public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception { - System.err.println("[" + chunkContext.getStepContext().getJobName() + "] contains interesting data!!"); + System.err.println("[" + chunkContext.getStepContext() + .getJobName() + "] contains interesting data!!"); return RepeatStatus.FINISHED; } } diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java index 95b1e4d155..e9bc852d56 100644 --- a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java @@ -7,20 +7,23 @@ import org.springframework.batch.core.annotation.BeforeStep; import org.springframework.batch.core.listener.ItemListenerSupport; import org.springframework.batch.item.ItemProcessor; -public class NumberInfoClassifier extends ItemListenerSupport - implements ItemProcessor { +import static org.baeldung.conditionalflow.NumberInfoDecider.NOTIFY; +import static org.baeldung.conditionalflow.NumberInfoDecider.QUIET; + +public class NumberInfoClassifier extends ItemListenerSupport implements ItemProcessor { private StepExecution stepExecution; @BeforeStep public void beforeStep(StepExecution stepExecution) { this.stepExecution = stepExecution; + this.stepExecution.setExitStatus(new ExitStatus(QUIET)); } @Override public void afterProcess(NumberInfo item, Integer result) { super.afterProcess(item, result); if (item.isPositive()) { - stepExecution.setExitStatus(new ExitStatus("NOTIFY")); + stepExecution.setExitStatus(new ExitStatus(NOTIFY)); } } diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java index 0ba7fde279..ab6e33aec1 100644 --- a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java @@ -1,15 +1,17 @@ package org.baeldung.conditionalflow.step; import org.baeldung.conditionalflow.model.NumberInfo; +import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepExecution; +import org.springframework.batch.core.annotation.BeforeStep; +import org.springframework.batch.core.listener.ItemListenerSupport; import org.springframework.batch.item.ItemProcessor; -public class NumberInfoClassifierWithDecider - implements ItemProcessor { - private StepExecution stepExecution; +public class NumberInfoClassifierWithDecider extends ItemListenerSupport implements ItemProcessor { @Override public Integer process(NumberInfo numberInfo) throws Exception { return Integer.valueOf(numberInfo.getNumber()); } + } diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoGenerator.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoGenerator.java index 35f6c39778..606ebf6204 100644 --- a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoGenerator.java +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoGenerator.java @@ -7,14 +7,14 @@ public class NumberInfoGenerator implements ItemReader { private int[] values; private int counter; - public NumberInfoGenerator(int[] values){ + public NumberInfoGenerator(int[] values) { this.values = values; counter = 0; } @Override public NumberInfo read() { - if(counter == values.length){ + if (counter == values.length) { return null; } else { return new NumberInfo(values[counter++]); diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoProcessor.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoProcessor.java deleted file mode 100644 index fe566221de..0000000000 --- a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoProcessor.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.conditionalflow.step; - -import org.baeldung.conditionalflow.model.NumberInfo; -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.StepExecution; -import org.springframework.batch.core.annotation.BeforeStep; -import org.springframework.batch.core.listener.ItemListenerSupport; -import org.springframework.batch.item.ItemProcessor; - -public class NumberInfoProcessor implements ItemProcessor { - private StepExecution stepExecution; - - @Override - public Integer process(NumberInfo numberInfo) throws Exception { - return Integer.valueOf(numberInfo.getNumber()); - } -} diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java index 8b8959d249..283b43f267 100644 --- a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java @@ -1,18 +1,15 @@ package org.baeldung.conditionalflow.step; -import org.springframework.batch.item.ItemWriter; - import java.io.OutputStream; import java.util.List; +import org.springframework.batch.item.ItemWriter; + public class PrependingStdoutWriter implements ItemWriter { private String prependText; private OutputStream writeTo; - private PrependingStdoutWriter() { - } - - public PrependingStdoutWriter(String prependText, OutputStream os){ + public PrependingStdoutWriter(String prependText, OutputStream os) { this.prependText = prependText; this.writeTo = os; } diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/DeciderJobIntegrationTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/DeciderJobIntegrationTest.java new file mode 100644 index 0000000000..8669264848 --- /dev/null +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/DeciderJobIntegrationTest.java @@ -0,0 +1,56 @@ +package org.baeldung.conditionalflow; + +import org.baeldung.conditionalflow.config.NumberInfoConfig; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.batch.core.ExitStatus; +import org.springframework.batch.core.JobExecution; +import org.springframework.batch.core.StepExecution; +import org.springframework.batch.test.AssertFile; +import org.springframework.batch.test.JobLauncherTestUtils; +import org.springframework.batch.test.JobRepositoryTestUtils; +import org.springframework.batch.test.context.SpringBatchTest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; +import org.springframework.test.context.support.DirtiesContextTestExecutionListener; + +import java.util.Collection; +import java.util.Iterator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringRunner.class) +@SpringBatchTest +@EnableAutoConfiguration +@ContextConfiguration(classes = { NumberInfoConfig.class }) +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class }) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +public class DeciderJobIntegrationTest { + @Autowired + private JobLauncherTestUtils jobLauncherTestUtils; + + @Test + public void whenNumberGeneratorDecider_thenNotifyStepRuns() throws Exception { + JobExecution jobExecution = jobLauncherTestUtils.launchJob(); + Collection actualStepExecutions = jobExecution.getStepExecutions(); + ExitStatus actualJobExitStatus = jobExecution.getExitStatus(); + + assertEquals(actualJobExitStatus.getExitCode().toString(), "COMPLETED"); + assertEquals(actualStepExecutions.size(), 2); + boolean notifyStepDidRun = false; + Iterator iterator = actualStepExecutions.iterator(); + while(iterator.hasNext() && !notifyStepDidRun){ + if(iterator.next().getStepName().equals("Notify step")){ + notifyStepDidRun = true; + } + } + assertTrue(notifyStepDidRun); + } +} diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java index cf3d361412..26cd286409 100644 --- a/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java @@ -1,44 +1,71 @@ package org.baeldung.conditionalflow.model; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.jupiter.api.Assertions.*; - @RunWith(SpringJUnit4ClassRunner.class) class NumberInfoUnitTest { @Test - void isPositive() { - assertTrue(NumberInfo.from(1).isPositive()); - assertTrue(NumberInfo.from(11).isPositive()); - assertFalse(NumberInfo.from(0).isPositive()); - assertFalse(NumberInfo.from(-1).isPositive()); - assertFalse(NumberInfo.from(-10).isPositive()); + void whenPositive_isPositive() { + assertTrue(NumberInfo.from(1) + .isPositive()); + assertTrue(NumberInfo.from(11) + .isPositive()); + assertFalse(NumberInfo.from(0) + .isPositive()); } @Test - void isEven() { - assertTrue(NumberInfo.from(0).isEven()); - assertTrue(NumberInfo.from(-2).isEven()); - assertTrue(NumberInfo.from(2).isEven()); - assertTrue(NumberInfo.from(-22).isEven()); - assertTrue(NumberInfo.from(22).isEven()); - - assertFalse(NumberInfo.from(1).isEven()); - assertFalse(NumberInfo.from(-1).isEven()); - - assertFalse(NumberInfo.from(13).isEven()); - assertFalse(NumberInfo.from(-13).isEven()); - assertFalse(NumberInfo.from(31).isEven()); - assertFalse(NumberInfo.from(-51).isEven()); + void whenNegative_isPositive_isFalse() { + assertFalse(NumberInfo.from(-1) + .isPositive()); + assertFalse(NumberInfo.from(-10) + .isPositive()); } @Test - void getNumber() { - for(int i = -100 ; i < 100 ; i++){ - assertEquals(i, NumberInfo.from(i).getNumber()); + void whenEven_isEven() { + assertTrue(NumberInfo.from(0) + .isEven()); + assertTrue(NumberInfo.from(-2) + .isEven()); + assertTrue(NumberInfo.from(2) + .isEven()); + assertTrue(NumberInfo.from(-22) + .isEven()); + assertTrue(NumberInfo.from(22) + .isEven()); + } + + @Test + void whenOdd_isEven_isFalse() { + + assertFalse(NumberInfo.from(1) + .isEven()); + assertFalse(NumberInfo.from(-1) + .isEven()); + + assertFalse(NumberInfo.from(13) + .isEven()); + assertFalse(NumberInfo.from(-13) + .isEven()); + assertFalse(NumberInfo.from(31) + .isEven()); + assertFalse(NumberInfo.from(-51) + .isEven()); + } + + @Test + void testStatic_fromMethod_equals_getNumber() { + for (int i = -100; i < 100; i++) { + assertEquals(i, NumberInfo.from(i) + .getNumber()); } } } \ No newline at end of file diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java index c195740caa..9b490799db 100644 --- a/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java @@ -1,15 +1,14 @@ package org.baeldung.conditionalflow.step; -import org.baeldung.conditionalflow.model.NumberInfo; -import org.baeldung.conditionalflow.step.NumberInfoClassifier; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.*; +import org.baeldung.conditionalflow.model.NumberInfo; +import org.junit.jupiter.api.Test; class NumberInfoClassifierUnitTest { @Test - void process() throws Exception { + void process_convertsToInteger() throws Exception { NumberInfoClassifier nic = new NumberInfoClassifier(); assertEquals(Integer.valueOf(4), nic.process(NumberInfo.from(4))); assertEquals(Integer.valueOf(-4), nic.process(NumberInfo.from(-4))); diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java index 3fc240bcbf..7794003959 100644 --- a/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java @@ -1,14 +1,14 @@ package org.baeldung.conditionalflow.step; -import org.baeldung.conditionalflow.model.NumberInfo; -import org.junit.jupiter.api.Test; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import org.baeldung.conditionalflow.model.NumberInfo; +import org.junit.jupiter.api.Test; + public class NumberInfoGeneratorUnitTest { @Test - public void testGenerateNumbers() { + public void testGenerateNumbers_correctOrderAndValue() { int[] numbers = new int[]{1, -2, 4, -10}; NumberInfoGenerator numberGenerator = new NumberInfoGenerator(numbers); assertEquals(new NumberInfo(numbers[0]), numberGenerator.read()); diff --git a/spring-batch/xml/retryOutput.xml b/spring-batch/xml/retryOutput.xml index d30f2c4a32..c5dec44f16 100644 --- a/spring-batch/xml/retryOutput.xml +++ b/spring-batch/xml/retryOutput.xml @@ -1 +1 @@ -1010000.04302222015-10-31 00:00:001234sammy1012321.04302222015-12-03 00:00:009999john \ No newline at end of file + \ No newline at end of file From f953196ddfeecbe61b285a4f6d702cb86119fcab Mon Sep 17 00:00:00 2001 From: mike b Date: Thu, 19 Mar 2020 20:15:52 -0400 Subject: [PATCH 14/59] [BAEL-3646] Fixing tests per review comments --- .../step/NumberInfoClassifier.java | 3 ++- .../step/NumberInfoClassifierWithDecider.java | 1 - .../DeciderJobIntegrationTest.java | 16 ++++++++-------- .../model/NumberInfoUnitTest.java | 10 +++++----- .../step/NumberInfoClassifierUnitTest.java | 2 +- .../step/NumberInfoGeneratorUnitTest.java | 2 +- 6 files changed, 17 insertions(+), 17 deletions(-) diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java index e9bc852d56..fdb28263e7 100644 --- a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifier.java @@ -10,7 +10,8 @@ import org.springframework.batch.item.ItemProcessor; import static org.baeldung.conditionalflow.NumberInfoDecider.NOTIFY; import static org.baeldung.conditionalflow.NumberInfoDecider.QUIET; -public class NumberInfoClassifier extends ItemListenerSupport implements ItemProcessor { +public class NumberInfoClassifier extends ItemListenerSupport + implements ItemProcessor { private StepExecution stepExecution; @BeforeStep diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java index ab6e33aec1..b9d251c02d 100644 --- a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java @@ -13,5 +13,4 @@ public class NumberInfoClassifierWithDecider extends ItemListenerSupport actualStepExecutions = jobExecution.getStepExecutions(); ExitStatus actualJobExitStatus = jobExecution.getExitStatus(); - assertEquals(actualJobExitStatus.getExitCode().toString(), "COMPLETED"); - assertEquals(actualStepExecutions.size(), 2); + assertEquals("COMPLETED", actualJobExitStatus.getExitCode() + .toString()); + assertEquals(2, actualStepExecutions.size()); boolean notifyStepDidRun = false; Iterator iterator = actualStepExecutions.iterator(); - while(iterator.hasNext() && !notifyStepDidRun){ - if(iterator.next().getStepName().equals("Notify step")){ + while (iterator.hasNext() && !notifyStepDidRun) { + if (iterator.next() + .getStepName() + .equals("Notify step")) { notifyStepDidRun = true; } } diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java index 26cd286409..dc396b38da 100644 --- a/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/model/NumberInfoUnitTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; class NumberInfoUnitTest { @Test - void whenPositive_isPositive() { + void givenPositive_whenFrom_isPositive() { assertTrue(NumberInfo.from(1) .isPositive()); assertTrue(NumberInfo.from(11) @@ -22,7 +22,7 @@ class NumberInfoUnitTest { } @Test - void whenNegative_isPositive_isFalse() { + void givenNegative_whenFrom_isNegative() { assertFalse(NumberInfo.from(-1) .isPositive()); assertFalse(NumberInfo.from(-10) @@ -30,7 +30,7 @@ class NumberInfoUnitTest { } @Test - void whenEven_isEven() { + void givenEven_whenFrom_isEven() { assertTrue(NumberInfo.from(0) .isEven()); assertTrue(NumberInfo.from(-2) @@ -44,7 +44,7 @@ class NumberInfoUnitTest { } @Test - void whenOdd_isEven_isFalse() { + void givenOdd_whenFrom_isOdd() { assertFalse(NumberInfo.from(1) .isEven()); @@ -62,7 +62,7 @@ class NumberInfoUnitTest { } @Test - void testStatic_fromMethod_equals_getNumber() { + void giveGeneratedInt_whenFrom_isNumberFromGenerator() { for (int i = -100; i < 100; i++) { assertEquals(i, NumberInfo.from(i) .getNumber()); diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java index 9b490799db..cea0626168 100644 --- a/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoClassifierUnitTest.java @@ -8,7 +8,7 @@ import org.junit.jupiter.api.Test; class NumberInfoClassifierUnitTest { @Test - void process_convertsToInteger() throws Exception { + void givenNumberInfo_whenProcess_thenConvertsToInteger() throws Exception { NumberInfoClassifier nic = new NumberInfoClassifier(); assertEquals(Integer.valueOf(4), nic.process(NumberInfo.from(4))); assertEquals(Integer.valueOf(-4), nic.process(NumberInfo.from(-4))); diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java index 7794003959..62fe35add6 100644 --- a/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java @@ -8,7 +8,7 @@ import org.junit.jupiter.api.Test; public class NumberInfoGeneratorUnitTest { @Test - public void testGenerateNumbers_correctOrderAndValue() { + public void givenArray_whenGenerator_correctOrderAndValue() { int[] numbers = new int[]{1, -2, 4, -10}; NumberInfoGenerator numberGenerator = new NumberInfoGenerator(numbers); assertEquals(new NumberInfo(numbers[0]), numberGenerator.read()); From d3b35f9f0cfb9ef49366f3b7f9db10f891fb0f6d Mon Sep 17 00:00:00 2001 From: Eduard Ardeleanu Date: Fri, 20 Mar 2020 17:28:47 +0200 Subject: [PATCH 15/59] BAEL-3853: Helpful NPE in Java 14 --- .../HelpfulNullPointerException.java | 56 +++++++++++++++++++ .../HelpfulNullPointerExceptionUnitTest.java | 37 ++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 core-java-modules/core-java-14/src/main/java/com/baeldung/java14/helpfulnullpointerexceptions/HelpfulNullPointerException.java create mode 100644 core-java-modules/core-java-14/src/test/java/com/baeldung/java14/helpfulnullpointerexceptions/HelpfulNullPointerExceptionUnitTest.java diff --git a/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/helpfulnullpointerexceptions/HelpfulNullPointerException.java b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/helpfulnullpointerexceptions/HelpfulNullPointerException.java new file mode 100644 index 0000000000..ef5dbb754c --- /dev/null +++ b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/helpfulnullpointerexceptions/HelpfulNullPointerException.java @@ -0,0 +1,56 @@ +package com.baeldung.java14.helpfulnullpointerexceptions; + +public class HelpfulNullPointerException { + + public static void main(String[] args) { + Employee employee = null; + employee.getName(); + } + + public String getEmployeeEmailAddress(Employee employee) { + String emailAddress = employee.getPersonalDetails().getEmailAddress().toLowerCase(); + return emailAddress; + } + + static class Employee { + String name; + PersonalDetails personalDetails; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public PersonalDetails getPersonalDetails() { + return personalDetails; + } + + public void setPersonalDetails(PersonalDetails personalDetails) { + this.personalDetails = personalDetails; + } + } + + static class PersonalDetails { + String emailAddress; + String phone; + + public String getEmailAddress() { + return emailAddress; + } + + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + } +} diff --git a/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/helpfulnullpointerexceptions/HelpfulNullPointerExceptionUnitTest.java b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/helpfulnullpointerexceptions/HelpfulNullPointerExceptionUnitTest.java new file mode 100644 index 0000000000..fae331bb92 --- /dev/null +++ b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/helpfulnullpointerexceptions/HelpfulNullPointerExceptionUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.java14.helpfulnullpointerexceptions; + +import org.junit.Test; + +import static com.baeldung.java14.helpfulnullpointerexceptions.HelpfulNullPointerException.Employee; +import static com.baeldung.java14.helpfulnullpointerexceptions.HelpfulNullPointerException.PersonalDetails; +import static org.assertj.core.api.Assertions.assertThat; + +public class HelpfulNullPointerExceptionUnitTest { + + @Test (expected = NullPointerException.class) + public void givenAnEmptyPersonalDetails_whenEmailAddressIsAccessed_thenThrowNPE() { + var helpfulNPE = new HelpfulNullPointerException(); + + var employee = new Employee(); + employee.setName("Eduard"); + employee.setPersonalDetails(new PersonalDetails()); + helpfulNPE.getEmployeeEmailAddress(employee); + } + + @Test + public void givenCompletePersonalDetails_whenEmailAddressIsAccessed_thenSuccess() { + var helpfulNPE = new HelpfulNullPointerException(); + var emailAddress = "eduard@gmx.com"; + + var employee = new Employee(); + employee.setName("Eduard"); + + var personalDetails = new PersonalDetails(); + personalDetails.setEmailAddress(emailAddress.toUpperCase()); + personalDetails.setPhone("1234"); + employee.setPersonalDetails(personalDetails); + + assertThat(helpfulNPE.getEmployeeEmailAddress(employee)).isEqualTo(emailAddress); + } + +} From 63bfa3706ad5739d42959458ec5fc51258154871 Mon Sep 17 00:00:00 2001 From: ajay74984 <51405689+ajay74984@users.noreply.github.com> Date: Sat, 21 Mar 2020 11:17:11 +0100 Subject: [PATCH 16/59] revert changes --- java-numbers-3/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/java-numbers-3/README.md b/java-numbers-3/README.md index a331a979ad..08e8dae8ef 100644 --- a/java-numbers-3/README.md +++ b/java-numbers-3/README.md @@ -2,4 +2,3 @@ - [Generating Random Numbers](https://www.baeldung.com/java-generating-random-numbers) - [Convert Double to Long in Java](https://www.baeldung.com/java-convert-double-long) -- [Guide to the Java Number Class](http://inprogress.baeldung.com/?p=180694&preview=true) From 0876b7fdc8a9e6748286b855f45bc8703a8bfeb7 Mon Sep 17 00:00:00 2001 From: Waldemar Date: Sat, 21 Mar 2020 15:41:40 +0100 Subject: [PATCH 17/59] BAEL-2398 add example --- coroutines-java/pom.xml | 89 +++++++++++++++++++ .../src/main/java/com/baeldung/App.java | 11 +++ 2 files changed, 100 insertions(+) create mode 100644 coroutines-java/pom.xml create mode 100644 coroutines-java/src/main/java/com/baeldung/App.java diff --git a/coroutines-java/pom.xml b/coroutines-java/pom.xml new file mode 100644 index 0000000000..c48efac934 --- /dev/null +++ b/coroutines-java/pom.xml @@ -0,0 +1,89 @@ + + 4.0.0 + + com.baeldung + coroutines-java + 1.0-SNAPSHOT + + coroutines-java + http://baeldung.com + + + UTF-8 + 1.8 + 1.8 + + + + + co.paralleluniverse + quasar-core + 0.8.0 + + + co.paralleluniverse + quasar-actors + 0.8.0 + + + co.paralleluniverse + quasar-reactive-streams + 0.8.0 + + + + + + + maven-dependency-plugin + 3.1.2 + + + getClasspathFilenames + + properties + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + com.baeldung.App + target/classes + java + + + -Dco.paralleluniverse.fibers.verifyInstrumentation=true + + + -javaagent:${co.paralleluniverse:quasar-core:jar} + + + -classpath + + + + com.baeldung.App + + + + + maven-compiler-plugin + 3.8.0 + + + org.apache.maven.plugins + maven-compiler-plugin + + 12 + 12 + + + + + diff --git a/coroutines-java/src/main/java/com/baeldung/App.java b/coroutines-java/src/main/java/com/baeldung/App.java new file mode 100644 index 0000000000..09157b1566 --- /dev/null +++ b/coroutines-java/src/main/java/com/baeldung/App.java @@ -0,0 +1,11 @@ +package com.baeldung; + +import co.paralleluniverse.fibers.Fiber; + +public class App { + public static void main(String[] args) { + new Fiber(() -> { + System.out.println("Inside fiber coroutine..."); + }).start(); + } +} From 380344f38ae15277f392cc5597bb63411207c0e3 Mon Sep 17 00:00:00 2001 From: Waldemar Date: Sat, 21 Mar 2020 15:47:20 +0100 Subject: [PATCH 18/59] BAEL-2398 pom formatting --- coroutines-java/pom.xml | 158 ++++++++++++++++++++-------------------- 1 file changed, 79 insertions(+), 79 deletions(-) diff --git a/coroutines-java/pom.xml b/coroutines-java/pom.xml index c48efac934..8d08bfdc88 100644 --- a/coroutines-java/pom.xml +++ b/coroutines-java/pom.xml @@ -1,89 +1,89 @@ - 4.0.0 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - com.baeldung - coroutines-java - 1.0-SNAPSHOT + com.baeldung + coroutines-java + 1.0-SNAPSHOT - coroutines-java - http://baeldung.com + coroutines-java + http://baeldung.com - - UTF-8 - 1.8 - 1.8 - + + UTF-8 + 1.8 + 1.8 + - - - co.paralleluniverse - quasar-core - 0.8.0 - - - co.paralleluniverse - quasar-actors - 0.8.0 - - - co.paralleluniverse - quasar-reactive-streams - 0.8.0 - - + + + co.paralleluniverse + quasar-core + 0.8.0 + + + co.paralleluniverse + quasar-actors + 0.8.0 + + + co.paralleluniverse + quasar-reactive-streams + 0.8.0 + + - - - - maven-dependency-plugin - 3.1.2 - - - getClasspathFilenames - - properties - - - - - - org.codehaus.mojo - exec-maven-plugin - 1.6.0 - - com.baeldung.App - target/classes - java - - - -Dco.paralleluniverse.fibers.verifyInstrumentation=true + + + + maven-dependency-plugin + 3.1.2 + + + getClasspathFilenames + + properties + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + com.baeldung.App + target/classes + java + + + -Dco.paralleluniverse.fibers.verifyInstrumentation=true - - -javaagent:${co.paralleluniverse:quasar-core:jar} + + -javaagent:${co.paralleluniverse:quasar-core:jar} - - -classpath - + + -classpath + - - com.baeldung.App - - - - - maven-compiler-plugin - 3.8.0 - - - org.apache.maven.plugins - maven-compiler-plugin - - 12 - 12 - - - - + + com.baeldung.App + + + + + maven-compiler-plugin + 3.8.0 + + + org.apache.maven.plugins + maven-compiler-plugin + + 12 + 12 + + + + From 51ad7ac4138ba728dde7f3d41cbbb14a88e448fb Mon Sep 17 00:00:00 2001 From: mike b Date: Tue, 24 Mar 2020 10:36:56 -0400 Subject: [PATCH 19/59] [BAEL-3646] addressing pr issues --- .../conditionalflow/step/NumberInfoClassifierWithDecider.java | 3 --- .../baeldung/conditionalflow/step/PrependingStdoutWriter.java | 4 +--- .../conditionalflow/step/NumberInfoGeneratorUnitTest.java | 3 ++- 3 files changed, 3 insertions(+), 7 deletions(-) diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java index b9d251c02d..4a8b7f1963 100644 --- a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/NumberInfoClassifierWithDecider.java @@ -1,9 +1,6 @@ package org.baeldung.conditionalflow.step; import org.baeldung.conditionalflow.model.NumberInfo; -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.StepExecution; -import org.springframework.batch.core.annotation.BeforeStep; import org.springframework.batch.core.listener.ItemListenerSupport; import org.springframework.batch.item.ItemProcessor; diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java index 283b43f267..c6f77df2ba 100644 --- a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java @@ -7,11 +7,9 @@ import org.springframework.batch.item.ItemWriter; public class PrependingStdoutWriter implements ItemWriter { private String prependText; - private OutputStream writeTo; - public PrependingStdoutWriter(String prependText, OutputStream os) { + public PrependingStdoutWriter(String prependText) { this.prependText = prependText; - this.writeTo = os; } public PrependingStdoutWriter(String prependText) { diff --git a/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java index 62fe35add6..90fd884674 100644 --- a/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java +++ b/spring-batch/src/test/java/org/baeldung/conditionalflow/step/NumberInfoGeneratorUnitTest.java @@ -7,9 +7,10 @@ import org.baeldung.conditionalflow.model.NumberInfo; import org.junit.jupiter.api.Test; public class NumberInfoGeneratorUnitTest { + @Test public void givenArray_whenGenerator_correctOrderAndValue() { - int[] numbers = new int[]{1, -2, 4, -10}; + int[] numbers = new int[] { 1, -2, 4, -10 }; NumberInfoGenerator numberGenerator = new NumberInfoGenerator(numbers); assertEquals(new NumberInfo(numbers[0]), numberGenerator.read()); assertEquals(new NumberInfo(numbers[1]), numberGenerator.read()); From a7ed49c4439fb29a5bd0d48da2812ba9dfdf3413 Mon Sep 17 00:00:00 2001 From: Waldemar Date: Tue, 24 Mar 2020 18:42:00 +0100 Subject: [PATCH 20/59] BAEL-2398: rename package name --- .../src/main/java/com/baeldung/{ => introduction}/App.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename coroutines-java/src/main/java/com/baeldung/{ => introduction}/App.java (100%) diff --git a/coroutines-java/src/main/java/com/baeldung/App.java b/coroutines-java/src/main/java/com/baeldung/introduction/App.java similarity index 100% rename from coroutines-java/src/main/java/com/baeldung/App.java rename to coroutines-java/src/main/java/com/baeldung/introduction/App.java From a7cb075f7d8cb308d6ced810233abbd485efe9f6 Mon Sep 17 00:00:00 2001 From: mike b Date: Tue, 24 Mar 2020 19:57:00 -0400 Subject: [PATCH 21/59] [BAEL-3646] Addressing broken PR --- .../conditionalflow/step/PrependingStdoutWriter.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java index c6f77df2ba..913c0885a9 100644 --- a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java @@ -12,12 +12,8 @@ public class PrependingStdoutWriter implements ItemWriter { this.prependText = prependText; } - public PrependingStdoutWriter(String prependText) { - this(prependText, System.out); - } - @Override - public void write(List list) throws Exception { + public void write(List list) { for (T listItem : list) { System.out.println(prependText + " " + listItem.toString()); } From c4ba08d9e5026059a3d070aafcf904a579cb86fe Mon Sep 17 00:00:00 2001 From: mike b Date: Tue, 24 Mar 2020 20:02:23 -0400 Subject: [PATCH 22/59] [BAEL-3646] remove unused import --- .../baeldung/conditionalflow/step/PrependingStdoutWriter.java | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java index 913c0885a9..9ffea1e798 100644 --- a/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java +++ b/spring-batch/src/main/java/org/baeldung/conditionalflow/step/PrependingStdoutWriter.java @@ -1,6 +1,5 @@ package org.baeldung.conditionalflow.step; -import java.io.OutputStream; import java.util.List; import org.springframework.batch.item.ItemWriter; From 9d11370afcda84ac9f07b9872f86f674e1767302 Mon Sep 17 00:00:00 2001 From: mike b Date: Wed, 25 Mar 2020 20:23:05 -0400 Subject: [PATCH 23/59] [bael-3646] trying to resolve merge conflict. --- spring-batch/repository.sqlite | Bin 73728 -> 73728 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/spring-batch/repository.sqlite b/spring-batch/repository.sqlite index 9d260fa2d1eed9ab00ea099508119d8e44235d87..2b549352ec8073708bd085fd414ed93d189c7511 100644 GIT binary patch delta 3276 zcmeHJUu;uV7{BNC-fPQRZd;t#GH8itU0~b2xA$M8MA_EC*xF7g!HwwX{l`k(TBI8f z(`+%~gBrHwJoEuH@kJg?jIP5MA0!f=L>$BiBhlc4kw;9-LX?Q-oOZPulF6HKG`ZjX zecwIj~+l4j?0LD$8& zA=s9n#T8Xm6q=>n9jTLre5sV5IM$sjn`8TnhV4kQWJsbWNseJEdQLV(*%1F2^lTlgnLRKO5wK=U1u${}~p(n+$ZXe10_tN=OzCX7?P(CVLO1 z2hy3t>6#6mqJ0zqEX#&M=UZ8drm=nbdm?`#Ylh%2$pY}fz(6~^+sDE;`vx0YmY`1f z!u~e+&R(HOvsul6kjm&f)IJ4S6VmEYc^eb67N@41!N8oLMT=*sb@2pU83 zL}41sX)FT+AvpU|idc8UxmTVfw#VUU>M%wVyJ6|oCkV3Z`lsnALMIAOL%xU+zS+^t zPJ$u{a_Q$Z;H7{E@e+yn5G~mF^(2vBV7dHdPbM`qm_&RMfJ(t%{Vj8b_o%vta#vGz zxG>t*S<_TGKKvN%0in$?x7*Fr2eSwI(|eB>js9Ly(dF7AMU>$6(Jf)3shX}0v*=Ws zU%_P-s0Yfn1jw61*0Wa9GO~}7Lh^qDN=^sq?ax?>lsW2SM z_(=%2Icojd>mZ;UVM2$W6}Rp{#I%s`RU6@RxmE+X(S?Zi(TlUdzmva10sc0{-$sI> zTF~Qddb^u3Dz$SPA9_teJ?8asn0xyzI5MZuY633I9dpwRjn-1k;ye(lVEH=xAU4g# z_U~eYtBgc#=@UQrjz!sjjk#C$Ut=r3wt{v<@zv8L=u6G%KkYJ$9{jj4mt z6YaGw@?Y;wJK&9(4N#qtNbzEgf%7xF8d|v0%7Z{d#UH(u5gu%F#WVH?a?a29n6WqEDc9d;tc$FzPi2BHqZu1T z6On^MQ%4@;=|A%HtHoQ}xFD{2MAju?xK`C4Z2^}LoG++S7Q5=Ux(H$0YQxBt}Ud>3drr4BUrS(i19yphT F(x1b+3nl;n delta 2982 zcmd^AO>7%Q6y8~97dwBp)1P3s)J8415w)|s-t}%&Q8kHO$8GJD#8s(~NH^m(cG|{P zvZ&$$;f_M8IrxCYkC4i-tqtc!z@-OBkszckRp>1TkcfmLr69qZ@g`~nDC&*2mfz3J z?2O*e_uiYCZ<(2InG1HIHjd-EfHr>k@*#ysZP(AmT&RP{LU-eeYl%l5PceQLpsV@)zGEbFqV7z(yb-B1u* zi)4%CscC!T4ps_g5#HBjtn1iN3w^TGW+hBLVW`t{zxwnn?OmS`3| zs?EII63KeDHQ7pd9x}PN-6y!ce|Xm#e&4J>K1}%sRu;H5R0Y01n(rUUr;?|0CvwAQ za%}Gbxx{yH2nm7^2z<6n;CPOA=_-9z3kzQW{sF%R-M`8X|sdlj%t>qMTQ_hRJs#9?y%b_w(za`nUrlQ-^A z86fXp$U6HwN$}!9&|e_c>=}?DvV1Ywls_GF*89jpE(|(-X9t>1!`V|OQxGkt0MPx72g9>okE+EDRRdg+ z%VT?E&MK~*-OqbapgZDryS@Bqek7AiPgKS;Nm(=0=0|d$M(&R739^-HDEe6eUgf=O zw1|98$_fIptw?ZX0lA%IrCv=9p3cK_)GXvCUs#b=$mJrl@)r_W+)rkfd?Zjj%shXL zGt{{yL%)(6mFG&}smVP3YBL`$*G5LVToAcVfG@`(QRLw7qoH)j??^95O0-|mzD21W zh+f;&p<2EaYT|CR(+5$0k;OVfxjzZu4+E&h+9?rLJBMt$I#ijq2P>147Os6GqVJ#2 zRl-x1H*G6ySHdMY3m?Sn)D9QT@&&8V1DVOx{(J`guM4DRc#*=Y<=nEb_K_FSQlh03 z1ixt@>Q&_X6wOHubnWi0rw4-v{u_g|Juq~BUH|#M0LbB>c6cBFrhbE&OawKijYgLtrObCFz3v4sza$h z)TGA9)y3Y&yXCy(^r0w|_2mJOfmU3ZvYPJJZ`~2-kc|H8kc^Svf9UbUv73DzY=TX! N#YFV(6CayBe*?Yuegpsj From 552aef2fdfcba4993d282cdb36f262430035b543 Mon Sep 17 00:00:00 2001 From: Waldemar Date: Fri, 27 Mar 2020 20:28:39 +0100 Subject: [PATCH 24/59] BAEL-2398: rename package --- coroutines-java/pom.xml | 4 ++-- .../src/main/java/com/baeldung/introduction/App.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/coroutines-java/pom.xml b/coroutines-java/pom.xml index 8d08bfdc88..3546aa5673 100644 --- a/coroutines-java/pom.xml +++ b/coroutines-java/pom.xml @@ -53,7 +53,7 @@ exec-maven-plugin 1.6.0 - com.baeldung.App + com.baeldung.introduction.App target/classes java @@ -68,7 +68,7 @@ - com.baeldung.App + com.baeldung.introduction.App diff --git a/coroutines-java/src/main/java/com/baeldung/introduction/App.java b/coroutines-java/src/main/java/com/baeldung/introduction/App.java index 09157b1566..f915464973 100644 --- a/coroutines-java/src/main/java/com/baeldung/introduction/App.java +++ b/coroutines-java/src/main/java/com/baeldung/introduction/App.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.introduction; import co.paralleluniverse.fibers.Fiber; From 106d35c490beb67f1824f8a647c20184afe895c6 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sat, 28 Mar 2020 15:44:15 +0530 Subject: [PATCH 25/59] JAVA-624: Added new module java-collections-maps-3 --- .../java/com/baeldung/map/compare/HashMapComparisonUnitTest.java | 0 .../com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {java-collections-maps => java-collections-maps-3}/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java (100%) rename {java-collections-maps-2 => java-collections-maps-3}/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java (100%) diff --git a/java-collections-maps/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java similarity index 100% rename from java-collections-maps/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java rename to java-collections-maps-3/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java similarity index 100% rename from java-collections-maps-2/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java rename to java-collections-maps-3/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java From 7dad227d93262d53733437de31ace468ab096299 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sat, 28 Mar 2020 15:46:17 +0530 Subject: [PATCH 26/59] JAVA-624: Updated READMEs and pom for new module --- java-collections-maps-2/README.md | 3 +-- java-collections-maps-3/README.md | 8 ++++++++ java-collections-maps-3/pom.xml | 26 ++++++++++++++++++++++++++ java-collections-maps/README.md | 3 +-- 4 files changed, 36 insertions(+), 4 deletions(-) create mode 100644 java-collections-maps-3/README.md create mode 100644 java-collections-maps-3/pom.xml diff --git a/java-collections-maps-2/README.md b/java-collections-maps-2/README.md index 8b33276f56..71c6a3f32b 100644 --- a/java-collections-maps-2/README.md +++ b/java-collections-maps-2/README.md @@ -13,5 +13,4 @@ This module contains articles about Map data structures in Java. - [Sort a HashMap in Java](https://www.baeldung.com/java-hashmap-sort) - [Finding the Highest Value in a Java Map](https://www.baeldung.com/java-find-map-max) - [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) -- [Java TreeMap vs HashMap](https://www.baeldung.com/java-treemap-vs-hashmap) -- More articles: [[<-- prev>]](/../java-collections-maps) +- More articles: [[<-- prev>]](/java-collections-maps) [[next -->]](/java-collections-maps-3) diff --git a/java-collections-maps-3/README.md b/java-collections-maps-3/README.md new file mode 100644 index 0000000000..8f185f6ad4 --- /dev/null +++ b/java-collections-maps-3/README.md @@ -0,0 +1,8 @@ +## Java Collections Cookbooks and Examples + +This module contains articles about Map data structures in Java. + +### Relevant Articles: +- [Java TreeMap vs HashMap](https://www.baeldung.com/java-treemap-vs-hashmap) +- [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps) +- More articles: [[<-- prev>]](/java-collections-maps-2) diff --git a/java-collections-maps-3/pom.xml b/java-collections-maps-3/pom.xml new file mode 100644 index 0000000000..30b0d01528 --- /dev/null +++ b/java-collections-maps-3/pom.xml @@ -0,0 +1,26 @@ + + + 4.0.0 + java-collections-maps-3 + 0.1.0-SNAPSHOT + java-collections-maps-3 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + + + + + + + \ No newline at end of file diff --git a/java-collections-maps/README.md b/java-collections-maps/README.md index dfd0d47dbc..8fa6fa32fa 100644 --- a/java-collections-maps/README.md +++ b/java-collections-maps/README.md @@ -10,8 +10,7 @@ This module contains articles about Map data structures in Java. - [How to Store Duplicate Keys in a Map in Java?](https://www.baeldung.com/java-map-duplicate-keys) - [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value) - [How to Check If a Key Exists in a Map](https://www.baeldung.com/java-map-key-exists) -- [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps) - [Immutable Map Implementations in Java](https://www.baeldung.com/java-immutable-maps) - [Guide to Apache Commons MultiValuedMap](https://www.baeldung.com/apache-commons-multi-valued-map) - [The Java HashMap Under the Hood](https://www.baeldung.com/java-hashmap-advanced) -- More articles: [[next -->]](/../java-collections-maps-2) +- More articles: [[next -->]](/java-collections-maps-2) From 7084709cd365a91d0eedf3ef2965ea5bcbda759f Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sat, 28 Mar 2020 15:46:52 +0530 Subject: [PATCH 27/59] JAVA-624: Added new module java-collections-maps-3 to main pom --- pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pom.xml b/pom.xml index 04a2ce054c..17cba6a494 100644 --- a/pom.xml +++ b/pom.xml @@ -456,6 +456,7 @@ java-collections-conversions-2 java-collections-maps java-collections-maps-2 + java-collections-maps-3 javafx @@ -967,6 +968,7 @@ java-collections-conversions-2 java-collections-maps java-collections-maps-2 + java-collections-maps-3 javafx From c18d09cd33c44bfe7fbd739d98ba0fb341b569cc Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sat, 28 Mar 2020 16:48:04 +0530 Subject: [PATCH 28/59] JAVA-623: Moved 3 articles from core-java-security to security-2 --- .../core-java-security/README.md | 5 +- core-java-modules/core-java-security/pom.xml | 15 -- .../baeldung/hashing/DigestAlgorithms.java | 9 -- .../baeldung/hashing/Keccak256Hashing.java | 30 ---- .../com/baeldung/hashing/SHA256Hashing.java | 39 ----- .../com/baeldung/hashing/SHA3Hashing.java | 45 ------ .../com/baeldung/hashing/SHACommonUtils.java | 16 -- .../passwordhashing/PBKDF2Hasher.java | 149 ------------------ .../passwordhashing/SHA512Hasher.java | 35 ---- .../passwordhashing/SimplePBKDF2Hasher.java | 18 --- .../hashing/Keccak256HashingUnitTest.java | 22 --- .../hashing/SHA256HashingUnitTest.java | 35 ---- .../baeldung/hashing/SHA3HashingUnitTest.java | 38 ----- .../baeldung/java/md5/JavaMD5UnitTest.java | 75 --------- .../passwordhashing/PBKDF2HasherUnitTest.java | 41 ----- .../passwordhashing/SHA512HasherUnitTest.java | 70 -------- .../src/test/resources/test_md5.txt | 1 - 17 files changed, 2 insertions(+), 641 deletions(-) delete mode 100644 core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/DigestAlgorithms.java delete mode 100644 core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/Keccak256Hashing.java delete mode 100644 core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHA256Hashing.java delete mode 100644 core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHA3Hashing.java delete mode 100644 core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHACommonUtils.java delete mode 100644 core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java delete mode 100644 core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java delete mode 100644 core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java delete mode 100644 core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java delete mode 100644 core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java delete mode 100644 core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java delete mode 100644 core-java-modules/core-java-security/src/test/java/com/baeldung/java/md5/JavaMD5UnitTest.java delete mode 100644 core-java-modules/core-java-security/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java delete mode 100644 core-java-modules/core-java-security/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java delete mode 100644 core-java-modules/core-java-security/src/test/resources/test_md5.txt diff --git a/core-java-modules/core-java-security/README.md b/core-java-modules/core-java-security/README.md index ff9b1eef14..83b12793b5 100644 --- a/core-java-modules/core-java-security/README.md +++ b/core-java-modules/core-java-security/README.md @@ -3,17 +3,16 @@ This module contains articles about core Java Security ### Relevant Articles: -- [MD5 Hashing in Java](http://www.baeldung.com/java-md5) + - [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class) - [Introduction to SSL in Java](http://www.baeldung.com/java-ssl) - [Java KeyStore API](http://www.baeldung.com/java-keystore) - [Encrypting and Decrypting Files in Java](http://www.baeldung.com/java-cipher-input-output-stream) -- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing) - [SSL Handshake Failures](https://www.baeldung.com/java-ssl-handshake-failures) -- [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java) - [Enabling TLS v1.2 in Java 7](https://www.baeldung.com/java-7-tls-v12) - [The Java SecureRandom Class](https://www.baeldung.com/java-secure-random) - [An Introduction to Java SASL](https://www.baeldung.com/java-sasl) - [A Guide to Java GSS API](https://www.baeldung.com/java-gss) - [Intro to the Java SecurityManager](https://www.baeldung.com/java-security-manager) +- More articles: [[next -->]](/core-java-modules/core-java-security-2) diff --git a/core-java-modules/core-java-security/pom.xml b/core-java-modules/core-java-security/pom.xml index a46c2e2d40..96024a73a1 100644 --- a/core-java-modules/core-java-security/pom.xml +++ b/core-java-modules/core-java-security/pom.xml @@ -24,24 +24,9 @@ ${assertj-core.version} test - - - commons-codec - commons-codec - ${commons-codec.version} - - - org.bouncycastle - bcprov-jdk15on - ${bouncycastle.version} - - - 1.60 - 1.11 - 3.10.0 diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/DigestAlgorithms.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/DigestAlgorithms.java deleted file mode 100644 index 94dd22ff4b..0000000000 --- a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/DigestAlgorithms.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.hashing; - -public class DigestAlgorithms { - - public static final String SHA3_256 = "SHA3-256"; - public static final String SHA_256 = "SHA-256"; - public static final String KECCAK_256 = "Keccak-256"; - -} diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/Keccak256Hashing.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/Keccak256Hashing.java deleted file mode 100644 index 19fc4cf059..0000000000 --- a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/Keccak256Hashing.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.hashing; - -import org.bouncycastle.jcajce.provider.digest.Keccak; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.util.encoders.Hex; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.Security; - -import static com.baeldung.hashing.DigestAlgorithms.KECCAK_256; -import static com.baeldung.hashing.SHACommonUtils.bytesToHex; - -public class Keccak256Hashing { - - public static String hashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException { - Security.addProvider(new BouncyCastleProvider()); - final MessageDigest digest = MessageDigest.getInstance(KECCAK_256); - final byte[] encodedhash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8)); - return bytesToHex(encodedhash); - } - - public static String hashWithBouncyCastle(final String originalString) { - Keccak.Digest256 digest256 = new Keccak.Digest256(); - byte[] hashbytes = digest256.digest(originalString.getBytes(StandardCharsets.UTF_8)); - return new String(Hex.encode(hashbytes)); - } - -} diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHA256Hashing.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHA256Hashing.java deleted file mode 100644 index ec008cebab..0000000000 --- a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHA256Hashing.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.hashing; - -import com.google.common.hash.Hashing; -import org.apache.commons.codec.digest.DigestUtils; -import org.bouncycastle.util.encoders.Hex; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -import static com.baeldung.hashing.DigestAlgorithms.SHA_256; -import static com.baeldung.hashing.SHACommonUtils.bytesToHex; - -public class SHA256Hashing { - - public static String HashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException { - final MessageDigest digest = MessageDigest.getInstance(SHA_256); - final byte[] encodedhash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8)); - return bytesToHex(encodedhash); - } - - public static String hashWithGuava(final String originalString) { - final String sha256hex = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString(); - return sha256hex; - } - - public static String HashWithApacheCommons(final String originalString) { - final String sha256hex = DigestUtils.sha256Hex(originalString); - return sha256hex; - } - - public static String HashWithBouncyCastle(final String originalString) throws NoSuchAlgorithmException { - final MessageDigest digest = MessageDigest.getInstance(SHA_256); - final byte[] hash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8)); - final String sha256hex = new String(Hex.encode(hash)); - return sha256hex; - } - -} diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHA3Hashing.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHA3Hashing.java deleted file mode 100644 index eb363205b1..0000000000 --- a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHA3Hashing.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.hashing; - -import com.google.common.hash.Hashing; -import org.apache.commons.codec.digest.DigestUtils; -import org.bouncycastle.crypto.digests.SHA3Digest; -import org.bouncycastle.jcajce.provider.digest.SHA3; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.util.encoders.Hex; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.Security; - -import static com.baeldung.hashing.DigestAlgorithms.SHA3_256; -import static com.baeldung.hashing.SHACommonUtils.bytesToHex; - -public class SHA3Hashing { - - /* works with JDK9+ only */ - public static String hashWithJavaMessageDigestJDK9(final String originalString) throws NoSuchAlgorithmException { - final MessageDigest digest = MessageDigest.getInstance(SHA3_256); - final byte[] hashbytes = digest.digest(originalString.getBytes(StandardCharsets.UTF_8)); - return bytesToHex(hashbytes); - } - - public static String hashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException { - Security.addProvider(new BouncyCastleProvider()); - final MessageDigest digest = MessageDigest.getInstance(SHA3_256); - final byte[] hashbytes = digest.digest(originalString.getBytes(StandardCharsets.UTF_8)); - return bytesToHex(hashbytes); - } - - /* works with JDK9+ only */ - public static String hashWithApacheCommonsJDK9(final String originalString) { - return new DigestUtils(SHA3_256).digestAsHex(originalString); - } - - public static String hashWithBouncyCastle(final String originalString) { - SHA3.Digest256 digest256 = new SHA3.Digest256(); - byte[] hashbytes = digest256.digest(originalString.getBytes(StandardCharsets.UTF_8)); - return new String(Hex.encode(hashbytes)); - } - -} diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHACommonUtils.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHACommonUtils.java deleted file mode 100644 index 0f28408083..0000000000 --- a/core-java-modules/core-java-security/src/main/java/com/baeldung/hashing/SHACommonUtils.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.hashing; - -class SHACommonUtils { - - public static String bytesToHex(byte[] hash) { - StringBuffer hexString = new StringBuffer(); - for (byte h : hash) { - String hex = Integer.toHexString(0xff & h); - if (hex.length() == 1) - hexString.append('0'); - hexString.append(hex); - } - return hexString.toString(); - } - -} diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java deleted file mode 100644 index e2259e4249..0000000000 --- a/core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java +++ /dev/null @@ -1,149 +0,0 @@ -package com.baeldung.passwordhashing; - -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.KeySpec; -import java.util.Arrays; -import java.util.Base64; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.PBEKeySpec; - -/** - * Hash passwords for storage, and test passwords against password tokens. - * - * Instances of this class can be used concurrently by multiple threads. - * - * @author erickson - * @see StackOverflow - */ -public final class PBKDF2Hasher -{ - - /** - * Each token produced by this class uses this identifier as a prefix. - */ - public static final String ID = "$31$"; - - /** - * The minimum recommended cost, used by default - */ - public static final int DEFAULT_COST = 16; - - private static final String ALGORITHM = "PBKDF2WithHmacSHA1"; - - private static final int SIZE = 128; - - private static final Pattern layout = Pattern.compile("\\$31\\$(\\d\\d?)\\$(.{43})"); - - private final SecureRandom random; - - private final int cost; - - public PBKDF2Hasher() - { - this(DEFAULT_COST); - } - - /** - * Create a password manager with a specified cost - * - * @param cost the exponential computational cost of hashing a password, 0 to 30 - */ - public PBKDF2Hasher(int cost) - { - iterations(cost); /* Validate cost */ - this.cost = cost; - this.random = new SecureRandom(); - } - - private static int iterations(int cost) - { - if ((cost < 0) || (cost > 30)) - throw new IllegalArgumentException("cost: " + cost); - return 1 << cost; - } - - /** - * Hash a password for storage. - * - * @return a secure authentication token to be stored for later authentication - */ - public String hash(char[] password) - { - byte[] salt = new byte[SIZE / 8]; - random.nextBytes(salt); - byte[] dk = pbkdf2(password, salt, 1 << cost); - byte[] hash = new byte[salt.length + dk.length]; - System.arraycopy(salt, 0, hash, 0, salt.length); - System.arraycopy(dk, 0, hash, salt.length, dk.length); - Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding(); - return ID + cost + '$' + enc.encodeToString(hash); - } - - /** - * Authenticate with a password and a stored password token. - * - * @return true if the password and token match - */ - public boolean checkPassword(char[] password, String token) - { - Matcher m = layout.matcher(token); - if (!m.matches()) - throw new IllegalArgumentException("Invalid token format"); - int iterations = iterations(Integer.parseInt(m.group(1))); - byte[] hash = Base64.getUrlDecoder().decode(m.group(2)); - byte[] salt = Arrays.copyOfRange(hash, 0, SIZE / 8); - byte[] check = pbkdf2(password, salt, iterations); - int zero = 0; - for (int idx = 0; idx < check.length; ++idx) - zero |= hash[salt.length + idx] ^ check[idx]; - return zero == 0; - } - - private static byte[] pbkdf2(char[] password, byte[] salt, int iterations) - { - KeySpec spec = new PBEKeySpec(password, salt, iterations, SIZE); - try { - SecretKeyFactory f = SecretKeyFactory.getInstance(ALGORITHM); - return f.generateSecret(spec).getEncoded(); - } - catch (NoSuchAlgorithmException ex) { - throw new IllegalStateException("Missing algorithm: " + ALGORITHM, ex); - } - catch (InvalidKeySpecException ex) { - throw new IllegalStateException("Invalid SecretKeyFactory", ex); - } - } - - /** - * Hash a password in an immutable {@code String}. - * - *

Passwords should be stored in a {@code char[]} so that it can be filled - * with zeros after use instead of lingering on the heap and elsewhere. - * - * @deprecated Use {@link #hash(char[])} instead - */ - @Deprecated - public String hash(String password) - { - return hash(password.toCharArray()); - } - - /** - * Authenticate with a password in an immutable {@code String} and a stored - * password token. - * - * @deprecated Use {@link #checkPassword(char[],String)} instead. - * @see #hash(String) - */ - @Deprecated - public boolean checkPassword(String password, String token) - { - return checkPassword(password.toCharArray(), token); - } - -} diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java deleted file mode 100644 index 4f5337f963..0000000000 --- a/core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.passwordhashing; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - - -/** A really simple SHA_512 Encryption example. - * - */ -public class SHA512Hasher { - - public String hash(String passwordToHash, byte[] salt){ - String generatedPassword = null; - try { - MessageDigest md = MessageDigest.getInstance("SHA-512"); - md.update(salt); - byte[] bytes = md.digest(passwordToHash.getBytes(StandardCharsets.UTF_8)); - StringBuilder sb = new StringBuilder(); - for(int i=0; i< bytes.length ;i++){ - sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); - } - generatedPassword = sb.toString(); - } - catch (NoSuchAlgorithmException e){ - e.printStackTrace(); - } - return generatedPassword; - } - - public boolean checkPassword(String hash, String attempt, byte[] salt){ - String generatedHash = hash(attempt, salt); - return hash.equals(generatedHash); - } -} diff --git a/core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java b/core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java deleted file mode 100644 index 36c9b65070..0000000000 --- a/core-java-modules/core-java-security/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.passwordhashing; - -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.PBEKeySpec; -import java.security.spec.KeySpec; - -/** A really simple SimplePBKDF2 Encryption example. - * - */ -public class SimplePBKDF2Hasher { - - public static String hashSimple(String password, byte[] salt) throws Exception{ - KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128); - SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); - byte[] hash = f.generateSecret(spec).getEncoded(); - return String.valueOf(hash); - } -} diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java b/core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java deleted file mode 100644 index 9ed35c8834..0000000000 --- a/core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.hashing; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class Keccak256HashingUnitTest { - - private static String originalValue = "abc123"; - private static String hashedValue = "719accc61a9cc126830e5906f9d672d06eab6f8597287095a2c55a8b775e7016"; - - @Test public void testHashWithJavaMessageDigest() throws Exception { - final String currentHashedValue = Keccak256Hashing.hashWithJavaMessageDigest(originalValue); - assertEquals(hashedValue, currentHashedValue); - } - - @Test public void testHashWithBouncyCastle() { - final String currentHashedValue = Keccak256Hashing.hashWithBouncyCastle(originalValue); - assertEquals(hashedValue, currentHashedValue); - } - -} diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java b/core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java deleted file mode 100644 index 6bc9ad2cc6..0000000000 --- a/core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.hashing; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class SHA256HashingUnitTest { - - private static String originalValue = "abc123"; - private static String hashedValue = "6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090"; - - @Test - public void testHashWithJavaMessageDigest() throws Exception { - final String currentHashedValue = SHA256Hashing.HashWithJavaMessageDigest(originalValue); - assertEquals(hashedValue, currentHashedValue); - } - - @Test - public void testHashWithGuava() throws Exception { - final String currentHashedValue = SHA256Hashing.hashWithGuava(originalValue); - assertEquals(hashedValue, currentHashedValue); - } - - @Test - public void testHashWithApacheCommans() throws Exception { - final String currentHashedValue = SHA256Hashing.HashWithApacheCommons(originalValue); - assertEquals(hashedValue, currentHashedValue); - } - - @Test - public void testHashWithBouncyCastle() throws Exception { - final String currentHashedValue = SHA256Hashing.HashWithBouncyCastle(originalValue); - assertEquals(hashedValue, currentHashedValue); - } -} \ No newline at end of file diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java b/core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java deleted file mode 100644 index fffab96405..0000000000 --- a/core-java-modules/core-java-security/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.hashing; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class SHA3HashingUnitTest { - - private static String originalValue = "abc123"; - private static String hashedValue = "f58fa3df820114f56e1544354379820cff464c9c41cb3ca0ad0b0843c9bb67ee"; - - /* works with JDK9+ only */ - //@Test - public void testHashWithJavaMessageDigestJDK9() throws Exception { - final String currentHashedValue = SHA3Hashing.hashWithJavaMessageDigestJDK9(originalValue); - assertEquals(hashedValue, currentHashedValue); - } - - @Test - public void testHashWithJavaMessageDigest() throws Exception { - final String currentHashedValue = SHA3Hashing.hashWithJavaMessageDigest(originalValue); - assertEquals(hashedValue, currentHashedValue); - } - - /* works with JDK9+ only */ - //@Test - public void testHashWithApacheCommonsJDK9() { - final String currentHashedValue = SHA3Hashing.hashWithApacheCommonsJDK9(originalValue); - assertEquals(hashedValue, currentHashedValue); - } - - @Test - public void testHashWithBouncyCastle() { - final String currentHashedValue = SHA3Hashing.hashWithBouncyCastle(originalValue); - assertEquals(hashedValue, currentHashedValue); - } - -} diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/java/md5/JavaMD5UnitTest.java b/core-java-modules/core-java-security/src/test/java/com/baeldung/java/md5/JavaMD5UnitTest.java deleted file mode 100644 index 67d6918c09..0000000000 --- a/core-java-modules/core-java-security/src/test/java/com/baeldung/java/md5/JavaMD5UnitTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.java.md5; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; - -import javax.xml.bind.DatatypeConverter; - -import org.apache.commons.codec.digest.DigestUtils; -import org.junit.Test; - -import com.google.common.hash.HashCode; -import com.google.common.hash.Hashing; - -public class JavaMD5UnitTest { - - String filename = "src/test/resources/test_md5.txt"; - String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; - - String hash = "35454B055CC325EA1AF2126E27707052"; - String password = "ILoveJava"; - - @Test - public void givenPassword_whenHashing_thenVerifying() throws NoSuchAlgorithmException { - String hash = "35454B055CC325EA1AF2126E27707052"; - String password = "ILoveJava"; - - MessageDigest md = MessageDigest.getInstance("MD5"); - md.update(password.getBytes()); - byte[] digest = md.digest(); - String myHash = DatatypeConverter.printHexBinary(digest).toUpperCase(); - - assertThat(myHash.equals(hash)).isTrue(); - } - - @Test - public void givenFile_generatingChecksum_thenVerifying() throws NoSuchAlgorithmException, IOException { - String filename = "src/test/resources/test_md5.txt"; - String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; - - MessageDigest md = MessageDigest.getInstance("MD5"); - md.update(Files.readAllBytes(Paths.get(filename))); - byte[] digest = md.digest(); - String myChecksum = DatatypeConverter.printHexBinary(digest).toUpperCase(); - - assertThat(myChecksum.equals(checksum)).isTrue(); - } - - @Test - public void givenPassword_whenHashingUsingCommons_thenVerifying() { - String hash = "35454B055CC325EA1AF2126E27707052"; - String password = "ILoveJava"; - - String md5Hex = DigestUtils.md5Hex(password).toUpperCase(); - - assertThat(md5Hex.equals(hash)).isTrue(); - } - - @Test - public void givenFile_whenChecksumUsingGuava_thenVerifying() throws IOException { - String filename = "src/test/resources/test_md5.txt"; - String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; - - HashCode hash = com.google.common.io.Files.hash(new File(filename), Hashing.md5()); - String myChecksum = hash.toString().toUpperCase(); - - assertThat(myChecksum.equals(checksum)).isTrue(); - } - -} diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java b/core-java-modules/core-java-security/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java deleted file mode 100644 index 8e90725c77..0000000000 --- a/core-java-modules/core-java-security/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.passwordhashing; - -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - - -public class PBKDF2HasherUnitTest { - - private PBKDF2Hasher mPBKDF2Hasher; - - @Before - public void setUp() throws Exception { - mPBKDF2Hasher = new PBKDF2Hasher(); - } - - @Test - public void givenCorrectMessageAndHash_whenAuthenticated_checkAuthenticationSucceeds() throws Exception { - String message1 = "password123"; - - String hash1 = mPBKDF2Hasher.hash(message1.toCharArray()); - - assertTrue(mPBKDF2Hasher.checkPassword(message1.toCharArray(), hash1)); - - } - - @Test - public void givenWrongMessage_whenAuthenticated_checkAuthenticationFails() throws Exception { - String message1 = "password123"; - - String hash1 = mPBKDF2Hasher.hash(message1.toCharArray()); - - String wrongPasswordAttempt = "IamWrong"; - - assertFalse(mPBKDF2Hasher.checkPassword(wrongPasswordAttempt.toCharArray(), hash1)); - - } - - -} \ No newline at end of file diff --git a/core-java-modules/core-java-security/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java b/core-java-modules/core-java-security/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java deleted file mode 100644 index 3acfb0ba9d..0000000000 --- a/core-java-modules/core-java-security/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.baeldung.passwordhashing; - -import org.junit.Before; -import org.junit.Test; - -import java.security.SecureRandom; - -import static org.junit.Assert.*; - -/** - * Created by PhysicsSam on 06-Sep-18. - */ -public class SHA512HasherUnitTest { - - private SHA512Hasher hasher; - private SecureRandom secureRandom; - - @Before - public void setUp() throws Exception { - hasher = new SHA512Hasher(); - secureRandom = new SecureRandom(); - } - - @Test - public void givenSamePasswordAndSalt_whenHashed_checkResultingHashesAreEqual() throws Exception { - - byte[] salt = new byte[16]; - secureRandom.nextBytes(salt); - - String hash1 = hasher.hash("password", salt); - String hash2 = hasher.hash("password", salt); - - assertEquals(hash1, hash2); - - } - - @Test - public void givenSamePasswordAndDifferentSalt_whenHashed_checkResultingHashesNotEqual() throws Exception { - - byte[] salt = new byte[16]; - secureRandom.nextBytes(salt); - String hash1 = hasher.hash("password", salt); - //generate a second salt - byte[] secondSalt = new byte[16]; - String hash2 = hasher.hash("password", secondSalt); - - assertNotEquals(hash1, hash2); - - } - - @Test - public void givenPredefinedHash_whenCorrectAttemptGiven_checkAuthenticationSucceeds() throws Exception { - byte[] salt = new byte[16]; - secureRandom.nextBytes(salt); - - String originalHash = hasher.hash("password123", salt); - - assertTrue(hasher.checkPassword(originalHash, "password123", salt)); - } - - @Test - public void givenPredefinedHash_whenIncorrectAttemptGiven_checkAuthenticationFails() throws Exception { - byte[] salt = new byte[16]; - secureRandom.nextBytes(salt); - - String originalHash = hasher.hash("password123", salt); - - assertFalse(hasher.checkPassword(originalHash, "password124", salt)); - } -} \ No newline at end of file diff --git a/core-java-modules/core-java-security/src/test/resources/test_md5.txt b/core-java-modules/core-java-security/src/test/resources/test_md5.txt deleted file mode 100644 index 95d09f2b10..0000000000 --- a/core-java-modules/core-java-security/src/test/resources/test_md5.txt +++ /dev/null @@ -1 +0,0 @@ -hello world \ No newline at end of file From e2b6b4bc924f860cd2ab7d77ed17ad8e2d969b15 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sat, 28 Mar 2020 16:48:43 +0530 Subject: [PATCH 29/59] JAVA-623: Moved 3 articles to core-java-security-2 --- .../core-java-security-2/README.md | 8 + .../core-java-security-2/pom.xml | 30 ++++ .../baeldung/hashing/DigestAlgorithms.java | 9 ++ .../baeldung/hashing/Keccak256Hashing.java | 30 ++++ .../com/baeldung/hashing/SHA256Hashing.java | 39 +++++ .../com/baeldung/hashing/SHA3Hashing.java | 45 ++++++ .../com/baeldung/hashing/SHACommonUtils.java | 16 ++ .../passwordhashing/PBKDF2Hasher.java | 149 ++++++++++++++++++ .../passwordhashing/SHA512Hasher.java | 35 ++++ .../passwordhashing/SimplePBKDF2Hasher.java | 18 +++ .../hashing/Keccak256HashingUnitTest.java | 22 +++ .../hashing/SHA256HashingUnitTest.java | 35 ++++ .../baeldung/hashing/SHA3HashingUnitTest.java | 38 +++++ .../baeldung/java/md5/JavaMD5UnitTest.java | 75 +++++++++ .../passwordhashing/PBKDF2HasherUnitTest.java | 41 +++++ .../passwordhashing/SHA512HasherUnitTest.java | 70 ++++++++ .../src/test/resources/test_md5.txt | 1 + 17 files changed, 661 insertions(+) create mode 100644 core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/DigestAlgorithms.java create mode 100644 core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/Keccak256Hashing.java create mode 100644 core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHA256Hashing.java create mode 100644 core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHA3Hashing.java create mode 100644 core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHACommonUtils.java create mode 100644 core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java create mode 100644 core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java create mode 100644 core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java create mode 100644 core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java create mode 100644 core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java create mode 100644 core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java create mode 100644 core-java-modules/core-java-security-2/src/test/java/com/baeldung/java/md5/JavaMD5UnitTest.java create mode 100644 core-java-modules/core-java-security-2/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java create mode 100644 core-java-modules/core-java-security-2/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java create mode 100644 core-java-modules/core-java-security-2/src/test/resources/test_md5.txt diff --git a/core-java-modules/core-java-security-2/README.md b/core-java-modules/core-java-security-2/README.md index c250e24078..2eb21fb77e 100644 --- a/core-java-modules/core-java-security-2/README.md +++ b/core-java-modules/core-java-security-2/README.md @@ -1,3 +1,11 @@ +## Core Java Security + +This module contains articles about core Java Security + ### Relevant Articles: - [Guide To The Java Authentication And Authorization Service (JAAS)](https://www.baeldung.com/java-authentication-authorization-service) +- [MD5 Hashing in Java](http://www.baeldung.com/java-md5) +- [Hashing a Password in Java](https://www.baeldung.com/java-password-hashing) +- [SHA-256 and SHA3-256 Hashing in Java](https://www.baeldung.com/sha-256-hashing-java) +- More articles: [[<-- prev]](/core-java-modules/core-java-security) diff --git a/core-java-modules/core-java-security-2/pom.xml b/core-java-modules/core-java-security-2/pom.xml index 23f0c5aab9..9315ab4af2 100644 --- a/core-java-modules/core-java-security-2/pom.xml +++ b/core-java-modules/core-java-security-2/pom.xml @@ -16,4 +16,34 @@ ../../parent-java + + + commons-codec + commons-codec + ${commons-codec.version} + + + + org.bouncycastle + bcprov-jdk15on + ${bouncycastle.version} + + + + + org.assertj + assertj-core + ${assertj-core.version} + test + + + + + + 1.60 + 1.11 + + + 3.10.0 + diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/DigestAlgorithms.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/DigestAlgorithms.java new file mode 100644 index 0000000000..94dd22ff4b --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/DigestAlgorithms.java @@ -0,0 +1,9 @@ +package com.baeldung.hashing; + +public class DigestAlgorithms { + + public static final String SHA3_256 = "SHA3-256"; + public static final String SHA_256 = "SHA-256"; + public static final String KECCAK_256 = "Keccak-256"; + +} diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/Keccak256Hashing.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/Keccak256Hashing.java new file mode 100644 index 0000000000..19fc4cf059 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/Keccak256Hashing.java @@ -0,0 +1,30 @@ +package com.baeldung.hashing; + +import org.bouncycastle.jcajce.provider.digest.Keccak; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.encoders.Hex; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.Security; + +import static com.baeldung.hashing.DigestAlgorithms.KECCAK_256; +import static com.baeldung.hashing.SHACommonUtils.bytesToHex; + +public class Keccak256Hashing { + + public static String hashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException { + Security.addProvider(new BouncyCastleProvider()); + final MessageDigest digest = MessageDigest.getInstance(KECCAK_256); + final byte[] encodedhash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8)); + return bytesToHex(encodedhash); + } + + public static String hashWithBouncyCastle(final String originalString) { + Keccak.Digest256 digest256 = new Keccak.Digest256(); + byte[] hashbytes = digest256.digest(originalString.getBytes(StandardCharsets.UTF_8)); + return new String(Hex.encode(hashbytes)); + } + +} diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHA256Hashing.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHA256Hashing.java new file mode 100644 index 0000000000..ec008cebab --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHA256Hashing.java @@ -0,0 +1,39 @@ +package com.baeldung.hashing; + +import com.google.common.hash.Hashing; +import org.apache.commons.codec.digest.DigestUtils; +import org.bouncycastle.util.encoders.Hex; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import static com.baeldung.hashing.DigestAlgorithms.SHA_256; +import static com.baeldung.hashing.SHACommonUtils.bytesToHex; + +public class SHA256Hashing { + + public static String HashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException { + final MessageDigest digest = MessageDigest.getInstance(SHA_256); + final byte[] encodedhash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8)); + return bytesToHex(encodedhash); + } + + public static String hashWithGuava(final String originalString) { + final String sha256hex = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString(); + return sha256hex; + } + + public static String HashWithApacheCommons(final String originalString) { + final String sha256hex = DigestUtils.sha256Hex(originalString); + return sha256hex; + } + + public static String HashWithBouncyCastle(final String originalString) throws NoSuchAlgorithmException { + final MessageDigest digest = MessageDigest.getInstance(SHA_256); + final byte[] hash = digest.digest(originalString.getBytes(StandardCharsets.UTF_8)); + final String sha256hex = new String(Hex.encode(hash)); + return sha256hex; + } + +} diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHA3Hashing.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHA3Hashing.java new file mode 100644 index 0000000000..eb363205b1 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHA3Hashing.java @@ -0,0 +1,45 @@ +package com.baeldung.hashing; + +import com.google.common.hash.Hashing; +import org.apache.commons.codec.digest.DigestUtils; +import org.bouncycastle.crypto.digests.SHA3Digest; +import org.bouncycastle.jcajce.provider.digest.SHA3; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.util.encoders.Hex; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.Security; + +import static com.baeldung.hashing.DigestAlgorithms.SHA3_256; +import static com.baeldung.hashing.SHACommonUtils.bytesToHex; + +public class SHA3Hashing { + + /* works with JDK9+ only */ + public static String hashWithJavaMessageDigestJDK9(final String originalString) throws NoSuchAlgorithmException { + final MessageDigest digest = MessageDigest.getInstance(SHA3_256); + final byte[] hashbytes = digest.digest(originalString.getBytes(StandardCharsets.UTF_8)); + return bytesToHex(hashbytes); + } + + public static String hashWithJavaMessageDigest(final String originalString) throws NoSuchAlgorithmException { + Security.addProvider(new BouncyCastleProvider()); + final MessageDigest digest = MessageDigest.getInstance(SHA3_256); + final byte[] hashbytes = digest.digest(originalString.getBytes(StandardCharsets.UTF_8)); + return bytesToHex(hashbytes); + } + + /* works with JDK9+ only */ + public static String hashWithApacheCommonsJDK9(final String originalString) { + return new DigestUtils(SHA3_256).digestAsHex(originalString); + } + + public static String hashWithBouncyCastle(final String originalString) { + SHA3.Digest256 digest256 = new SHA3.Digest256(); + byte[] hashbytes = digest256.digest(originalString.getBytes(StandardCharsets.UTF_8)); + return new String(Hex.encode(hashbytes)); + } + +} diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHACommonUtils.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHACommonUtils.java new file mode 100644 index 0000000000..0f28408083 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/hashing/SHACommonUtils.java @@ -0,0 +1,16 @@ +package com.baeldung.hashing; + +class SHACommonUtils { + + public static String bytesToHex(byte[] hash) { + StringBuffer hexString = new StringBuffer(); + for (byte h : hash) { + String hex = Integer.toHexString(0xff & h); + if (hex.length() == 1) + hexString.append('0'); + hexString.append(hex); + } + return hexString.toString(); + } + +} diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java new file mode 100644 index 0000000000..e2259e4249 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/PBKDF2Hasher.java @@ -0,0 +1,149 @@ +package com.baeldung.passwordhashing; + +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import java.util.Arrays; +import java.util.Base64; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; + +/** + * Hash passwords for storage, and test passwords against password tokens. + * + * Instances of this class can be used concurrently by multiple threads. + * + * @author erickson + * @see StackOverflow + */ +public final class PBKDF2Hasher +{ + + /** + * Each token produced by this class uses this identifier as a prefix. + */ + public static final String ID = "$31$"; + + /** + * The minimum recommended cost, used by default + */ + public static final int DEFAULT_COST = 16; + + private static final String ALGORITHM = "PBKDF2WithHmacSHA1"; + + private static final int SIZE = 128; + + private static final Pattern layout = Pattern.compile("\\$31\\$(\\d\\d?)\\$(.{43})"); + + private final SecureRandom random; + + private final int cost; + + public PBKDF2Hasher() + { + this(DEFAULT_COST); + } + + /** + * Create a password manager with a specified cost + * + * @param cost the exponential computational cost of hashing a password, 0 to 30 + */ + public PBKDF2Hasher(int cost) + { + iterations(cost); /* Validate cost */ + this.cost = cost; + this.random = new SecureRandom(); + } + + private static int iterations(int cost) + { + if ((cost < 0) || (cost > 30)) + throw new IllegalArgumentException("cost: " + cost); + return 1 << cost; + } + + /** + * Hash a password for storage. + * + * @return a secure authentication token to be stored for later authentication + */ + public String hash(char[] password) + { + byte[] salt = new byte[SIZE / 8]; + random.nextBytes(salt); + byte[] dk = pbkdf2(password, salt, 1 << cost); + byte[] hash = new byte[salt.length + dk.length]; + System.arraycopy(salt, 0, hash, 0, salt.length); + System.arraycopy(dk, 0, hash, salt.length, dk.length); + Base64.Encoder enc = Base64.getUrlEncoder().withoutPadding(); + return ID + cost + '$' + enc.encodeToString(hash); + } + + /** + * Authenticate with a password and a stored password token. + * + * @return true if the password and token match + */ + public boolean checkPassword(char[] password, String token) + { + Matcher m = layout.matcher(token); + if (!m.matches()) + throw new IllegalArgumentException("Invalid token format"); + int iterations = iterations(Integer.parseInt(m.group(1))); + byte[] hash = Base64.getUrlDecoder().decode(m.group(2)); + byte[] salt = Arrays.copyOfRange(hash, 0, SIZE / 8); + byte[] check = pbkdf2(password, salt, iterations); + int zero = 0; + for (int idx = 0; idx < check.length; ++idx) + zero |= hash[salt.length + idx] ^ check[idx]; + return zero == 0; + } + + private static byte[] pbkdf2(char[] password, byte[] salt, int iterations) + { + KeySpec spec = new PBEKeySpec(password, salt, iterations, SIZE); + try { + SecretKeyFactory f = SecretKeyFactory.getInstance(ALGORITHM); + return f.generateSecret(spec).getEncoded(); + } + catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("Missing algorithm: " + ALGORITHM, ex); + } + catch (InvalidKeySpecException ex) { + throw new IllegalStateException("Invalid SecretKeyFactory", ex); + } + } + + /** + * Hash a password in an immutable {@code String}. + * + *

Passwords should be stored in a {@code char[]} so that it can be filled + * with zeros after use instead of lingering on the heap and elsewhere. + * + * @deprecated Use {@link #hash(char[])} instead + */ + @Deprecated + public String hash(String password) + { + return hash(password.toCharArray()); + } + + /** + * Authenticate with a password in an immutable {@code String} and a stored + * password token. + * + * @deprecated Use {@link #checkPassword(char[],String)} instead. + * @see #hash(String) + */ + @Deprecated + public boolean checkPassword(String password, String token) + { + return checkPassword(password.toCharArray(), token); + } + +} diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java new file mode 100644 index 0000000000..4f5337f963 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/SHA512Hasher.java @@ -0,0 +1,35 @@ +package com.baeldung.passwordhashing; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + + +/** A really simple SHA_512 Encryption example. + * + */ +public class SHA512Hasher { + + public String hash(String passwordToHash, byte[] salt){ + String generatedPassword = null; + try { + MessageDigest md = MessageDigest.getInstance("SHA-512"); + md.update(salt); + byte[] bytes = md.digest(passwordToHash.getBytes(StandardCharsets.UTF_8)); + StringBuilder sb = new StringBuilder(); + for(int i=0; i< bytes.length ;i++){ + sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); + } + generatedPassword = sb.toString(); + } + catch (NoSuchAlgorithmException e){ + e.printStackTrace(); + } + return generatedPassword; + } + + public boolean checkPassword(String hash, String attempt, byte[] salt){ + String generatedHash = hash(attempt, salt); + return hash.equals(generatedHash); + } +} diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java new file mode 100644 index 0000000000..36c9b65070 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/passwordhashing/SimplePBKDF2Hasher.java @@ -0,0 +1,18 @@ +package com.baeldung.passwordhashing; + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import java.security.spec.KeySpec; + +/** A really simple SimplePBKDF2 Encryption example. + * + */ +public class SimplePBKDF2Hasher { + + public static String hashSimple(String password, byte[] salt) throws Exception{ + KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128); + SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); + byte[] hash = f.generateSecret(spec).getEncoded(); + return String.valueOf(hash); + } +} diff --git a/core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java new file mode 100644 index 0000000000..9ed35c8834 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/Keccak256HashingUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.hashing; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class Keccak256HashingUnitTest { + + private static String originalValue = "abc123"; + private static String hashedValue = "719accc61a9cc126830e5906f9d672d06eab6f8597287095a2c55a8b775e7016"; + + @Test public void testHashWithJavaMessageDigest() throws Exception { + final String currentHashedValue = Keccak256Hashing.hashWithJavaMessageDigest(originalValue); + assertEquals(hashedValue, currentHashedValue); + } + + @Test public void testHashWithBouncyCastle() { + final String currentHashedValue = Keccak256Hashing.hashWithBouncyCastle(originalValue); + assertEquals(hashedValue, currentHashedValue); + } + +} diff --git a/core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java new file mode 100644 index 0000000000..6bc9ad2cc6 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/SHA256HashingUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.hashing; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class SHA256HashingUnitTest { + + private static String originalValue = "abc123"; + private static String hashedValue = "6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090"; + + @Test + public void testHashWithJavaMessageDigest() throws Exception { + final String currentHashedValue = SHA256Hashing.HashWithJavaMessageDigest(originalValue); + assertEquals(hashedValue, currentHashedValue); + } + + @Test + public void testHashWithGuava() throws Exception { + final String currentHashedValue = SHA256Hashing.hashWithGuava(originalValue); + assertEquals(hashedValue, currentHashedValue); + } + + @Test + public void testHashWithApacheCommans() throws Exception { + final String currentHashedValue = SHA256Hashing.HashWithApacheCommons(originalValue); + assertEquals(hashedValue, currentHashedValue); + } + + @Test + public void testHashWithBouncyCastle() throws Exception { + final String currentHashedValue = SHA256Hashing.HashWithBouncyCastle(originalValue); + assertEquals(hashedValue, currentHashedValue); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java new file mode 100644 index 0000000000..fffab96405 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/hashing/SHA3HashingUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.hashing; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class SHA3HashingUnitTest { + + private static String originalValue = "abc123"; + private static String hashedValue = "f58fa3df820114f56e1544354379820cff464c9c41cb3ca0ad0b0843c9bb67ee"; + + /* works with JDK9+ only */ + //@Test + public void testHashWithJavaMessageDigestJDK9() throws Exception { + final String currentHashedValue = SHA3Hashing.hashWithJavaMessageDigestJDK9(originalValue); + assertEquals(hashedValue, currentHashedValue); + } + + @Test + public void testHashWithJavaMessageDigest() throws Exception { + final String currentHashedValue = SHA3Hashing.hashWithJavaMessageDigest(originalValue); + assertEquals(hashedValue, currentHashedValue); + } + + /* works with JDK9+ only */ + //@Test + public void testHashWithApacheCommonsJDK9() { + final String currentHashedValue = SHA3Hashing.hashWithApacheCommonsJDK9(originalValue); + assertEquals(hashedValue, currentHashedValue); + } + + @Test + public void testHashWithBouncyCastle() { + final String currentHashedValue = SHA3Hashing.hashWithBouncyCastle(originalValue); + assertEquals(hashedValue, currentHashedValue); + } + +} diff --git a/core-java-modules/core-java-security-2/src/test/java/com/baeldung/java/md5/JavaMD5UnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/java/md5/JavaMD5UnitTest.java new file mode 100644 index 0000000000..67d6918c09 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/java/md5/JavaMD5UnitTest.java @@ -0,0 +1,75 @@ +package com.baeldung.java.md5; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import javax.xml.bind.DatatypeConverter; + +import org.apache.commons.codec.digest.DigestUtils; +import org.junit.Test; + +import com.google.common.hash.HashCode; +import com.google.common.hash.Hashing; + +public class JavaMD5UnitTest { + + String filename = "src/test/resources/test_md5.txt"; + String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; + + String hash = "35454B055CC325EA1AF2126E27707052"; + String password = "ILoveJava"; + + @Test + public void givenPassword_whenHashing_thenVerifying() throws NoSuchAlgorithmException { + String hash = "35454B055CC325EA1AF2126E27707052"; + String password = "ILoveJava"; + + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(password.getBytes()); + byte[] digest = md.digest(); + String myHash = DatatypeConverter.printHexBinary(digest).toUpperCase(); + + assertThat(myHash.equals(hash)).isTrue(); + } + + @Test + public void givenFile_generatingChecksum_thenVerifying() throws NoSuchAlgorithmException, IOException { + String filename = "src/test/resources/test_md5.txt"; + String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; + + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(Files.readAllBytes(Paths.get(filename))); + byte[] digest = md.digest(); + String myChecksum = DatatypeConverter.printHexBinary(digest).toUpperCase(); + + assertThat(myChecksum.equals(checksum)).isTrue(); + } + + @Test + public void givenPassword_whenHashingUsingCommons_thenVerifying() { + String hash = "35454B055CC325EA1AF2126E27707052"; + String password = "ILoveJava"; + + String md5Hex = DigestUtils.md5Hex(password).toUpperCase(); + + assertThat(md5Hex.equals(hash)).isTrue(); + } + + @Test + public void givenFile_whenChecksumUsingGuava_thenVerifying() throws IOException { + String filename = "src/test/resources/test_md5.txt"; + String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; + + HashCode hash = com.google.common.io.Files.hash(new File(filename), Hashing.md5()); + String myChecksum = hash.toString().toUpperCase(); + + assertThat(myChecksum.equals(checksum)).isTrue(); + } + +} diff --git a/core-java-modules/core-java-security-2/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java new file mode 100644 index 0000000000..8e90725c77 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/passwordhashing/PBKDF2HasherUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.passwordhashing; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + + +public class PBKDF2HasherUnitTest { + + private PBKDF2Hasher mPBKDF2Hasher; + + @Before + public void setUp() throws Exception { + mPBKDF2Hasher = new PBKDF2Hasher(); + } + + @Test + public void givenCorrectMessageAndHash_whenAuthenticated_checkAuthenticationSucceeds() throws Exception { + String message1 = "password123"; + + String hash1 = mPBKDF2Hasher.hash(message1.toCharArray()); + + assertTrue(mPBKDF2Hasher.checkPassword(message1.toCharArray(), hash1)); + + } + + @Test + public void givenWrongMessage_whenAuthenticated_checkAuthenticationFails() throws Exception { + String message1 = "password123"; + + String hash1 = mPBKDF2Hasher.hash(message1.toCharArray()); + + String wrongPasswordAttempt = "IamWrong"; + + assertFalse(mPBKDF2Hasher.checkPassword(wrongPasswordAttempt.toCharArray(), hash1)); + + } + + +} \ No newline at end of file diff --git a/core-java-modules/core-java-security-2/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java new file mode 100644 index 0000000000..3acfb0ba9d --- /dev/null +++ b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/passwordhashing/SHA512HasherUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.passwordhashing; + +import org.junit.Before; +import org.junit.Test; + +import java.security.SecureRandom; + +import static org.junit.Assert.*; + +/** + * Created by PhysicsSam on 06-Sep-18. + */ +public class SHA512HasherUnitTest { + + private SHA512Hasher hasher; + private SecureRandom secureRandom; + + @Before + public void setUp() throws Exception { + hasher = new SHA512Hasher(); + secureRandom = new SecureRandom(); + } + + @Test + public void givenSamePasswordAndSalt_whenHashed_checkResultingHashesAreEqual() throws Exception { + + byte[] salt = new byte[16]; + secureRandom.nextBytes(salt); + + String hash1 = hasher.hash("password", salt); + String hash2 = hasher.hash("password", salt); + + assertEquals(hash1, hash2); + + } + + @Test + public void givenSamePasswordAndDifferentSalt_whenHashed_checkResultingHashesNotEqual() throws Exception { + + byte[] salt = new byte[16]; + secureRandom.nextBytes(salt); + String hash1 = hasher.hash("password", salt); + //generate a second salt + byte[] secondSalt = new byte[16]; + String hash2 = hasher.hash("password", secondSalt); + + assertNotEquals(hash1, hash2); + + } + + @Test + public void givenPredefinedHash_whenCorrectAttemptGiven_checkAuthenticationSucceeds() throws Exception { + byte[] salt = new byte[16]; + secureRandom.nextBytes(salt); + + String originalHash = hasher.hash("password123", salt); + + assertTrue(hasher.checkPassword(originalHash, "password123", salt)); + } + + @Test + public void givenPredefinedHash_whenIncorrectAttemptGiven_checkAuthenticationFails() throws Exception { + byte[] salt = new byte[16]; + secureRandom.nextBytes(salt); + + String originalHash = hasher.hash("password123", salt); + + assertFalse(hasher.checkPassword(originalHash, "password124", salt)); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-security-2/src/test/resources/test_md5.txt b/core-java-modules/core-java-security-2/src/test/resources/test_md5.txt new file mode 100644 index 0000000000..95d09f2b10 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/test/resources/test_md5.txt @@ -0,0 +1 @@ +hello world \ No newline at end of file From 4382852a1731d9d06f838219ec176ddf89c04d3d Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Sun, 29 Mar 2020 19:00:40 +0200 Subject: [PATCH 30/59] JAVA-43: Upgrade spring-security-modules to Spring Boot 2 --- spring-security-modules/spring-security-acl/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-security-modules/spring-security-acl/pom.xml b/spring-security-modules/spring-security-acl/pom.xml index 3c613f9d92..5c04aaa9ca 100644 --- a/spring-security-modules/spring-security-acl/pom.xml +++ b/spring-security-modules/spring-security-acl/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 From 35bbf9c8845c7c6091afdefb5fb49e8f54035f1c Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Mon, 30 Mar 2020 01:29:02 +0430 Subject: [PATCH 31/59] Borrowing one Example from JCIP --- .../volatilekeyword/TaskRunner.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/volatilekeyword/TaskRunner.java diff --git a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/volatilekeyword/TaskRunner.java b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/volatilekeyword/TaskRunner.java new file mode 100644 index 0000000000..f0493d4911 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/volatilekeyword/TaskRunner.java @@ -0,0 +1,25 @@ +package com.baeldung.concurrent.volatilekeyword; + +public class TaskRunner { + + private static int number; + private volatile static boolean ready; + + private static class Reader extends Thread { + + @Override + public void run() { + while (!ready) { + Thread.yield(); + } + + System.out.println(number); + } + } + + public static void main(String[] args) { + new Reader().start(); + number = 42; + ready = true; + } +} From ee95317ad9dd8af56a885bcac40b9b11d04dca56 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Sun, 29 Mar 2020 23:54:31 +0200 Subject: [PATCH 32/59] JAVA-42: Upgrade spring-security-ldap to Spring Boot 2 --- .../spring-security-ldap/pom.xml | 8 +++++-- .../com/baeldung/SampleLDAPApplication.java | 13 +----------- .../{security => config}/SecurityConfig.java | 21 +++++++++++++++---- .../java/com/baeldung/config/WebConfig.java | 16 ++++++++++++++ .../src/main/resources/application.properties | 1 + .../src/main/resources/webSecurityConfig.xml | 1 + 6 files changed, 42 insertions(+), 18 deletions(-) rename spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/{security => config}/SecurityConfig.java (53%) create mode 100644 spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/WebConfig.java create mode 100644 spring-security-modules/spring-security-ldap/src/main/resources/application.properties diff --git a/spring-security-modules/spring-security-ldap/pom.xml b/spring-security-modules/spring-security-ldap/pom.xml index f5e8856648..baed682186 100644 --- a/spring-security-modules/spring-security-ldap/pom.xml +++ b/spring-security-modules/spring-security-ldap/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -21,6 +21,10 @@ org.springframework.boot spring-boot-starter-security + + org.springframework.boot + spring-boot-starter-web + org.springframework.boot spring-boot-starter-thymeleaf diff --git a/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/SampleLDAPApplication.java b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/SampleLDAPApplication.java index ec585f2387..2d619cccfa 100644 --- a/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/SampleLDAPApplication.java +++ b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/SampleLDAPApplication.java @@ -2,7 +2,7 @@ package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @@ -19,15 +19,4 @@ public class SampleLDAPApplication extends SpringBootServletInitializer { SpringApplication.run(SampleLDAPApplication.class, args); } - @Bean - public WebMvcConfigurerAdapter adapter() { - return new WebMvcConfigurerAdapter() { - @Override - public void addViewControllers(ViewControllerRegistry registry) { - registry.addViewController("/login") - .setViewName("login"); - } - }; - } - } \ No newline at end of file diff --git a/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/security/SecurityConfig.java b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/SecurityConfig.java similarity index 53% rename from spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/security/SecurityConfig.java rename to spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/SecurityConfig.java index a00cb02459..69f90d9de9 100644 --- a/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/security/SecurityConfig.java +++ b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/SecurityConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.security; +package com.baeldung.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; @@ -14,13 +14,26 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.ldapAuthentication().userSearchBase("ou=people").userSearchFilter("(uid={0})").groupSearchBase("ou=groups").groupSearchFilter("(member={0})").contextSource().root("dc=baeldung,dc=com").ldif("classpath:users.ldif"); + auth.ldapAuthentication() + .userSearchBase("ou=people") + .userSearchFilter("(uid={0})") + .groupSearchBase("ou=groups") + .groupSearchFilter("(member={0})") + .contextSource() + .root("dc=baeldung,dc=com") + .ldif("classpath:users.ldif"); } @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests().antMatchers("/", "/home").permitAll().anyRequest().authenticated(); - http.formLogin().loginPage("/login").permitAll().and().logout().logoutSuccessUrl("/"); + http + .authorizeRequests() + .antMatchers("/", "/home", "/css/**") + .permitAll() + .anyRequest() + .authenticated() + .and().formLogin().loginPage("/login").permitAll() + .and().logout().logoutSuccessUrl("/"); } } diff --git a/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/WebConfig.java b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/WebConfig.java new file mode 100644 index 0000000000..9809be1844 --- /dev/null +++ b/spring-security-modules/spring-security-ldap/src/main/java/com/baeldung/config/WebConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebConfig implements WebMvcConfigurer { + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/login") + .setViewName("login"); + } +} diff --git a/spring-security-modules/spring-security-ldap/src/main/resources/application.properties b/spring-security-modules/spring-security-ldap/src/main/resources/application.properties new file mode 100644 index 0000000000..3d0221bb7b --- /dev/null +++ b/spring-security-modules/spring-security-ldap/src/main/resources/application.properties @@ -0,0 +1 @@ +management.health.ldap.enabled=false \ No newline at end of file diff --git a/spring-security-modules/spring-security-ldap/src/main/resources/webSecurityConfig.xml b/spring-security-modules/spring-security-ldap/src/main/resources/webSecurityConfig.xml index c13f65de5e..adfd603e54 100644 --- a/spring-security-modules/spring-security-ldap/src/main/resources/webSecurityConfig.xml +++ b/spring-security-modules/spring-security-ldap/src/main/resources/webSecurityConfig.xml @@ -10,6 +10,7 @@ + From 0628c8dd423c2c46932b474b5f2d0d51e6b26369 Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Mon, 30 Mar 2020 17:55:33 +0430 Subject: [PATCH 33/59] Introducing nullsFirst and nullsLast --- .../com/baeldung/java8/Java8SortUnitTest.java | 63 ++++++++++++++++--- 1 file changed, 53 insertions(+), 10 deletions(-) diff --git a/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/Java8SortUnitTest.java b/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/Java8SortUnitTest.java index 57d9d8347b..9e510575fc 100644 --- a/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/Java8SortUnitTest.java +++ b/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/Java8SortUnitTest.java @@ -1,18 +1,17 @@ package com.baeldung.java8; -import static org.hamcrest.Matchers.equalTo; +import com.baeldung.java8.entity.Human; +import com.google.common.collect.Lists; +import com.google.common.primitives.Ints; +import org.junit.Assert; +import org.junit.Test; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; -import org.junit.Assert; -import org.junit.Test; - -import com.baeldung.java8.entity.Human; -import com.google.common.collect.Lists; -import com.google.common.primitives.Ints; +import static org.hamcrest.Matchers.equalTo; public class Java8SortUnitTest { @@ -113,11 +112,11 @@ public class Java8SortUnitTest { humans.sort(Comparator.comparing(Human::getName)); Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12))); } - + @Test public final void givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { final List letters = Lists.newArrayList("B", "A", "C"); - + final List sortedLetters = letters.stream().sorted().collect(Collectors.toList()); Assert.assertThat(sortedLetters.get(0), equalTo("A")); } @@ -126,7 +125,7 @@ public class Java8SortUnitTest { public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() { final List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12)); final Comparator nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName()); - + final List sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList()); Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12))); } @@ -164,4 +163,48 @@ public class Java8SortUnitTest { Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10))); } + @Test(expected = NullPointerException.class) + public final void givenANullElement_whenSortingEntitiesByName_thenThrowsNPE() { + final List humans = Lists.newArrayList(null, new Human("Jack", 12)); + + humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName())); + } + + @Test + public final void givenANullElement_whenSortingEntitiesByNameManually_thenMovesTheNullToLast() { + final List humans = Lists.newArrayList(null, new Human("Jack", 12), null); + + humans.sort((h1, h2) -> { + if (h1 == null) return h2 == null ? 0 : 1; + else if (h2 == null) return -1; + + return h1.getName().compareTo(h2.getName()); + }); + + Assert.assertNotNull(humans.get(0)); + Assert.assertNull(humans.get(1)); + Assert.assertNull(humans.get(2)); + } + + @Test + public final void givenANullElement_whenSortingEntitiesByName_thenMovesTheNullToLast() { + final List humans = Lists.newArrayList(null, new Human("Jack", 12), null); + + humans.sort(Comparator.nullsLast(Comparator.comparing(Human::getName))); + + Assert.assertNotNull(humans.get(0)); + Assert.assertNull(humans.get(1)); + Assert.assertNull(humans.get(2)); + } + + @Test + public final void givenANullElement_whenSortingEntitiesByName_thenMovesTheNullToStart() { + final List humans = Lists.newArrayList(null, new Human("Jack", 12), null); + + humans.sort(Comparator.nullsFirst(Comparator.comparing(Human::getName))); + + Assert.assertNull(humans.get(0)); + Assert.assertNull(humans.get(1)); + Assert.assertNotNull(humans.get(2)); + } } From 3f83ed67d3511a057bbf5b0db8e56f214ffd88a7 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Mon, 30 Mar 2020 23:27:11 +0200 Subject: [PATCH 34/59] JAVA-42: Upgrade spring-security-kerberos to Spring Boot 2 --- spring-security-modules/spring-security-kerberos/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-security-modules/spring-security-kerberos/pom.xml b/spring-security-modules/spring-security-kerberos/pom.xml index 6846bdf063..51a48a78c6 100644 --- a/spring-security-modules/spring-security-kerberos/pom.xml +++ b/spring-security-modules/spring-security-kerberos/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 From 3f2d436db4e93cf57428c75758376b8e2d17b3c2 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Mon, 30 Mar 2020 23:45:37 +0200 Subject: [PATCH 35/59] JAVA-42: Upgrade spring-security-cache-control to Spring Boot 2 --- .../spring-security-cache-control/pom.xml | 38 +++---------------- .../ResourceEndpointIntegrationTest.java | 2 +- 2 files changed, 7 insertions(+), 33 deletions(-) diff --git a/spring-security-modules/spring-security-cache-control/pom.xml b/spring-security-modules/spring-security-cache-control/pom.xml index acc37b41ef..743b3c291d 100644 --- a/spring-security-modules/spring-security-cache-control/pom.xml +++ b/spring-security-modules/spring-security-cache-control/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -23,41 +23,15 @@ spring-boot-starter-web - org.springframework.security - spring-security-core - - - org.springframework.security - spring-security-config - - - org.springframework.security - spring-security-web - - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} + org.springframework.boot + spring-boot-starter-security - org.hamcrest - hamcrest - ${hamcrest.version} + org.springframework.boot + spring-boot-starter-test test - - - org.mockito - mockito-core - test - - - - org.springframework - spring-test - - \ No newline at end of file diff --git a/spring-security-modules/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointIntegrationTest.java b/spring-security-modules/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointIntegrationTest.java index d6a1a97773..d4d24a4986 100644 --- a/spring-security-modules/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointIntegrationTest.java +++ b/spring-security-modules/spring-security-cache-control/src/test/java/com/baeldung/cachecontrol/ResourceEndpointIntegrationTest.java @@ -4,8 +4,8 @@ import static io.restassured.RestAssured.given; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringRunner; import io.restassured.http.ContentType; From a0478a7832e003ac3748ae5b574504b12e64dc1a Mon Sep 17 00:00:00 2001 From: ramkumarvenkat Date: Tue, 31 Mar 2020 12:09:13 +0530 Subject: [PATCH 36/59] Fix code after article changes --- .../com/baeldung/guava/entity/Profile.java | 20 ++++++++ .../com/baeldung/guava/entity/Session.java | 13 ++++++ .../java/com/baeldung/guava/entity/User.java | 20 ++++++++ .../guava/mapmaker/GuavaMapMakerUnitTest.java | 46 +++++++++++++------ 4 files changed, 84 insertions(+), 15 deletions(-) create mode 100644 guava-collections-map/src/main/java/com/baeldung/guava/entity/Profile.java create mode 100644 guava-collections-map/src/main/java/com/baeldung/guava/entity/Session.java create mode 100644 guava-collections-map/src/main/java/com/baeldung/guava/entity/User.java diff --git a/guava-collections-map/src/main/java/com/baeldung/guava/entity/Profile.java b/guava-collections-map/src/main/java/com/baeldung/guava/entity/Profile.java new file mode 100644 index 0000000000..17a6502f39 --- /dev/null +++ b/guava-collections-map/src/main/java/com/baeldung/guava/entity/Profile.java @@ -0,0 +1,20 @@ +package com.baeldung.guava.entity; + +public class Profile { + private long id; + private String type; + + public Profile(long id, String type) { + this.id = id; + this.type = type; + } + + public long getId() { + return id; + } + + public String getName() { + return type; + } + +} diff --git a/guava-collections-map/src/main/java/com/baeldung/guava/entity/Session.java b/guava-collections-map/src/main/java/com/baeldung/guava/entity/Session.java new file mode 100644 index 0000000000..b834c23df1 --- /dev/null +++ b/guava-collections-map/src/main/java/com/baeldung/guava/entity/Session.java @@ -0,0 +1,13 @@ +package com.baeldung.guava.entity; + +public class Session { + private long id; + + public Session(long id) { + this.id = id; + } + + public long getId() { + return id; + } +} diff --git a/guava-collections-map/src/main/java/com/baeldung/guava/entity/User.java b/guava-collections-map/src/main/java/com/baeldung/guava/entity/User.java new file mode 100644 index 0000000000..613045ec23 --- /dev/null +++ b/guava-collections-map/src/main/java/com/baeldung/guava/entity/User.java @@ -0,0 +1,20 @@ +package com.baeldung.guava.entity; + +public class User { + private long id; + private String name; + + public User(long id, String name) { + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public String getName() { + return name; + } + +} diff --git a/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java b/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java index 8da459f22e..e2bc1349c6 100644 --- a/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java +++ b/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java @@ -1,40 +1,56 @@ package com.baeldung.guava.mapmaker; +import com.baeldung.guava.entity.Profile; +import com.baeldung.guava.entity.Session; +import com.baeldung.guava.entity.User; import com.google.common.collect.MapMaker; +import org.junit.Assert; import org.junit.Test; import java.util.concurrent.ConcurrentMap; +import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertNotNull; public class GuavaMapMakerUnitTest { @Test - public void whenMakeMap_thenCreated() { - ConcurrentMap concurrentMap = new MapMaker().makeMap(); - assertNotNull(concurrentMap); + public void whenCreateCaches_thenCreated() { + ConcurrentMap sessionCache = new MapMaker().makeMap(); + assertNotNull(sessionCache); + + ConcurrentMap profileCache = new MapMaker().makeMap(); + assertNotNull(profileCache); + + User userA = new User(1, "UserA"); + + sessionCache.put(userA, new Session(100)); + Assert.assertThat(sessionCache.size(), equalTo(1)); + + profileCache.put(userA, new Profile(1000, "Personal")); + Assert.assertThat(profileCache.size(), equalTo(1)); } @Test - public void whenMakeMapWithWeakKeys_thenCreated() { - ConcurrentMap concurrentMap = new MapMaker().weakKeys().makeMap(); - assertNotNull(concurrentMap); + public void whenCreateCacheWithInitialCapacity_thenCreated() { + ConcurrentMap profileCache = new MapMaker().initialCapacity(100).makeMap(); + assertNotNull(profileCache); } @Test - public void whenMakeMapWithWeakValues_thenCreated() { - ConcurrentMap concurrentMap = new MapMaker().weakValues().makeMap(); - assertNotNull(concurrentMap); + public void whenCreateCacheWithConcurrencyLevel_thenCreated() { + ConcurrentMap sessionCache = new MapMaker().concurrencyLevel(10).makeMap(); + assertNotNull(sessionCache); } @Test - public void whenMakeMapWithInitialCapacity_thenCreated() { - ConcurrentMap concurrentMap = new MapMaker().initialCapacity(10).makeMap(); - assertNotNull(concurrentMap); + public void whenCreateCacheWithWeakKeys_thenCreated() { + ConcurrentMap sessionCache = new MapMaker().weakKeys().makeMap(); + assertNotNull(sessionCache); } @Test - public void whenMakeMapWithConcurrencyLevel_thenCreated() { - ConcurrentMap concurrentMap = new MapMaker().concurrencyLevel(10).makeMap(); - assertNotNull(concurrentMap); + public void whenCreateCacheWithWeakValues_thenCreated() { + ConcurrentMap profileCache = new MapMaker().weakValues().makeMap(); + assertNotNull(profileCache); } } From d1b40a0c026a07b5780e85bd8170f3a397967189 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Tue, 31 Mar 2020 22:55:19 +0200 Subject: [PATCH 37/59] JAVA-42: Upgrade spring-security-x509 to Spring Boot 2 --- spring-security-modules/spring-security-x509/pom.xml | 4 ++-- .../src/main/resources/application.properties | 6 +++--- .../src/main/resources/application.properties | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/spring-security-modules/spring-security-x509/pom.xml b/spring-security-modules/spring-security-x509/pom.xml index a4ff908eed..d4132f058d 100644 --- a/spring-security-modules/spring-security-x509/pom.xml +++ b/spring-security-modules/spring-security-x509/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-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/application.properties b/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/application.properties index f293d6712d..53dfe9976a 100644 --- a/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/application.properties +++ b/spring-security-modules/spring-security-x509/spring-security-x509-basic-auth/src/main/resources/application.properties @@ -1,8 +1,8 @@ -server.ssl.key-store=../keystore/keystore.jks +server.ssl.key-store=keystore/keystore.jks server.ssl.key-store-password=changeit server.ssl.key-alias=localhost server.ssl.key-password=changeit server.ssl.enabled=true server.port=8443 -security.user.name=Admin -security.user.password=admin \ No newline at end of file +spring.security.user.name=Admin +spring.security.user.password=admin \ No newline at end of file diff --git a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/resources/application.properties b/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/resources/application.properties index 174eba9f98..743c9c4582 100644 --- a/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/resources/application.properties +++ b/spring-security-modules/spring-security-x509/spring-security-x509-client-auth/src/main/resources/application.properties @@ -4,8 +4,8 @@ server.ssl.key-alias=localhost server.ssl.key-password=changeit server.ssl.enabled=true server.port=8443 -security.user.name=Admin -security.user.password=admin +spring.security.user.name=Admin +spring.security.user.password=admin server.ssl.trust-store=../keystore/truststore.jks server.ssl.trust-store-password=changeit server.ssl.client-auth=need \ No newline at end of file From 3d6c7359fa3522e9985d2126509238624a667e04 Mon Sep 17 00:00:00 2001 From: Krzysztof Woyke Date: Wed, 1 Apr 2020 14:35:03 +0200 Subject: [PATCH 38/59] JAVA-995: Upgrade Spring Boot to the latest 2.2.6 version --- parent-boot-2/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index 6e9e90a6d3..c7bb11b1d5 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -81,7 +81,7 @@ 3.3.0 1.0.22.RELEASE - 2.2.2.RELEASE + 2.2.6.RELEASE From 37ed8f63271c225427a172d8b95224f5be09f626 Mon Sep 17 00:00:00 2001 From: Waldemar Date: Wed, 1 Apr 2020 20:29:34 +0200 Subject: [PATCH 39/59] BAEL-2398 rename package --- coroutines-java/pom.xml | 4 ++-- .../main/java/com/baeldung/{introduction => quasar}/App.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) rename coroutines-java/src/main/java/com/baeldung/{introduction => quasar}/App.java (86%) diff --git a/coroutines-java/pom.xml b/coroutines-java/pom.xml index 3546aa5673..caee769a78 100644 --- a/coroutines-java/pom.xml +++ b/coroutines-java/pom.xml @@ -53,7 +53,7 @@ exec-maven-plugin 1.6.0 - com.baeldung.introduction.App + com.baeldung.quasar.App target/classes java @@ -68,7 +68,7 @@ - com.baeldung.introduction.App + com.baeldung.quasar.App diff --git a/coroutines-java/src/main/java/com/baeldung/introduction/App.java b/coroutines-java/src/main/java/com/baeldung/quasar/App.java similarity index 86% rename from coroutines-java/src/main/java/com/baeldung/introduction/App.java rename to coroutines-java/src/main/java/com/baeldung/quasar/App.java index f915464973..510877d1be 100644 --- a/coroutines-java/src/main/java/com/baeldung/introduction/App.java +++ b/coroutines-java/src/main/java/com/baeldung/quasar/App.java @@ -1,4 +1,4 @@ -package com.baeldung.introduction; +package com.baeldung.quasar; import co.paralleluniverse.fibers.Fiber; From 7187cb0dfbd3487877248742309519bed0f55d49 Mon Sep 17 00:00:00 2001 From: ramkumarvenkat Date: Thu, 2 Apr 2020 07:13:19 +0530 Subject: [PATCH 40/59] Change package name --- .../java/com/baeldung/guava/{entity => mapmaker}/Profile.java | 2 +- .../java/com/baeldung/guava/{entity => mapmaker}/Session.java | 2 +- .../java/com/baeldung/guava/{entity => mapmaker}/User.java | 2 +- .../com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java | 3 --- 4 files changed, 3 insertions(+), 6 deletions(-) rename guava-collections-map/src/main/java/com/baeldung/guava/{entity => mapmaker}/Profile.java (88%) rename guava-collections-map/src/main/java/com/baeldung/guava/{entity => mapmaker}/Session.java (81%) rename guava-collections-map/src/main/java/com/baeldung/guava/{entity => mapmaker}/User.java (88%) diff --git a/guava-collections-map/src/main/java/com/baeldung/guava/entity/Profile.java b/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Profile.java similarity index 88% rename from guava-collections-map/src/main/java/com/baeldung/guava/entity/Profile.java rename to guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Profile.java index 17a6502f39..165c5a9f8f 100644 --- a/guava-collections-map/src/main/java/com/baeldung/guava/entity/Profile.java +++ b/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Profile.java @@ -1,4 +1,4 @@ -package com.baeldung.guava.entity; +package com.baeldung.guava.mapmaker; public class Profile { private long id; diff --git a/guava-collections-map/src/main/java/com/baeldung/guava/entity/Session.java b/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Session.java similarity index 81% rename from guava-collections-map/src/main/java/com/baeldung/guava/entity/Session.java rename to guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Session.java index b834c23df1..a614f431f8 100644 --- a/guava-collections-map/src/main/java/com/baeldung/guava/entity/Session.java +++ b/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Session.java @@ -1,4 +1,4 @@ -package com.baeldung.guava.entity; +package com.baeldung.guava.mapmaker; public class Session { private long id; diff --git a/guava-collections-map/src/main/java/com/baeldung/guava/entity/User.java b/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/User.java similarity index 88% rename from guava-collections-map/src/main/java/com/baeldung/guava/entity/User.java rename to guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/User.java index 613045ec23..a7f0435049 100644 --- a/guava-collections-map/src/main/java/com/baeldung/guava/entity/User.java +++ b/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/User.java @@ -1,4 +1,4 @@ -package com.baeldung.guava.entity; +package com.baeldung.guava.mapmaker; public class User { private long id; diff --git a/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java b/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java index e2bc1349c6..754e3ac099 100644 --- a/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java +++ b/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java @@ -1,8 +1,5 @@ package com.baeldung.guava.mapmaker; -import com.baeldung.guava.entity.Profile; -import com.baeldung.guava.entity.Session; -import com.baeldung.guava.entity.User; import com.google.common.collect.MapMaker; import org.junit.Assert; import org.junit.Test; From 509423ba5714718292b4b08782afe7f73dbcd80f Mon Sep 17 00:00:00 2001 From: Krzysztof Woyke Date: Thu, 2 Apr 2020 16:10:53 +0200 Subject: [PATCH 41/59] JAVA-997: Upgrade Spring Core & Security to the latest versions --- parent-spring-5/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/parent-spring-5/pom.xml b/parent-spring-5/pom.xml index 27f355bfad..c75655ebc8 100644 --- a/parent-spring-5/pom.xml +++ b/parent-spring-5/pom.xml @@ -31,8 +31,8 @@ - 5.2.2.RELEASE - 5.2.1.RELEASE + 5.2.5.RELEASE + 5.2.3.RELEASE \ No newline at end of file From 55d1d12216712635a005ab6d7629ebeb2fc97f40 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sat, 4 Apr 2020 12:55:27 +0530 Subject: [PATCH 42/59] JAVA-624: Updated READMEs for prev links --- java-collections-maps-2/README.md | 2 +- java-collections-maps-3/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/java-collections-maps-2/README.md b/java-collections-maps-2/README.md index 71c6a3f32b..2188960543 100644 --- a/java-collections-maps-2/README.md +++ b/java-collections-maps-2/README.md @@ -13,4 +13,4 @@ This module contains articles about Map data structures in Java. - [Sort a HashMap in Java](https://www.baeldung.com/java-hashmap-sort) - [Finding the Highest Value in a Java Map](https://www.baeldung.com/java-find-map-max) - [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) -- More articles: [[<-- prev>]](/java-collections-maps) [[next -->]](/java-collections-maps-3) +- More articles: [[<-- prev]](/java-collections-maps) [[next -->]](/java-collections-maps-3) diff --git a/java-collections-maps-3/README.md b/java-collections-maps-3/README.md index 8f185f6ad4..886461a35c 100644 --- a/java-collections-maps-3/README.md +++ b/java-collections-maps-3/README.md @@ -5,4 +5,4 @@ This module contains articles about Map data structures in Java. ### Relevant Articles: - [Java TreeMap vs HashMap](https://www.baeldung.com/java-treemap-vs-hashmap) - [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps) -- More articles: [[<-- prev>]](/java-collections-maps-2) +- More articles: [[<-- prev]](/java-collections-maps-2) From ffc854e2f0d92d531aae9d576c387bfb3ee078d5 Mon Sep 17 00:00:00 2001 From: Waldemar Date: Sat, 4 Apr 2020 11:38:24 +0200 Subject: [PATCH 43/59] BAEL-2398: add libraries-concurrency module --- libraries-concurrency/pom.xml | 15 +++++++++++++++ pom.xml | 1 + 2 files changed, 16 insertions(+) create mode 100644 libraries-concurrency/pom.xml diff --git a/libraries-concurrency/pom.xml b/libraries-concurrency/pom.xml new file mode 100644 index 0000000000..0dc546e63a --- /dev/null +++ b/libraries-concurrency/pom.xml @@ -0,0 +1,15 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + libraries-concurrency + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index a295439951..9694941645 100644 --- a/pom.xml +++ b/pom.xml @@ -1259,6 +1259,7 @@ wildfly xml xstream + libraries-concurrency From 0cb40ad2665b4ed854938cc57d126a73ba6b4a1a Mon Sep 17 00:00:00 2001 From: Waldemar Date: Sat, 4 Apr 2020 11:48:18 +0200 Subject: [PATCH 44/59] BAEL-2398: move coroutines-java module into libraries-concurrency module --- .../coroutines-java}/pom.xml | 15 +++++---------- .../src/main/java/com/baeldung/quasar/App.java | 0 libraries-concurrency/pom.xml | 11 ++++++++--- 3 files changed, 13 insertions(+), 13 deletions(-) rename {coroutines-java => libraries-concurrency/coroutines-java}/pom.xml (89%) rename {coroutines-java => libraries-concurrency/coroutines-java}/src/main/java/com/baeldung/quasar/App.java (100%) diff --git a/coroutines-java/pom.xml b/libraries-concurrency/coroutines-java/pom.xml similarity index 89% rename from coroutines-java/pom.xml rename to libraries-concurrency/coroutines-java/pom.xml index caee769a78..72356738d4 100644 --- a/coroutines-java/pom.xml +++ b/libraries-concurrency/coroutines-java/pom.xml @@ -2,19 +2,14 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - - com.baeldung coroutines-java - 1.0-SNAPSHOT - coroutines-java - http://baeldung.com - - UTF-8 - 1.8 - 1.8 - + + com.baeldung + libraries-concurrency + 1.0.0-SNAPSHOT + diff --git a/coroutines-java/src/main/java/com/baeldung/quasar/App.java b/libraries-concurrency/coroutines-java/src/main/java/com/baeldung/quasar/App.java similarity index 100% rename from coroutines-java/src/main/java/com/baeldung/quasar/App.java rename to libraries-concurrency/coroutines-java/src/main/java/com/baeldung/quasar/App.java diff --git a/libraries-concurrency/pom.xml b/libraries-concurrency/pom.xml index 0dc546e63a..5ba722ae2e 100644 --- a/libraries-concurrency/pom.xml +++ b/libraries-concurrency/pom.xml @@ -2,14 +2,19 @@ + 4.0.0 + libraries-concurrency + libraries-concurrency + pom + parent-modules com.baeldung 1.0.0-SNAPSHOT - 4.0.0 - - libraries-concurrency + + coroutines-java + \ No newline at end of file From 585ed13442a50a8471d5df66d831d4b069e27c2a Mon Sep 17 00:00:00 2001 From: Waldemar Date: Sat, 4 Apr 2020 11:50:20 +0200 Subject: [PATCH 45/59] BAEL-2398: rename coroutines-java to coroutines-with-quasar --- .../{coroutines-java => coroutines-with-quasar}/pom.xml | 4 ++-- .../src/main/java/com/baeldung/quasar/App.java | 0 libraries-concurrency/pom.xml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) rename libraries-concurrency/{coroutines-java => coroutines-with-quasar}/pom.xml (97%) rename libraries-concurrency/{coroutines-java => coroutines-with-quasar}/src/main/java/com/baeldung/quasar/App.java (100%) diff --git a/libraries-concurrency/coroutines-java/pom.xml b/libraries-concurrency/coroutines-with-quasar/pom.xml similarity index 97% rename from libraries-concurrency/coroutines-java/pom.xml rename to libraries-concurrency/coroutines-with-quasar/pom.xml index 72356738d4..59241272e7 100644 --- a/libraries-concurrency/coroutines-java/pom.xml +++ b/libraries-concurrency/coroutines-with-quasar/pom.xml @@ -2,8 +2,8 @@ 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 - coroutines-java - coroutines-java + coroutines-with-quasar + coroutines-with-quasar com.baeldung diff --git a/libraries-concurrency/coroutines-java/src/main/java/com/baeldung/quasar/App.java b/libraries-concurrency/coroutines-with-quasar/src/main/java/com/baeldung/quasar/App.java similarity index 100% rename from libraries-concurrency/coroutines-java/src/main/java/com/baeldung/quasar/App.java rename to libraries-concurrency/coroutines-with-quasar/src/main/java/com/baeldung/quasar/App.java diff --git a/libraries-concurrency/pom.xml b/libraries-concurrency/pom.xml index 5ba722ae2e..7ae834025f 100644 --- a/libraries-concurrency/pom.xml +++ b/libraries-concurrency/pom.xml @@ -14,7 +14,7 @@ - coroutines-java + coroutines-with-quasar \ No newline at end of file From 1acadab18b1fec5fe1422faf7c01d6b4c5b45ffd Mon Sep 17 00:00:00 2001 From: Fabricio Pautasso Date: Sat, 4 Apr 2020 11:55:13 -0300 Subject: [PATCH 46/59] BAEL-3918 - Adding BigDecimal numbers using the Stream API (#8900) * BAEL-3918 - Adding BigDecimal numbers using the Stream API * BAEL-3918 - Adding BigDecimal numbers using the Stream API * BAEL-3918 - Adding BigDecimal numbers using the Stream API * BAEL-3918 - Updating test methods names to be compliant with Baeldung standards * Minor name change Co-authored-by: ashleyfrieze --- .../bigdecimals/AddNumbersUnitTest.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/bigdecimals/AddNumbersUnitTest.java diff --git a/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/bigdecimals/AddNumbersUnitTest.java b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/bigdecimals/AddNumbersUnitTest.java new file mode 100644 index 0000000000..9399908b30 --- /dev/null +++ b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/bigdecimals/AddNumbersUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.streams.bigdecimals; + +import static org.junit.Assert.assertEquals; + +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.List; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import org.junit.Test; + +public class AddNumbersUnitTest { + + @Test + public void givenIntStream_whenSum_thenResultIsCorrect() { + IntStream intNumbers = IntStream.range(0, 3); + assertEquals(3, intNumbers.sum()); + } + + @Test + public void givenCollectionOfDouble_whenUsingMapToDoubleToSum_thenResultIsCorrect() { + List doubleNumbers = Arrays.asList(23.48, 52.26, 13.5); + double result = doubleNumbers.stream() + .mapToDouble(Double::doubleValue) + .sum(); + assertEquals(89.24, result, .1); + } + + public void givenStreamOfIntegers_whenUsingReduceToSum_thenResultIsCorrect() { + Stream intNumbers = Stream.of(0, 1, 2); + int result = intNumbers.reduce(0, Integer::sum); + assertEquals(106, result); + } + + public void givenStreamOfBigDecimals_whenUsingReduceToSum_thenResultIsCorrect() { + Stream bigDecimalNumber = Stream.of(BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN); + BigDecimal result = bigDecimalNumber.reduce(BigDecimal.ZERO, BigDecimal::add); + assertEquals(11, result); + } + +} From 487d6b38fc3ac13af3dd026745c83e56b0716f13 Mon Sep 17 00:00:00 2001 From: mikr Date: Sat, 4 Apr 2020 20:24:48 +0200 Subject: [PATCH 47/59] JAVA-117 Standardize spring-boot-modules/spring-boot --- .../java/{org => com}/baeldung/boot/Application.java | 2 +- .../baeldung/boot/config/H2JpaConfig.java | 6 +++--- .../{org => com}/baeldung/boot/config/WebConfig.java | 8 ++++---- .../boot/controller/servlet/HelloWorldServlet.java | 2 +- .../controller/servlet/SpringHelloWorldServlet.java | 2 +- .../boot/converter/GenericBigDecimalConverter.java | 2 +- .../boot/converter/StringToEmployeeConverter.java | 2 +- .../boot/converter/StringToEnumConverterFactory.java | 2 +- .../StringToEmployeeConverterController.java | 2 +- .../{org => com}/baeldung/boot/domain/Modes.java | 2 +- .../common/error/MyCustomErrorController.java | 2 +- .../error/SpringHelloServletRegistrationBean.java | 2 +- .../common/error/controller/ErrorController.java | 2 +- .../MyServletContainerCustomizationBean.java | 2 +- .../resources/ExecutorServiceExitCodeGenerator.java | 2 +- .../{org => com}/baeldung/demo/DemoApplication.java | 2 +- .../baeldung/demo/boottest/Employee.java | 2 +- .../baeldung/demo/boottest/EmployeeRepository.java | 2 +- .../demo/boottest/EmployeeRestController.java | 2 +- .../baeldung/demo/boottest/EmployeeService.java | 2 +- .../baeldung/demo/boottest/EmployeeServiceImpl.java | 2 +- .../baeldung/demo/components/FooService.java | 6 +++--- .../baeldung/demo/exceptions/CommonException.java | 2 +- .../demo/exceptions/FooNotFoundException.java | 2 +- .../java/{org => com}/baeldung/demo/model/Foo.java | 2 +- .../baeldung/demo/repository/FooRepository.java | 4 ++-- .../baeldung/demo/service/FooController.java | 6 +++--- .../endpoints/info/TotalUsersInfoContributor.java | 4 ++-- .../baeldung/main/SpringBootApplication.java | 12 ++++++------ .../main/java/{org => com}/baeldung/model/User.java | 2 +- .../baeldung/repository/UserRepository.java | 4 ++-- .../baeldung/session/exception/Application.java | 4 ++-- .../session/exception/repository/FooRepository.java | 4 ++-- .../exception/repository/FooRepositoryImpl.java | 4 ++-- .../baeldung/startup/AppStartupRunner.java | 2 +- .../startup/CommandLineAppStartupRunner.java | 2 +- .../baeldung/boot/ApplicationIntegrationTest.java | 4 ++-- .../boot/DemoApplicationIntegrationTest.java | 4 ++-- .../repository/FooRepositoryIntegrationTest.java | 8 ++++---- .../repository/HibernateSessionIntegrationTest.java | 8 ++++---- .../NoHibernateSessionIntegrationTest.java | 8 ++++---- .../converter/CustomConverterIntegrationTest.java | 6 +++--- ...ToEmployeeConverterControllerIntegrationTest.java | 4 ++-- .../boottest/EmployeeControllerIntegrationTest.java | 5 +---- .../boottest/EmployeeRepositoryIntegrationTest.java | 6 +++--- .../EmployeeRestControllerIntegrationTest.java | 4 ++-- .../boottest/EmployeeServiceImplIntegrationTest.java | 6 +++++- .../baeldung/demo/boottest/JsonUtil.java | 2 +- .../repository/UserRepositoryIntegrationTest.java | 7 ++++--- 49 files changed, 93 insertions(+), 91 deletions(-) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/boot/Application.java (93%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/boot/config/H2JpaConfig.java (89%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/boot/config/WebConfig.java (71%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/boot/controller/servlet/HelloWorldServlet.java (96%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java (96%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/boot/converter/GenericBigDecimalConverter.java (96%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/boot/converter/StringToEmployeeConverter.java (90%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/boot/converter/StringToEnumConverterFactory.java (95%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/boot/converter/controller/StringToEmployeeConverterController.java (91%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/boot/domain/Modes.java (54%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/common/error/MyCustomErrorController.java (93%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/common/error/SpringHelloServletRegistrationBean.java (91%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/common/error/controller/ErrorController.java (90%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/common/properties/MyServletContainerCustomizationBean.java (95%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java (94%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/demo/DemoApplication.java (94%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/demo/boottest/Employee.java (95%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/demo/boottest/EmployeeRepository.java (91%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/demo/boottest/EmployeeRestController.java (96%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/demo/boottest/EmployeeService.java (89%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/demo/boottest/EmployeeServiceImpl.java (96%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/demo/components/FooService.java (77%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/demo/exceptions/CommonException.java (85%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/demo/exceptions/FooNotFoundException.java (86%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/demo/model/Foo.java (95%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/demo/repository/FooRepository.java (70%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/demo/service/FooController.java (85%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/endpoints/info/TotalUsersInfoContributor.java (89%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/main/SpringBootApplication.java (78%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/model/User.java (96%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/repository/UserRepository.java (98%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/session/exception/Application.java (87%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/session/exception/repository/FooRepository.java (50%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/session/exception/repository/FooRepositoryImpl.java (88%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/startup/AppStartupRunner.java (95%) rename spring-boot-modules/spring-boot/src/main/java/{org => com}/baeldung/startup/CommandLineAppStartupRunner.java (94%) rename spring-boot-modules/spring-boot/src/test/java/{org => com}/baeldung/boot/ApplicationIntegrationTest.java (85%) rename spring-boot-modules/spring-boot/src/test/java/{org => com}/baeldung/boot/DemoApplicationIntegrationTest.java (87%) rename spring-boot-modules/spring-boot/src/test/java/{org => com}/baeldung/boot/repository/FooRepositoryIntegrationTest.java (82%) rename spring-boot-modules/spring-boot/src/test/java/{org => com}/baeldung/boot/repository/HibernateSessionIntegrationTest.java (81%) rename spring-boot-modules/spring-boot/src/test/java/{org => com}/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java (78%) rename spring-boot-modules/spring-boot/src/test/java/{org => com}/baeldung/converter/CustomConverterIntegrationTest.java (94%) rename spring-boot-modules/spring-boot/src/test/java/{org => com}/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java (94%) rename spring-boot-modules/spring-boot/src/test/java/{org => com}/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java (93%) rename spring-boot-modules/spring-boot/src/test/java/{org => com}/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java (94%) rename spring-boot-modules/spring-boot/src/test/java/{org => com}/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java (97%) rename spring-boot-modules/spring-boot/src/test/java/{org => com}/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java (94%) rename spring-boot-modules/spring-boot/src/test/java/{org => com}/baeldung/demo/boottest/JsonUtil.java (91%) rename spring-boot-modules/spring-boot/src/test/java/{org => com}/baeldung/repository/UserRepositoryIntegrationTest.java (92%) diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/Application.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/Application.java similarity index 93% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/Application.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/Application.java index c1b6558b26..cb0d0c1532 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/Application.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/Application.java @@ -1,4 +1,4 @@ -package org.baeldung.boot; +package com.baeldung.boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/config/H2JpaConfig.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/H2JpaConfig.java similarity index 89% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/config/H2JpaConfig.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/H2JpaConfig.java index 92a6ed7ab0..928928c9a5 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/config/H2JpaConfig.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/H2JpaConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.config; +package com.baeldung.boot.config; import java.util.Properties; @@ -18,7 +18,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration -@EnableJpaRepositories(basePackages = { "org.baeldung.boot.repository", "org.baeldung.boot.boottest", "org.baeldung.repository" }) +@EnableJpaRepositories(basePackages = { "com.baeldung.boot.repository", "com.baeldung.boot.boottest", "com.baeldung.repository" }) @PropertySource("classpath:persistence-generic-entity.properties") @EnableTransactionManagement public class H2JpaConfig { @@ -41,7 +41,7 @@ public class H2JpaConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.boot.domain", "org.baeldung.boot.model", "org.baeldung.boot.boottest", "org.baeldung.model" }); + em.setPackagesToScan(new String[] { "com.baeldung.boot.domain", "com.baeldung.boot.model", "com.baeldung.boot.boottest", "com.baeldung.model" }); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/WebConfig.java similarity index 71% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/WebConfig.java index 9554facb12..b23c910a04 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/config/WebConfig.java @@ -1,8 +1,8 @@ -package org.baeldung.boot.config; +package com.baeldung.boot.config; -import org.baeldung.boot.converter.StringToEmployeeConverter; -import org.baeldung.boot.converter.StringToEnumConverterFactory; -import org.baeldung.boot.converter.GenericBigDecimalConverter; +import com.baeldung.boot.converter.StringToEmployeeConverter; +import com.baeldung.boot.converter.StringToEnumConverterFactory; +import com.baeldung.boot.converter.GenericBigDecimalConverter; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/HelloWorldServlet.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/HelloWorldServlet.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/HelloWorldServlet.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/HelloWorldServlet.java index 34ad11254c..80c75aa8b5 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/HelloWorldServlet.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/HelloWorldServlet.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.controller.servlet; +package com.baeldung.boot.controller.servlet; import java.io.IOException; import java.io.PrintWriter; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java index 91547683c6..f276f94b7c 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/controller/servlet/SpringHelloWorldServlet.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.controller.servlet; +package com.baeldung.boot.controller.servlet; import java.io.IOException; import java.io.PrintWriter; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/GenericBigDecimalConverter.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/GenericBigDecimalConverter.java index 8add28fc2d..fc73cfee5f 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/GenericBigDecimalConverter.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.converter; +package com.baeldung.boot.converter; import com.google.common.collect.ImmutableSet; import org.springframework.core.convert.TypeDescriptor; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEmployeeConverter.java similarity index 90% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEmployeeConverter.java index 1bf75b38f0..ac635532ea 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEmployeeConverter.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.converter; +package com.baeldung.boot.converter; import org.springframework.core.convert.converter.Converter; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEnumConverterFactory.java similarity index 95% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEnumConverterFactory.java index ddb2cd2b08..a2dce11a6a 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/StringToEnumConverterFactory.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.converter; +package com.baeldung.boot.converter; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.ConverterFactory; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/controller/StringToEmployeeConverterController.java similarity index 91% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/controller/StringToEmployeeConverterController.java index 27bad4c387..260b1c734b 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/converter/controller/StringToEmployeeConverterController.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.converter.controller; +package com.baeldung.boot.converter.controller; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/domain/Modes.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/domain/Modes.java similarity index 54% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/domain/Modes.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/domain/Modes.java index dcba064e8c..7717294996 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/boot/domain/Modes.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/boot/domain/Modes.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.domain; +package com.baeldung.boot.domain; public enum Modes { diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/error/MyCustomErrorController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/MyCustomErrorController.java similarity index 93% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/error/MyCustomErrorController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/MyCustomErrorController.java index df0e3ec0b2..373ae8f745 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/error/MyCustomErrorController.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/MyCustomErrorController.java @@ -1,4 +1,4 @@ -package org.baeldung.common.error; +package com.baeldung.common.error; import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.web.bind.annotation.GetMapping; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/SpringHelloServletRegistrationBean.java similarity index 91% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/SpringHelloServletRegistrationBean.java index 774cf1b970..3f51a4ab69 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/SpringHelloServletRegistrationBean.java @@ -1,4 +1,4 @@ -package org.baeldung.common.error; +package com.baeldung.common.error; import org.springframework.boot.web.servlet.ServletRegistrationBean; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/error/controller/ErrorController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/controller/ErrorController.java similarity index 90% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/error/controller/ErrorController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/controller/ErrorController.java index ac5f92e9c9..1e5fbf3ac4 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/error/controller/ErrorController.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/error/controller/ErrorController.java @@ -1,4 +1,4 @@ -package org.baeldung.common.error.controller; +package com.baeldung.common.error.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/properties/MyServletContainerCustomizationBean.java similarity index 95% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/properties/MyServletContainerCustomizationBean.java index d553d44769..be503b1b6c 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/properties/MyServletContainerCustomizationBean.java @@ -1,4 +1,4 @@ -package org.baeldung.common.properties; +package com.baeldung.common.properties; import org.springframework.boot.web.server.ErrorPage; import org.springframework.boot.web.server.WebServerFactoryCustomizer; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java similarity index 94% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java index 64853a9941..1db7054f85 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java @@ -1,4 +1,4 @@ -package org.baeldung.common.resources; +package com.baeldung.common.resources; import org.springframework.boot.ExitCodeGenerator; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/DemoApplication.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java similarity index 94% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/DemoApplication.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java index 4a88fcea07..eb091b4695 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/DemoApplication.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java @@ -1,4 +1,4 @@ -package org.baeldung.demo; +package com.baeldung.demo; import com.baeldung.graphql.GraphqlConfiguration; import org.springframework.boot.SpringApplication; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/Employee.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/Employee.java similarity index 95% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/Employee.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/Employee.java index 645ce2838a..fa3c1dc809 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/Employee.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/Employee.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRepository.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRepository.java similarity index 91% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRepository.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRepository.java index 00fdbfaae4..b6850d587e 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRepository.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRepository.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRestController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRestController.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRestController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRestController.java index 516bff0e8c..7d2e06d4a0 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeRestController.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRestController.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeService.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeService.java similarity index 89% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeService.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeService.java index 07765a511c..ff1976cad1 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeService.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeService.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeServiceImpl.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeServiceImpl.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeServiceImpl.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeServiceImpl.java index a1639b29cc..156fc571f3 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/boottest/EmployeeServiceImpl.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeServiceImpl.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/components/FooService.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/components/FooService.java similarity index 77% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/components/FooService.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/components/FooService.java index 66943f6461..98a0db67ef 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/components/FooService.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/components/FooService.java @@ -1,7 +1,7 @@ -package org.baeldung.demo.components; +package com.baeldung.demo.components; -import org.baeldung.demo.model.Foo; -import org.baeldung.demo.repository.FooRepository; +import com.baeldung.demo.model.Foo; +import com.baeldung.demo.repository.FooRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/exceptions/CommonException.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/CommonException.java similarity index 85% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/exceptions/CommonException.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/CommonException.java index 51dd7bbd44..276802d0b9 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/exceptions/CommonException.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/CommonException.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.exceptions; +package com.baeldung.demo.exceptions; public class CommonException extends RuntimeException { diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/exceptions/FooNotFoundException.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/FooNotFoundException.java similarity index 86% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/exceptions/FooNotFoundException.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/FooNotFoundException.java index 59796c58f0..8c425d078e 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/exceptions/FooNotFoundException.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/exceptions/FooNotFoundException.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.exceptions; +package com.baeldung.demo.exceptions; public class FooNotFoundException extends RuntimeException { diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/model/Foo.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/model/Foo.java similarity index 95% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/model/Foo.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/model/Foo.java index e5638cfd3d..796bcca11b 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/model/Foo.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/model/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.model; +package com.baeldung.demo.model; import java.io.Serializable; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/repository/FooRepository.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/repository/FooRepository.java similarity index 70% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/repository/FooRepository.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/repository/FooRepository.java index c04e0c7438..ed27ac23bc 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/repository/FooRepository.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/repository/FooRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.demo.repository; +package com.baeldung.demo.repository; -import org.baeldung.demo.model.Foo; +import com.baeldung.demo.model.Foo; import org.springframework.data.jpa.repository.JpaRepository; public interface FooRepository extends JpaRepository { diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/service/FooController.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/service/FooController.java similarity index 85% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/service/FooController.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/service/FooController.java index c28dcde1a7..c72c52fa3e 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/demo/service/FooController.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/service/FooController.java @@ -1,7 +1,7 @@ -package org.baeldung.demo.service; +package com.baeldung.demo.service; -import org.baeldung.demo.components.FooService; -import org.baeldung.demo.model.Foo; +import com.baeldung.demo.model.Foo; +import com.baeldung.demo.components.FooService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/endpoints/info/TotalUsersInfoContributor.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java similarity index 89% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/endpoints/info/TotalUsersInfoContributor.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java index 34b50a2c0a..c316cabda5 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/endpoints/info/TotalUsersInfoContributor.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java @@ -1,9 +1,9 @@ -package org.baeldung.endpoints.info; +package com.baeldung.endpoints.info; import java.util.HashMap; import java.util.Map; -import org.baeldung.repository.UserRepository; +import com.baeldung.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/main/SpringBootApplication.java similarity index 78% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/main/SpringBootApplication.java index a203659d63..c8cfb50f1c 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/main/SpringBootApplication.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/main/SpringBootApplication.java @@ -1,9 +1,9 @@ -package org.baeldung.main; +package com.baeldung.main; -import org.baeldung.boot.controller.servlet.HelloWorldServlet; -import org.baeldung.boot.controller.servlet.SpringHelloWorldServlet; -import org.baeldung.common.error.SpringHelloServletRegistrationBean; -import org.baeldung.common.resources.ExecutorServiceExitCodeGenerator; +import com.baeldung.boot.controller.servlet.HelloWorldServlet; +import com.baeldung.boot.controller.servlet.SpringHelloWorldServlet; +import com.baeldung.common.error.SpringHelloServletRegistrationBean; +import com.baeldung.common.resources.ExecutorServiceExitCodeGenerator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -18,7 +18,7 @@ import java.util.concurrent.Executors; @RestController @EnableAutoConfiguration -@ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.boot.config" }) +@ComponentScan({ "org.baeldung.common.error", "com.baeldung.common.error.controller", "com.baeldung.common.properties", "com.baeldung.common.resources", "com.baeldung.endpoints", "com.baeldung.service", "com.baeldung.monitor.jmx", "com.baeldung.boot.config" }) public class SpringBootApplication { private static ApplicationContext applicationContext; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/model/User.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/model/User.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/model/User.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/model/User.java index eb886338a0..cc5f27f38c 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/model/User.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/model/User.java @@ -1,4 +1,4 @@ -package org.baeldung.model; +package com.baeldung.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/repository/UserRepository.java similarity index 98% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/repository/UserRepository.java index 752664cd5d..4dd863fb17 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/repository/UserRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.repository; +package com.baeldung.repository; -import org.baeldung.model.User; +import com.baeldung.model.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/session/exception/Application.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/Application.java similarity index 87% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/session/exception/Application.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/Application.java index 354c64c258..de4ca5998e 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/session/exception/Application.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/Application.java @@ -1,6 +1,6 @@ -package org.baeldung.session.exception; +package com.baeldung.session.exception; -import org.baeldung.demo.model.Foo; +import com.baeldung.demo.model.Foo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepository.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepository.java similarity index 50% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepository.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepository.java index ce7bbfe57b..5e748973ed 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepository.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.session.exception.repository; +package com.baeldung.session.exception.repository; -import org.baeldung.demo.model.Foo; +import com.baeldung.demo.model.Foo; public interface FooRepository { diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepositoryImpl.java similarity index 88% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepositoryImpl.java index 607bae83ba..a304373d6c 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/session/exception/repository/FooRepositoryImpl.java @@ -1,8 +1,8 @@ -package org.baeldung.session.exception.repository; +package com.baeldung.session.exception.repository; import javax.persistence.EntityManagerFactory; -import org.baeldung.demo.model.Foo; +import com.baeldung.demo.model.Foo; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/startup/AppStartupRunner.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/AppStartupRunner.java similarity index 95% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/startup/AppStartupRunner.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/AppStartupRunner.java index d491bdb42c..0495473704 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/startup/AppStartupRunner.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/AppStartupRunner.java @@ -1,4 +1,4 @@ -package org.baeldung.startup; +package com.baeldung.startup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/startup/CommandLineAppStartupRunner.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/CommandLineAppStartupRunner.java similarity index 94% rename from spring-boot-modules/spring-boot/src/main/java/org/baeldung/startup/CommandLineAppStartupRunner.java rename to spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/CommandLineAppStartupRunner.java index 6a7be59c21..48c5225cf1 100644 --- a/spring-boot-modules/spring-boot/src/main/java/org/baeldung/startup/CommandLineAppStartupRunner.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/startup/CommandLineAppStartupRunner.java @@ -1,4 +1,4 @@ -package org.baeldung.startup; +package com.baeldung.startup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java similarity index 85% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java index 5e351157c8..462291e0ac 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/ApplicationIntegrationTest.java @@ -1,6 +1,6 @@ -package org.baeldung.boot; +package com.baeldung.boot; -import org.baeldung.session.exception.Application; +import com.baeldung.session.exception.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/DemoApplicationIntegrationTest.java similarity index 87% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/DemoApplicationIntegrationTest.java index 0541da3199..aaf4f1f780 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/DemoApplicationIntegrationTest.java @@ -1,6 +1,6 @@ -package org.baeldung.boot; +package com.baeldung.boot; -import org.baeldung.demo.DemoApplication; +import com.baeldung.demo.DemoApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java similarity index 82% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java index c32e36d7e3..1772739d20 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/FooRepositoryIntegrationTest.java @@ -1,8 +1,8 @@ -package org.baeldung.boot.repository; +package com.baeldung.boot.repository; -import org.baeldung.boot.DemoApplicationIntegrationTest; -import org.baeldung.demo.model.Foo; -import org.baeldung.demo.repository.FooRepository; +import com.baeldung.boot.DemoApplicationIntegrationTest; +import com.baeldung.demo.model.Foo; +import com.baeldung.demo.repository.FooRepository; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java similarity index 81% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java index b22282e896..2fe072bb67 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/HibernateSessionIntegrationTest.java @@ -1,8 +1,8 @@ -package org.baeldung.boot.repository; +package com.baeldung.boot.repository; -import org.baeldung.boot.DemoApplicationIntegrationTest; -import org.baeldung.demo.model.Foo; -import org.baeldung.demo.repository.FooRepository; +import com.baeldung.boot.DemoApplicationIntegrationTest; +import com.baeldung.demo.model.Foo; +import com.baeldung.demo.repository.FooRepository; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java similarity index 78% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java index 5c8d10223b..2e3326e6b1 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java @@ -1,8 +1,8 @@ -package org.baeldung.boot.repository; +package com.baeldung.boot.repository; -import org.baeldung.boot.ApplicationIntegrationTest; -import org.baeldung.demo.model.Foo; -import org.baeldung.session.exception.repository.FooRepository; +import com.baeldung.boot.ApplicationIntegrationTest; +import com.baeldung.demo.model.Foo; +import com.baeldung.session.exception.repository.FooRepository; import org.hibernate.HibernateException; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/CustomConverterIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/CustomConverterIntegrationTest.java index bd1ae2c8fa..4619964783 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/converter/CustomConverterIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/CustomConverterIntegrationTest.java @@ -1,9 +1,9 @@ -package org.baeldung.converter; +package com.baeldung.converter; import com.baeldung.toggle.Employee; -import org.baeldung.boot.Application; -import org.baeldung.boot.domain.Modes; +import com.baeldung.boot.Application; +import com.baeldung.boot.domain.Modes; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java index 2afda7565a..52dc542ebf 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.converter.controller; +package com.baeldung.converter.controller; import org.junit.Test; import org.junit.runner.RunWith; @@ -14,7 +14,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultHandlers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.baeldung.boot.Application; +import com.baeldung.boot.Application; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = Application.class) diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java similarity index 93% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java index 2d70583a54..962abf0fa3 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java @@ -1,8 +1,5 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; -import org.baeldung.demo.boottest.Employee; -import org.baeldung.demo.boottest.EmployeeRestController; -import org.baeldung.demo.boottest.EmployeeService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java index 3042f95a46..164887886b 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java @@ -1,7 +1,7 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; -import org.baeldung.demo.boottest.Employee; -import org.baeldung.demo.boottest.EmployeeRepository; +import com.baeldung.demo.boottest.Employee; +import com.baeldung.demo.boottest.EmployeeRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java similarity index 97% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java index a4b35889d6..327e9f9d56 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.is; @@ -14,7 +14,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import java.io.IOException; import java.util.List; -import org.baeldung.demo.DemoApplication; +import com.baeldung.demo.DemoApplication; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java index df28111a57..88f2830a2b 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import static org.assertj.core.api.Assertions.assertThat; @@ -6,6 +6,10 @@ import java.util.Arrays; import java.util.List; import java.util.Optional; +import com.baeldung.demo.boottest.Employee; +import com.baeldung.demo.boottest.EmployeeRepository; +import com.baeldung.demo.boottest.EmployeeService; +import com.baeldung.demo.boottest.EmployeeServiceImpl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/JsonUtil.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/JsonUtil.java similarity index 91% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/JsonUtil.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/JsonUtil.java index 7e04f47696..3fcd709f7c 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/demo/boottest/JsonUtil.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/JsonUtil.java @@ -1,4 +1,4 @@ -package org.baeldung.demo.boottest; +package com.baeldung.demo.boottest; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java similarity index 92% rename from spring-boot-modules/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java rename to spring-boot-modules/spring-boot/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java index ea7f118967..a1318949f3 100644 --- a/spring-boot-modules/spring-boot/src/test/java/org/baeldung/repository/UserRepositoryIntegrationTest.java +++ b/spring-boot-modules/spring-boot/src/test/java/com/baeldung/repository/UserRepositoryIntegrationTest.java @@ -1,7 +1,8 @@ -package org.baeldung.repository; +package com.baeldung.repository; -import org.baeldung.boot.config.H2JpaConfig; -import org.baeldung.model.User; +import com.baeldung.boot.config.H2JpaConfig; +import com.baeldung.model.User; +import com.baeldung.repository.UserRepository; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; From 2d0f2c171bba3b8d970de9e8e76c9e78ea07d124 Mon Sep 17 00:00:00 2001 From: mikr Date: Sat, 4 Apr 2020 20:40:09 +0200 Subject: [PATCH 48/59] JAVA-117 Standardize spring-boot-modules/spring-boot-client --- .../main/java/{org => com}/baeldung/boot/Application.java | 2 +- .../java/{org => com}/baeldung/boot/client/Details.java | 2 +- .../baeldung/boot/client/DetailsServiceClient.java | 2 +- .../{org => com}/baeldung/websocket/client/Message.java | 2 +- .../baeldung/websocket/client/MyStompSessionHandler.java | 2 +- .../{org => com}/baeldung/websocket/client/StompClient.java | 2 +- .../test/java/{org => com}/baeldung/SpringContextTest.java | 4 ++-- .../boot/client/DetailsServiceClientIntegrationTest.java | 6 ++++-- .../client/MyStompSessionHandlerIntegrationTest.java | 1 - 9 files changed, 12 insertions(+), 11 deletions(-) rename spring-boot-modules/spring-boot-client/src/main/java/{org => com}/baeldung/boot/Application.java (93%) rename spring-boot-modules/spring-boot-client/src/main/java/{org => com}/baeldung/boot/client/Details.java (93%) rename spring-boot-modules/spring-boot-client/src/main/java/{org => com}/baeldung/boot/client/DetailsServiceClient.java (93%) rename spring-boot-modules/spring-boot-client/src/main/java/{org => com}/baeldung/websocket/client/Message.java (89%) rename spring-boot-modules/spring-boot-client/src/main/java/{org => com}/baeldung/websocket/client/MyStompSessionHandler.java (98%) rename spring-boot-modules/spring-boot-client/src/main/java/{org => com}/baeldung/websocket/client/StompClient.java (96%) rename spring-boot-modules/spring-boot-client/src/test/java/{org => com}/baeldung/SpringContextTest.java (86%) rename spring-boot-modules/spring-boot-client/src/test/java/{org => com}/baeldung/boot/client/DetailsServiceClientIntegrationTest.java (90%) diff --git a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/boot/Application.java b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/Application.java similarity index 93% rename from spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/boot/Application.java rename to spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/Application.java index c1b6558b26..cb0d0c1532 100644 --- a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/boot/Application.java +++ b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/Application.java @@ -1,4 +1,4 @@ -package org.baeldung.boot; +package com.baeldung.boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/boot/client/Details.java b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/client/Details.java similarity index 93% rename from spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/boot/client/Details.java rename to spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/client/Details.java index 1e3ddf7b21..c806476634 100644 --- a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/boot/client/Details.java +++ b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/client/Details.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.client; +package com.baeldung.boot.client; public class Details { diff --git a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/client/DetailsServiceClient.java similarity index 93% rename from spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java rename to spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/client/DetailsServiceClient.java index f2b9d6d030..a9f1b08c97 100644 --- a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/boot/client/DetailsServiceClient.java +++ b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/boot/client/DetailsServiceClient.java @@ -1,4 +1,4 @@ -package org.baeldung.boot.client; +package com.baeldung.boot.client; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.stereotype.Service; diff --git a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/websocket/client/Message.java b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/Message.java similarity index 89% rename from spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/websocket/client/Message.java rename to spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/Message.java index 2744c49f62..19140f76a2 100644 --- a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/websocket/client/Message.java +++ b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/Message.java @@ -1,4 +1,4 @@ -package org.baeldung.websocket.client; +package com.baeldung.websocket.client; public class Message { diff --git a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/MyStompSessionHandler.java similarity index 98% rename from spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java rename to spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/MyStompSessionHandler.java index 92beab9430..8ccc42c58a 100644 --- a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/websocket/client/MyStompSessionHandler.java +++ b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/MyStompSessionHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.websocket.client; +package com.baeldung.websocket.client; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/websocket/client/StompClient.java b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/StompClient.java similarity index 96% rename from spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/websocket/client/StompClient.java rename to spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/StompClient.java index 2bff07186d..04d87dd2ed 100644 --- a/spring-boot-modules/spring-boot-client/src/main/java/org/baeldung/websocket/client/StompClient.java +++ b/spring-boot-modules/spring-boot-client/src/main/java/com/baeldung/websocket/client/StompClient.java @@ -1,4 +1,4 @@ -package org.baeldung.websocket.client; +package com.baeldung.websocket.client; import java.util.Scanner; diff --git a/spring-boot-modules/spring-boot-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/SpringContextTest.java similarity index 86% rename from spring-boot-modules/spring-boot-client/src/test/java/org/baeldung/SpringContextTest.java rename to spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/SpringContextTest.java index 9c3b83ea79..1341f17eac 100644 --- a/spring-boot-modules/spring-boot-client/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/SpringContextTest.java @@ -1,6 +1,6 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.boot.Application; +import com.baeldung.boot.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-boot-modules/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/boot/client/DetailsServiceClientIntegrationTest.java similarity index 90% rename from spring-boot-modules/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java rename to spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/boot/client/DetailsServiceClientIntegrationTest.java index d423300b85..4af5370950 100644 --- a/spring-boot-modules/spring-boot-client/src/test/java/org/baeldung/boot/client/DetailsServiceClientIntegrationTest.java +++ b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/boot/client/DetailsServiceClientIntegrationTest.java @@ -1,10 +1,12 @@ -package org.baeldung.boot.client; +package com.baeldung.boot.client; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; -import org.baeldung.boot.Application; +import com.baeldung.boot.Application; +import com.baeldung.boot.client.Details; +import com.baeldung.boot.client.DetailsServiceClient; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java index bb1b5e254e..57eec935f6 100644 --- a/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java +++ b/spring-boot-modules/spring-boot-client/src/test/java/com/baeldung/websocket/client/MyStompSessionHandlerIntegrationTest.java @@ -1,6 +1,5 @@ package com.baeldung.websocket.client; -import org.baeldung.websocket.client.MyStompSessionHandler; import org.junit.Test; import org.mockito.Mockito; import org.springframework.messaging.simp.stomp.StompHeaders; From 641956f87db3f02e3291cc684e868b9d19b808ad Mon Sep 17 00:00:00 2001 From: mikr Date: Sat, 4 Apr 2020 21:16:51 +0200 Subject: [PATCH 49/59] JAVA-117 Standardize spring-boot-modules/spring-boot-gradle --- spring-boot-modules/spring-boot-gradle/build.gradle | 8 ++++---- .../main/java/{org => com}/baeldung/DemoApplication.java | 2 +- .../java/{org => com}/baeldung/DemoApplicationTests.java | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) rename spring-boot-modules/spring-boot-gradle/src/main/java/{org => com}/baeldung/DemoApplication.java (92%) rename spring-boot-modules/spring-boot-gradle/src/test/java/{org => com}/baeldung/DemoApplicationTests.java (93%) diff --git a/spring-boot-modules/spring-boot-gradle/build.gradle b/spring-boot-modules/spring-boot-gradle/build.gradle index 96055536c3..faae01a1a5 100644 --- a/spring-boot-modules/spring-boot-gradle/build.gradle +++ b/spring-boot-modules/spring-boot-gradle/build.gradle @@ -21,7 +21,7 @@ apply plugin: 'io.spring.dependency-management' //add tasks thinJar and thinResolve for thin JAR deployments apply plugin: 'org.springframework.boot.experimental.thin-launcher' -group = 'org.baeldung' +group = 'com.baeldung' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 @@ -35,16 +35,16 @@ dependencies { } springBoot { - mainClassName = 'org.baeldung.DemoApplication' + mainClassName = 'com.baeldung.DemoApplication' } bootJar { // This is overridden by the mainClassName in springBoot{} and added here for reference purposes. - mainClassName = 'org.baeldung.DemoApplication' + mainClassName = 'com.baeldung.DemoApplication' // This block serves the same purpose as the above thus commented out. Added here for reference purposes // manifest { -// attributes 'Start-Class': 'org.baeldung.DemoApplication' +// attributes 'Start-Class': 'com.baeldung.DemoApplication' // } } diff --git a/spring-boot-modules/spring-boot-gradle/src/main/java/org/baeldung/DemoApplication.java b/spring-boot-modules/spring-boot-gradle/src/main/java/com/baeldung/DemoApplication.java similarity index 92% rename from spring-boot-modules/spring-boot-gradle/src/main/java/org/baeldung/DemoApplication.java rename to spring-boot-modules/spring-boot-gradle/src/main/java/com/baeldung/DemoApplication.java index f8df823f25..64bac6936b 100644 --- a/spring-boot-modules/spring-boot-gradle/src/main/java/org/baeldung/DemoApplication.java +++ b/spring-boot-modules/spring-boot-gradle/src/main/java/com/baeldung/DemoApplication.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-modules/spring-boot-gradle/src/test/java/org/baeldung/DemoApplicationTests.java b/spring-boot-modules/spring-boot-gradle/src/test/java/com/baeldung/DemoApplicationTests.java similarity index 93% rename from spring-boot-modules/spring-boot-gradle/src/test/java/org/baeldung/DemoApplicationTests.java rename to spring-boot-modules/spring-boot-gradle/src/test/java/com/baeldung/DemoApplicationTests.java index b24bfb2cb6..65395582cb 100644 --- a/spring-boot-modules/spring-boot-gradle/src/test/java/org/baeldung/DemoApplicationTests.java +++ b/spring-boot-modules/spring-boot-gradle/src/test/java/com/baeldung/DemoApplicationTests.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; From ad889f6bcd2c597f86434b731141ccb4f0321ca1 Mon Sep 17 00:00:00 2001 From: mikr Date: Sat, 4 Apr 2020 21:47:45 +0200 Subject: [PATCH 50/59] JAVA-117 Standardize spring-boot-modules --- .../src/test/java/org/baeldung/SpringContextTest.java | 2 +- .../src/test/java/org/baeldung/SpringContextTest.java | 2 +- .../src/test/java/org/baeldung/SpringContextTest.java | 2 +- spring-boot-modules/spring-boot-artifacts/pom.xml | 2 +- .../src/test/java/org/baeldung/SpringContextTest.java | 2 +- .../src/test/java/org/baeldung/SpringContextTest.java | 2 +- .../src/test/java/org/baeldung/SpringContextTest.java | 2 +- .../src/test/java/org/baeldung/SpringContextTest.java | 2 +- spring-boot-modules/spring-boot-deployment/pom.xml | 2 +- .../src/test/java/org/baeldung/SpringContextTest.java | 2 +- .../src/test/java/org/baeldung/SpringContextTest.java | 2 +- .../src/test/java/org/baeldung/SpringContextTest.java | 2 +- .../src/test/java/org/baeldung/SpringContextLiveTest.java | 2 +- .../src/test/java/org/baeldung/SpringContextTest.java | 2 +- .../properties/external/ExternalPropertiesWithJavaConfig.java | 2 +- .../properties/external/ExternalPropertiesWithXmlConfig.java | 2 +- .../properties/external/ExternalPropertiesWithXmlConfigOne.java | 2 +- .../src/test/java/org/baeldung/SpringContextTest.java | 2 +- .../src/test/java/org/baeldung/SpringContextTest.java | 2 +- .../src/test/java/org/baeldung/SpringContextTest.java | 2 +- .../src/main/java/com/baeldung/main/SpringBootApplication.java | 2 +- 21 files changed, 21 insertions(+), 21 deletions(-) diff --git a/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java index 834f26dacf..78a1ab7a54 100644 --- a/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-admin/spring-boot-admin-client/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java index c185456019..3322193134 100644 --- a/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-admin/spring-boot-admin-server/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-angular/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-angular/src/test/java/org/baeldung/SpringContextTest.java index 961d756a68..0f4fa757d6 100644 --- a/spring-boot-modules/spring-boot-angular/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-angular/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-artifacts/pom.xml b/spring-boot-modules/spring-boot-artifacts/pom.xml index f7c8636593..de9f6ab635 100644 --- a/spring-boot-modules/spring-boot-artifacts/pom.xml +++ b/spring-boot-modules/spring-boot-artifacts/pom.xml @@ -208,7 +208,7 @@ - org.baeldung.boot.Application + com.baeldung.boot.Application 3.1.1 3.3.7-1 2.2 diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java index 8324fabfca..ce743e0f77 100644 --- a/spring-boot-modules/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java index ff3e795778..ca8989724b 100644 --- a/spring-boot-modules/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-ctx-fluent/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java index e6ce83fab5..b4668e7d2b 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java index b82b67df68..7103da97f3 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-deployment/pom.xml b/spring-boot-modules/spring-boot-deployment/pom.xml index 64c0e698f6..b3fc3eabd1 100644 --- a/spring-boot-modules/spring-boot-deployment/pom.xml +++ b/spring-boot-modules/spring-boot-deployment/pom.xml @@ -190,7 +190,7 @@ - org.baeldung.boot.Application + com.baeldung.boot.Application 3.1.1 3.3.7-1 2.2 diff --git a/spring-boot-modules/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java index ab6e4557d5..97810cf590 100644 --- a/spring-boot-modules/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-jasypt/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java index 4effccc083..3f3ecd87d0 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-keycloak/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java index 9817522e68..d2660ad84e 100644 --- a/spring-boot-modules/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-logging-log4j2/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextLiveTest.java index 069dd41b8d..209a93d94c 100644 --- a/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextLiveTest.java +++ b/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java index 16e0708fc9..e73f4e79f7 100644 --- a/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithJavaConfig.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithJavaConfig.java index d43f18f6a7..5b954f8941 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithJavaConfig.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithJavaConfig.java @@ -7,7 +7,7 @@ import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; @Configuration -@ComponentScan("org.baeldung.properties.core") +@ComponentScan("com.baeldung.properties.core") @PropertySource("classpath:foo.properties") public class ExternalPropertiesWithJavaConfig { diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfig.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfig.java index 6d105428d9..9080e3d0ba 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfig.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfig.java @@ -6,7 +6,7 @@ import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource("classpath:configForProperties.xml") -@ComponentScan("org.baeldung.core") +@ComponentScan("com.baeldung.core") public class ExternalPropertiesWithXmlConfig { public ExternalPropertiesWithXmlConfig() { diff --git a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfigOne.java b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfigOne.java index 6f1e4c8490..f45f5b6a03 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfigOne.java +++ b/spring-boot-modules/spring-boot-properties/src/main/java/com/baeldung/properties/external/ExternalPropertiesWithXmlConfigOne.java @@ -6,7 +6,7 @@ import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource("classpath:configForPropertiesOne.xml") -@ComponentScan("org.baeldung.core") +@ComponentScan("com.baeldung.core") public class ExternalPropertiesWithXmlConfigOne { public ExternalPropertiesWithXmlConfigOne() { diff --git a/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java index 874c4f582f..2e1a17199d 100644 --- a/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-property-exp/property-exp-custom-config/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java index 874c4f582f..2e1a17199d 100644 --- a/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-property-exp/property-exp-default-config/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java index 16e0708fc9..e73f4e79f7 100644 --- a/spring-boot-modules/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-vue/src/test/java/org/baeldung/SpringContextTest.java @@ -1,4 +1,4 @@ -package org.baeldung; +package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/main/SpringBootApplication.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/main/SpringBootApplication.java index c8cfb50f1c..383932524f 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/main/SpringBootApplication.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/main/SpringBootApplication.java @@ -18,7 +18,7 @@ import java.util.concurrent.Executors; @RestController @EnableAutoConfiguration -@ComponentScan({ "org.baeldung.common.error", "com.baeldung.common.error.controller", "com.baeldung.common.properties", "com.baeldung.common.resources", "com.baeldung.endpoints", "com.baeldung.service", "com.baeldung.monitor.jmx", "com.baeldung.boot.config" }) +@ComponentScan({ "com.baeldung.common.error", "com.baeldung.common.error.controller", "com.baeldung.common.properties", "com.baeldung.common.resources", "com.baeldung.endpoints", "com.baeldung.service", "com.baeldung.monitor.jmx", "com.baeldung.boot.config" }) public class SpringBootApplication { private static ApplicationContext applicationContext; From 8c5dfc6f173c01ff21b6392393152fad6154bdea Mon Sep 17 00:00:00 2001 From: kwoyke Date: Sun, 5 Apr 2020 07:52:47 +0200 Subject: [PATCH 51/59] BAEL-3978: Add code samples for Objects.equals() (#9033) --- .../comparelong/CompareLongUnitTest.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparelong/CompareLongUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparelong/CompareLongUnitTest.java index ab4ea2b657..a26b0a74b0 100644 --- a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparelong/CompareLongUnitTest.java +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparelong/CompareLongUnitTest.java @@ -1,8 +1,12 @@ package com.baeldung.comparelong; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + import org.junit.Test; +import java.util.Objects; + public class CompareLongUnitTest { @Test @@ -32,6 +36,33 @@ public class CompareLongUnitTest { assertThat(l1.equals(l2)).isTrue(); } + @Test + public void givenLongValuesLessThan128_whenUsingObjectsEquals_thenSuccess() { + + Long l1 = 127L; + Long l2 = 127L; + + assertThat(Objects.equals(l1, l2)).isTrue(); + } + + @Test + public void givenLongValuesGreaterOrEqualsThan128_whenUsingObjectsEquals_thenSuccess() { + + Long l1 = 128L; + Long l2 = 128L; + + assertThat(Objects.equals(l1, l2)).isTrue(); + } + + @Test + public void givenNullReference_whenUsingObjectsEquals_thenNoException() { + + Long l1 = null; + Long l2 = 128L; + + assertThatCode(() -> Objects.equals(l1, l2)).doesNotThrowAnyException(); + } + @Test public void givenLongValuesGreaterOrEqualsThan128_whenUsingComparisonOperator_andLongValue_thenSuccess() { From b30ee628059d55773e18420d9ed8df9f079678eb Mon Sep 17 00:00:00 2001 From: Belma Jakupovic Date: Mon, 6 Apr 2020 20:22:28 +0200 Subject: [PATCH 52/59] Belma Jakupovic - Mockito additional answers (#9041) --- .../mockito/additionalanswers/Book.java | 58 ++++++++++++++++ .../additionalanswers/BookRepository.java | 17 +++++ .../additionalanswers/BookService.java | 22 ++++++ .../BookServiceUnitTest.java | 68 +++++++++++++++++++ 4 files changed, 165 insertions(+) create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/Book.java create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookRepository.java create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookService.java create mode 100644 testing-modules/mockito-2/src/test/java/com/baeldung/mockito/additionalanswers/BookServiceUnitTest.java diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/Book.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/Book.java new file mode 100644 index 0000000000..fa021f8cba --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/Book.java @@ -0,0 +1,58 @@ +package com.baeldung.mockito.additionalanswers; + +public class Book { + + private Long bookId; + + private String title; + + private String author; + + private int numberOfPages; + + public Book(String title, String author, int numberOfPages) { + this.title = title; + this.author = author; + this.numberOfPages = numberOfPages; + } + + public Book(Long bookId, String title, String author, int numberOfPages) { + this.bookId = bookId; + this.title = title; + this.author = author; + this.numberOfPages = numberOfPages; + } + + public Long getBookId() { + return bookId; + } + + public void setBookId(Long bookId) { + this.bookId = bookId; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public int getNumberOfPages() { + return numberOfPages; + } + + public void setNumberOfPages(int numberOfPages) { + this.numberOfPages = numberOfPages; + } +} + diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookRepository.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookRepository.java new file mode 100644 index 0000000000..78187e3f01 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookRepository.java @@ -0,0 +1,17 @@ +package com.baeldung.mockito.additionalanswers; + +public class BookRepository { + public Book getByBookId(Long bookId) { + return new Book(bookId, "To Kill a Mocking Bird", "Harper Lee", 256); + } + + public Book save(Book book) { + return new Book(book.getBookId(), book.getTitle(), book.getAuthor(), book.getNumberOfPages()); + } + + public Book checkIfEquals(Book bookOne, Book bookTwo, Book bookThree) { + if (bookOne.equals(bookTwo) && bookTwo.equals(bookThree) && bookThree.equals(bookOne)) { + return bookOne; + } else return bookTwo; + } +} diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookService.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookService.java new file mode 100644 index 0000000000..92c01f8a70 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/additionalanswers/BookService.java @@ -0,0 +1,22 @@ +package com.baeldung.mockito.additionalanswers; + +public class BookService { + private final BookRepository bookRepository; + + public BookService(BookRepository bookRepository) { + this.bookRepository = bookRepository; + } + + public Book getByBookId(Long id) { + return bookRepository.getByBookId(id); + } + + public Book save(Book book) { + return bookRepository.save(book); + } + + public Book checkifEquals(Book book1, Book book2, Book book3) { + return bookRepository.checkIfEquals(book1, book2, book3); + } +} + diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/additionalanswers/BookServiceUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/additionalanswers/BookServiceUnitTest.java new file mode 100644 index 0000000000..c9527ec0ec --- /dev/null +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/additionalanswers/BookServiceUnitTest.java @@ -0,0 +1,68 @@ +package com.baeldung.mockito.additionalanswers; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.AdditionalAnswers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; + +@RunWith(MockitoJUnitRunner.class) +public class BookServiceUnitTest { + @InjectMocks + private BookService bookService; + + @Mock + private BookRepository bookRepository; + + @Test + public void givenSaveMethodMocked_whenSaveInvoked_ThenReturnFirstArgument_UnitTest() { + Book book = new Book("To Kill a Mocking Bird", "Harper Lee", 256); + Mockito.when(bookRepository.save(any(Book.class))).then(AdditionalAnswers.returnsFirstArg()); + + Book savedBook = bookService.save(book); + + assertEquals(savedBook, book); + } + + @Test + public void givenCheckifEqualsMethodMocked_whenCheckifEqualsInvoked_ThenReturnSecondArgument_UnitTest() { + Book book1 = new Book(1L, "The Stranger", "Albert Camus", 456); + Book book2 = new Book(2L, "Animal Farm", "George Orwell", 300); + Book book3 = new Book(3L, "Romeo and Juliet", "William Shakespeare", 200); + + Mockito.when(bookRepository.checkIfEquals(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsSecondArg()); + + Book secondBook = bookService.checkifEquals(book1, book2, book3); + + assertEquals(secondBook, book2); + } + + @Test + public void givenCheckifEqualsMethodMocked_whenCheckifEqualsInvoked_ThenReturnLastArgument_UnitTest() { + Book book1 = new Book(1L, "The Stranger", "Albert Camus", 456); + Book book2 = new Book(2L, "Animal Farm", "George Orwell", 300); + Book book3 = new Book(3L, "Romeo and Juliet", "William Shakespeare", 200); + + Mockito.when(bookRepository.checkIfEquals(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsLastArg()); + + Book lastBook = bookService.checkifEquals(book1, book2, book3); + assertEquals(lastBook, book3); + } + + @Test + public void givenCheckifEqualsMethodMocked_whenCheckifEqualsInvoked_ThenReturnArgumentAtIndex_UnitTest() { + Book book1 = new Book(1L, "The Stranger", "Albert Camus", 456); + Book book2 = new Book(2L, "Animal Farm", "George Orwell", 300); + Book book3 = new Book(3L, "Romeo and Juliet", "William Shakespeare", 200); + + Mockito.when(bookRepository.checkIfEquals(any(Book.class), any(Book.class), any(Book.class))).then(AdditionalAnswers.returnsArgAt(1)); + + Book bookOnIndex = bookService.checkifEquals(book1, book2, book3); + + assertEquals(bookOnIndex, book2); + } +} From ab6fee6012ba5ab83ab4263ea3a53a771b4f7ecf Mon Sep 17 00:00:00 2001 From: Jonathan Cook Date: Mon, 6 Apr 2020 22:21:24 +0200 Subject: [PATCH 53/59] BAEL-3868 - Fix the integrations tests in mocks (#9039) * 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 Co-authored-by: Jonathan Cook --- .../jmockit/ExpectationsCollaborator.java | 2 +- .../jmockit/ExpectationsIntegrationTest.java | 35 ++++++++++--------- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/testing-modules/mocks/src/main/java/com/baeldung/jmockit/ExpectationsCollaborator.java b/testing-modules/mocks/src/main/java/com/baeldung/jmockit/ExpectationsCollaborator.java index 799e7721e0..1aafa28a6a 100644 --- a/testing-modules/mocks/src/main/java/com/baeldung/jmockit/ExpectationsCollaborator.java +++ b/testing-modules/mocks/src/main/java/com/baeldung/jmockit/ExpectationsCollaborator.java @@ -15,5 +15,5 @@ public interface ExpectationsCollaborator { void methodForArgThat(Object o); String methodReturnsString(); int methodReturnsInt(); - Object methodForDelegate(int i); + int methodForDelegate(int i); } diff --git a/testing-modules/mocks/src/test/java/com/baeldung/jmockit/ExpectationsIntegrationTest.java b/testing-modules/mocks/src/test/java/com/baeldung/jmockit/ExpectationsIntegrationTest.java index 8b0c3ab4ec..1ff90111d1 100644 --- a/testing-modules/mocks/src/test/java/com/baeldung/jmockit/ExpectationsIntegrationTest.java +++ b/testing-modules/mocks/src/test/java/com/baeldung/jmockit/ExpectationsIntegrationTest.java @@ -1,21 +1,21 @@ package com.baeldung.jmockit; -import com.baeldung.jmockit.ExpectationsCollaborator; -import com.baeldung.jmockit.Model; -import mockit.Delegate; -import mockit.Expectations; -import mockit.Mocked; -import mockit.Verifications; -import mockit.integration.junit4.JMockit; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.Test; import org.junit.runner.RunWith; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; +import mockit.Delegate; +import mockit.Expectations; +import mockit.Mocked; +import mockit.Verifications; +import mockit.integration.junit4.JMockit; @RunWith(JMockit.class) @SuppressWarnings("unchecked") @@ -112,17 +112,16 @@ public class ExpectationsIntegrationTest { result = "foo"; result = new Exception(); result = "bar"; - mock.methodReturnsInt(); - result = new int[]{1, 2, 3}; - mock.methodReturnsString(); returns("foo", "bar"); mock.methodReturnsInt(); + result = new int[]{1, 2, 3}; result = 1; }}; assertEquals("Should return foo", "foo", mock.methodReturnsString()); try { mock.methodReturnsString(); + fail("Shouldn't reach here"); } catch (Exception e) { // NOOP } @@ -134,13 +133,14 @@ public class ExpectationsIntegrationTest { assertEquals("Should return bar", "bar", mock.methodReturnsString()); assertEquals("Should return 1", 1, mock.methodReturnsInt()); } - + @Test public void testDelegate(@Mocked ExpectationsCollaborator mock) { new Expectations() {{ mock.methodForDelegate(anyInt); - result = new Delegate() { - public int delegate(int i) throws Exception { + + result = new Delegate() { + int delegate(int i) throws Exception { if (i < 3) { return 5; } else { @@ -153,6 +153,7 @@ public class ExpectationsIntegrationTest { assertEquals("Should return 5", 5, mock.methodForDelegate(1)); try { mock.methodForDelegate(3); + fail("Shouldn't reach here"); } catch (Exception e) { } } From ad669c87a4c4de7df98f6dddf5db813cd76b254d Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Mon, 6 Apr 2020 22:28:19 +0200 Subject: [PATCH 54/59] JAVA-1201: Disable libraries-concurrency in the main pom.xml --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index e21c13efc2..bc9b820766 100644 --- a/pom.xml +++ b/pom.xml @@ -1263,7 +1263,7 @@ wildfly xml xstream - libraries-concurrency + From 7f010f0f98ee07b1fc42237bc864a30ea622596a Mon Sep 17 00:00:00 2001 From: Krzysztof Woyke Date: Tue, 7 Apr 2020 08:50:55 +0200 Subject: [PATCH 55/59] Revert "JAVA-1201: Disable libraries-concurrency in the main pom.xml" This reverts commit ad669c87a4c4de7df98f6dddf5db813cd76b254d. --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index bc9b820766..e21c13efc2 100644 --- a/pom.xml +++ b/pom.xml @@ -1263,7 +1263,7 @@ wildfly xml xstream - + libraries-concurrency From 5bd296e8d0470a9eea32f8b7c42e56b992e222f7 Mon Sep 17 00:00:00 2001 From: Krzysztof Woyke Date: Tue, 7 Apr 2020 08:52:00 +0200 Subject: [PATCH 56/59] JAVA-1201: Disable coroutines-with-quasar as it needs Java 12 --- libraries-concurrency/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries-concurrency/pom.xml b/libraries-concurrency/pom.xml index 7ae834025f..cb59b17674 100644 --- a/libraries-concurrency/pom.xml +++ b/libraries-concurrency/pom.xml @@ -14,7 +14,7 @@ - coroutines-with-quasar + \ No newline at end of file From 8e107d118090a1704ae096aecf101c6dd3c37858 Mon Sep 17 00:00:00 2001 From: Sampada <46674082+sampada07@users.noreply.github.com> Date: Wed, 8 Apr 2020 02:26:53 +0530 Subject: [PATCH 57/59] BAEL-3895: HTTP/2 in Netty (#9036) * BAEL-3895 : HTTP/2 in Netty * BAEL-3895: Added Live Test in place of java client * BAEL-3895: Commented out netty module from main pom as it needs Java 13 --- netty/README.md | 6 + netty/pom.xml | 34 +++++ .../com/baeldung/netty/http2/Http2Util.java | 135 ++++++++++++++++++ .../http2/client/Http2ClientInitializer.java | 46 ++++++ .../client/Http2ClientResponseHandler.java | 128 +++++++++++++++++ .../http2/client/Http2SettingsHandler.java | 30 ++++ .../netty/http2/server/Http2Server.java | 59 ++++++++ .../server/Http2ServerResponseHandler.java | 52 +++++++ netty/src/main/resources/logback.xml | 13 ++ .../baeldung/netty/Http2ClientLiveTest.java | 91 ++++++++++++ pom.xml | 2 + 11 files changed, 596 insertions(+) create mode 100644 netty/README.md create mode 100644 netty/pom.xml create mode 100644 netty/src/main/java/com/baeldung/netty/http2/Http2Util.java create mode 100644 netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientInitializer.java create mode 100644 netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientResponseHandler.java create mode 100644 netty/src/main/java/com/baeldung/netty/http2/client/Http2SettingsHandler.java create mode 100644 netty/src/main/java/com/baeldung/netty/http2/server/Http2Server.java create mode 100644 netty/src/main/java/com/baeldung/netty/http2/server/Http2ServerResponseHandler.java create mode 100644 netty/src/main/resources/logback.xml create mode 100644 netty/src/test/java/com/baeldung/netty/Http2ClientLiveTest.java diff --git a/netty/README.md b/netty/README.md new file mode 100644 index 0000000000..b006c1c686 --- /dev/null +++ b/netty/README.md @@ -0,0 +1,6 @@ +## Netty + +This module contains articles about Netty. + +### Relevant Articles: + diff --git a/netty/pom.xml b/netty/pom.xml new file mode 100644 index 0000000000..1a33eef92e --- /dev/null +++ b/netty/pom.xml @@ -0,0 +1,34 @@ + + + 4.0.0 + netty + 0.0.1-SNAPSHOT + netty + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + io.netty + netty-all + ${netty.version} + + + + org.conscrypt + conscrypt-openjdk-uber + 2.4.0 + + + + + + 4.1.48.Final + + + \ No newline at end of file diff --git a/netty/src/main/java/com/baeldung/netty/http2/Http2Util.java b/netty/src/main/java/com/baeldung/netty/http2/Http2Util.java new file mode 100644 index 0000000000..62b6d4c4ed --- /dev/null +++ b/netty/src/main/java/com/baeldung/netty/http2/Http2Util.java @@ -0,0 +1,135 @@ +package com.baeldung.netty.http2; + +import static io.netty.handler.logging.LogLevel.INFO; + +import java.security.cert.CertificateException; + +import javax.net.ssl.SSLException; + +import com.baeldung.netty.http2.client.Http2ClientResponseHandler; +import com.baeldung.netty.http2.client.Http2SettingsHandler; +import com.baeldung.netty.http2.server.Http2ServerResponseHandler; + +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPipeline; +import io.netty.handler.codec.http.DefaultFullHttpRequest; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.HttpHeaderNames; +import io.netty.handler.codec.http.HttpHeaderValues; +import io.netty.handler.codec.http.HttpMethod; +import io.netty.handler.codec.http.HttpScheme; +import io.netty.handler.codec.http.HttpVersion; +import io.netty.handler.codec.http2.DefaultHttp2Connection; +import io.netty.handler.codec.http2.DelegatingDecompressorFrameListener; +import io.netty.handler.codec.http2.Http2Connection; +import io.netty.handler.codec.http2.Http2FrameCodecBuilder; +import io.netty.handler.codec.http2.Http2FrameLogger; +import io.netty.handler.codec.http2.Http2SecurityUtil; +import io.netty.handler.codec.http2.HttpConversionUtil; +import io.netty.handler.codec.http2.HttpToHttp2ConnectionHandler; +import io.netty.handler.codec.http2.HttpToHttp2ConnectionHandlerBuilder; +import io.netty.handler.codec.http2.InboundHttp2ToHttpAdapterBuilder; +import io.netty.handler.ssl.ApplicationProtocolConfig; +import io.netty.handler.ssl.ApplicationProtocolConfig.Protocol; +import io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior; +import io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior; +import io.netty.handler.ssl.ApplicationProtocolNames; +import io.netty.handler.ssl.ApplicationProtocolNegotiationHandler; +import io.netty.handler.ssl.SslContext; +import io.netty.handler.ssl.SslContextBuilder; +import io.netty.handler.ssl.SslProvider; +import io.netty.handler.ssl.SupportedCipherSuiteFilter; +import io.netty.handler.ssl.util.InsecureTrustManagerFactory; +import io.netty.handler.ssl.util.SelfSignedCertificate; + +public class Http2Util { + public static SslContext createSSLContext(boolean isServer) throws SSLException, CertificateException { + + SslContext sslCtx; + + SelfSignedCertificate ssc = new SelfSignedCertificate(); + + if (isServer) { + sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()) + .sslProvider(SslProvider.JDK) + .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) + .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN, + SelectorFailureBehavior.NO_ADVERTISE, + SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) + .build(); + } else { + sslCtx = SslContextBuilder.forClient() + .sslProvider(SslProvider.JDK) + .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) + .trustManager(InsecureTrustManagerFactory.INSTANCE) + .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN, + SelectorFailureBehavior.NO_ADVERTISE, + SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2)) + .build(); + } + return sslCtx; + + } + + public static ApplicationProtocolNegotiationHandler getServerAPNHandler() { + ApplicationProtocolNegotiationHandler serverAPNHandler = new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_2) { + + @Override + protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception { + if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { + ctx.pipeline() + .addLast(Http2FrameCodecBuilder.forServer() + .build(), new Http2ServerResponseHandler()); + return; + } + throw new IllegalStateException("Protocol: " + protocol + " not supported"); + } + }; + return serverAPNHandler; + + } + + public static ApplicationProtocolNegotiationHandler getClientAPNHandler(int maxContentLength, Http2SettingsHandler settingsHandler, Http2ClientResponseHandler responseHandler) { + final Http2FrameLogger logger = new Http2FrameLogger(INFO, Http2Util.class); + final Http2Connection connection = new DefaultHttp2Connection(false); + + HttpToHttp2ConnectionHandler connectionHandler = new HttpToHttp2ConnectionHandlerBuilder() + .frameListener(new DelegatingDecompressorFrameListener(connection, new InboundHttp2ToHttpAdapterBuilder(connection).maxContentLength(maxContentLength) + .propagateSettings(true) + .build())) + .frameLogger(logger) + .connection(connection) + .build(); + + ApplicationProtocolNegotiationHandler clientAPNHandler = new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_2) { + @Override + protected void configurePipeline(ChannelHandlerContext ctx, String protocol) { + if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { + ChannelPipeline p = ctx.pipeline(); + p.addLast(connectionHandler); + p.addLast(settingsHandler, responseHandler); + return; + } + ctx.close(); + throw new IllegalStateException("Protocol: " + protocol + " not supported"); + } + }; + + return clientAPNHandler; + + } + + public static FullHttpRequest createGetRequest(String host, int port) { + FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.valueOf("HTTP/2.0"), HttpMethod.GET, "/", Unpooled.EMPTY_BUFFER); + request.headers() + .add(HttpHeaderNames.HOST, new String(host + ":" + port)); + request.headers() + .add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), HttpScheme.HTTPS); + request.headers() + .add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); + request.headers() + .add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); + return request; + } +} diff --git a/netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientInitializer.java b/netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientInitializer.java new file mode 100644 index 0000000000..d50240fcb2 --- /dev/null +++ b/netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientInitializer.java @@ -0,0 +1,46 @@ +package com.baeldung.netty.http2.client; + +import com.baeldung.netty.http2.Http2Util; + +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelPipeline; +import io.netty.channel.socket.SocketChannel; +import io.netty.handler.ssl.SslContext; + +public class Http2ClientInitializer extends ChannelInitializer { + + private final SslContext sslCtx; + private final int maxContentLength; + private Http2SettingsHandler settingsHandler; + private Http2ClientResponseHandler responseHandler; + private String host; + private int port; + + public Http2ClientInitializer(SslContext sslCtx, int maxContentLength, String host, int port) { + this.sslCtx = sslCtx; + this.maxContentLength = maxContentLength; + this.host = host; + this.port = port; + } + + @Override + public void initChannel(SocketChannel ch) throws Exception { + + settingsHandler = new Http2SettingsHandler(ch.newPromise()); + responseHandler = new Http2ClientResponseHandler(); + + if (sslCtx != null) { + ChannelPipeline pipeline = ch.pipeline(); + pipeline.addLast(sslCtx.newHandler(ch.alloc(), host, port)); + pipeline.addLast(Http2Util.getClientAPNHandler(maxContentLength, settingsHandler, responseHandler)); + } + } + + public Http2SettingsHandler getSettingsHandler() { + return settingsHandler; + } + + public Http2ClientResponseHandler getResponseHandler() { + return responseHandler; + } +} diff --git a/netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientResponseHandler.java b/netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientResponseHandler.java new file mode 100644 index 0000000000..4e17155bbc --- /dev/null +++ b/netty/src/main/java/com/baeldung/netty/http2/client/Http2ClientResponseHandler.java @@ -0,0 +1,128 @@ +package com.baeldung.netty.http2.client; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.handler.codec.http.FullHttpResponse; +import io.netty.handler.codec.http2.HttpConversionUtil; +import io.netty.util.CharsetUtil; + +public class Http2ClientResponseHandler extends SimpleChannelInboundHandler { + + private final Logger logger = LoggerFactory.getLogger(Http2ClientResponseHandler.class); + private final Map streamidMap; + + public Http2ClientResponseHandler() { + streamidMap = new HashMap(); + } + + public MapValues put(int streamId, ChannelFuture writeFuture, ChannelPromise promise) { + return streamidMap.put(streamId, new MapValues(writeFuture, promise)); + } + + public String awaitResponses(long timeout, TimeUnit unit) { + + Iterator> itr = streamidMap.entrySet() + .iterator(); + + String response = null; + + while (itr.hasNext()) { + Entry entry = itr.next(); + ChannelFuture writeFuture = entry.getValue() + .getWriteFuture(); + + if (!writeFuture.awaitUninterruptibly(timeout, unit)) { + throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey()); + } + if (!writeFuture.isSuccess()) { + throw new RuntimeException(writeFuture.cause()); + } + ChannelPromise promise = entry.getValue() + .getPromise(); + + if (!promise.awaitUninterruptibly(timeout, unit)) { + throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey()); + } + if (!promise.isSuccess()) { + throw new RuntimeException(promise.cause()); + } + logger.info("---Stream id: " + entry.getKey() + " received---"); + response = entry.getValue().getResponse(); + + itr.remove(); + } + + return response; + + } + + @Override + protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { + Integer streamId = msg.headers() + .getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text()); + if (streamId == null) { + logger.error("HttpResponseHandler unexpected message received: " + msg); + return; + } + + MapValues value = streamidMap.get(streamId); + + if (value == null) { + logger.error("Message received for unknown stream id " + streamId); + ctx.close(); + } else { + ByteBuf content = msg.content(); + if (content.isReadable()) { + int contentLength = content.readableBytes(); + byte[] arr = new byte[contentLength]; + content.readBytes(arr); + String response = new String(arr, 0, contentLength, CharsetUtil.UTF_8); + logger.info("Response from Server: "+ (response)); + value.setResponse(response); + } + + value.getPromise() + .setSuccess(); + } + } + + public static class MapValues { + ChannelFuture writeFuture; + ChannelPromise promise; + String response; + + public String getResponse() { + return response; + } + + public void setResponse(String response) { + this.response = response; + } + + public MapValues(ChannelFuture writeFuture2, ChannelPromise promise2) { + this.writeFuture = writeFuture2; + this.promise = promise2; + } + + public ChannelFuture getWriteFuture() { + return writeFuture; + } + + public ChannelPromise getPromise() { + return promise; + } + + } +} diff --git a/netty/src/main/java/com/baeldung/netty/http2/client/Http2SettingsHandler.java b/netty/src/main/java/com/baeldung/netty/http2/client/Http2SettingsHandler.java new file mode 100644 index 0000000000..93841187c7 --- /dev/null +++ b/netty/src/main/java/com/baeldung/netty/http2/client/Http2SettingsHandler.java @@ -0,0 +1,30 @@ +package com.baeldung.netty.http2.client; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.handler.codec.http2.Http2Settings; + +import java.util.concurrent.TimeUnit; + +public class Http2SettingsHandler extends SimpleChannelInboundHandler { + private final ChannelPromise promise; + + public Http2SettingsHandler(ChannelPromise promise) { + this.promise = promise; + } + + public void awaitSettings(long timeout, TimeUnit unit) throws Exception { + if (!promise.awaitUninterruptibly(timeout, unit)) { + throw new IllegalStateException("Timed out waiting for settings"); + } + } + + @Override + protected void channelRead0(ChannelHandlerContext ctx, Http2Settings msg) throws Exception { + promise.setSuccess(); + + ctx.pipeline() + .remove(this); + } +} diff --git a/netty/src/main/java/com/baeldung/netty/http2/server/Http2Server.java b/netty/src/main/java/com/baeldung/netty/http2/server/Http2Server.java new file mode 100644 index 0000000000..a8e9e59953 --- /dev/null +++ b/netty/src/main/java/com/baeldung/netty/http2/server/Http2Server.java @@ -0,0 +1,59 @@ +package com.baeldung.netty.http2.server; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.netty.http2.Http2Util; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelOption; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.logging.LogLevel; +import io.netty.handler.logging.LoggingHandler; +import io.netty.handler.ssl.SslContext; + +public final class Http2Server { + + private static final int PORT = 8443; + private static final Logger logger = LoggerFactory.getLogger(Http2Server.class); + + public static void main(String[] args) throws Exception { + SslContext sslCtx = Http2Util.createSSLContext(true); + + EventLoopGroup group = new NioEventLoopGroup(); + try { + ServerBootstrap b = new ServerBootstrap(); + b.option(ChannelOption.SO_BACKLOG, 1024); + b.group(group) + .channel(NioServerSocketChannel.class) + .handler(new LoggingHandler(LogLevel.INFO)) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) throws Exception { + if (sslCtx != null) { + ch.pipeline() + .addLast(sslCtx.newHandler(ch.alloc()), Http2Util.getServerAPNHandler()); + } + } + + }); + + Channel ch = b.bind(PORT) + .sync() + .channel(); + + logger.info("HTTP/2 Server is listening on https://127.0.0.1:" + PORT + '/'); + + ch.closeFuture() + .sync(); + } finally { + group.shutdownGracefully(); + } + } + +} diff --git a/netty/src/main/java/com/baeldung/netty/http2/server/Http2ServerResponseHandler.java b/netty/src/main/java/com/baeldung/netty/http2/server/Http2ServerResponseHandler.java new file mode 100644 index 0000000000..24c66f15bb --- /dev/null +++ b/netty/src/main/java/com/baeldung/netty/http2/server/Http2ServerResponseHandler.java @@ -0,0 +1,52 @@ +package com.baeldung.netty.http2.server; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelHandler.Sharable; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.HttpResponseStatus; +import io.netty.handler.codec.http2.DefaultHttp2DataFrame; +import io.netty.handler.codec.http2.DefaultHttp2Headers; +import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame; +import io.netty.handler.codec.http2.Http2Headers; +import io.netty.handler.codec.http2.Http2HeadersFrame; +import io.netty.util.CharsetUtil; + +@Sharable +public class Http2ServerResponseHandler extends ChannelDuplexHandler { + + static final ByteBuf RESPONSE_BYTES = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8)); + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + super.exceptionCaught(ctx, cause); + cause.printStackTrace(); + ctx.close(); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + if (msg instanceof Http2HeadersFrame) { + Http2HeadersFrame msgHeader = (Http2HeadersFrame) msg; + if (msgHeader.isEndStream()) { + ByteBuf content = ctx.alloc() + .buffer(); + content.writeBytes(RESPONSE_BYTES.duplicate()); + + Http2Headers headers = new DefaultHttp2Headers().status(HttpResponseStatus.OK.codeAsText()); + ctx.write(new DefaultHttp2HeadersFrame(headers).stream(msgHeader.stream())); + ctx.write(new DefaultHttp2DataFrame(content, true).stream(msgHeader.stream())); + } + + } else { + super.channelRead(ctx, msg); + } + } + + @Override + public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { + ctx.flush(); + } + +} diff --git a/netty/src/main/resources/logback.xml b/netty/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/netty/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/netty/src/test/java/com/baeldung/netty/Http2ClientLiveTest.java b/netty/src/test/java/com/baeldung/netty/Http2ClientLiveTest.java new file mode 100644 index 0000000000..6b9a53a1b3 --- /dev/null +++ b/netty/src/test/java/com/baeldung/netty/Http2ClientLiveTest.java @@ -0,0 +1,91 @@ +package com.baeldung.netty; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.netty.http2.Http2Util; +import com.baeldung.netty.http2.client.Http2ClientInitializer; +import com.baeldung.netty.http2.client.Http2ClientResponseHandler; +import com.baeldung.netty.http2.client.Http2SettingsHandler; + +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelOption; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.ssl.SslContext; + +//Ensure the server class - Http2Server.java is already started before running this test +public class Http2ClientLiveTest { + + private static final Logger logger = LoggerFactory.getLogger(Http2ClientLiveTest.class); + + private static final String HOST = "127.0.0.1"; + private static final int PORT = 8443; + private SslContext sslCtx; + private Channel channel; + + @Before + public void setup() throws Exception { + sslCtx = Http2Util.createSSLContext(false); + } + + @Test + public void whenRequestSent_thenHelloWorldReceived() throws Exception { + + EventLoopGroup workerGroup = new NioEventLoopGroup(); + Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE, HOST, PORT); + + try { + Bootstrap b = new Bootstrap(); + b.group(workerGroup); + b.channel(NioSocketChannel.class); + b.option(ChannelOption.SO_KEEPALIVE, true); + b.remoteAddress(HOST, PORT); + b.handler(initializer); + + channel = b.connect() + .syncUninterruptibly() + .channel(); + + logger.info("Connected to [" + HOST + ':' + PORT + ']'); + + Http2SettingsHandler http2SettingsHandler = initializer.getSettingsHandler(); + http2SettingsHandler.awaitSettings(60, TimeUnit.SECONDS); + + logger.info("Sending request(s)..."); + + FullHttpRequest request = Http2Util.createGetRequest(HOST, PORT); + + Http2ClientResponseHandler responseHandler = initializer.getResponseHandler(); + int streamId = 3; + + responseHandler.put(streamId, channel.write(request), channel.newPromise()); + channel.flush(); + String response = responseHandler.awaitResponses(60, TimeUnit.SECONDS); + + assertEquals("Hello World", response); + + logger.info("Finished HTTP/2 request(s)"); + + } finally { + workerGroup.shutdownGracefully(); + } + + } + + @After + public void cleanup() { + channel.close() + .syncUninterruptibly(); + } +} diff --git a/pom.xml b/pom.xml index e21c13efc2..5602e807b9 100644 --- a/pom.xml +++ b/pom.xml @@ -536,6 +536,7 @@ mybatis netflix-modules + ninja open-liberty @@ -1047,6 +1048,7 @@ mybatis netflix-modules + ninja open-liberty From f9ac384b8567a06c65e7b1e47c3ec2c3026a8dda Mon Sep 17 00:00:00 2001 From: Sam Millington Date: Wed, 8 Apr 2020 18:40:34 +0100 Subject: [PATCH 58/59] Added BAEL-3604 code (#9020) * Added BAEL-3604 code --- .../core-java-security-2/pom.xml | 11 ++++ .../com/baeldung/checksums/ChecksumUtils.java | 23 +++++++++ .../checksums/ChecksumUtilsUnitTest.java | 51 +++++++++++++++++++ 3 files changed, 85 insertions(+) create mode 100644 core-java-modules/core-java-security-2/src/main/java/com/baeldung/checksums/ChecksumUtils.java create mode 100644 core-java-modules/core-java-security-2/src/test/java/com/baeldung/checksums/ChecksumUtilsUnitTest.java diff --git a/core-java-modules/core-java-security-2/pom.xml b/core-java-modules/core-java-security-2/pom.xml index 9315ab4af2..5db3b67c04 100644 --- a/core-java-modules/core-java-security-2/pom.xml +++ b/core-java-modules/core-java-security-2/pom.xml @@ -17,6 +17,7 @@ + commons-codec commons-codec @@ -36,6 +37,15 @@ ${assertj-core.version} test + + + + javax.xml.bind + jaxb-api + 2.3.1 + + + @@ -46,4 +56,5 @@ 3.10.0 + diff --git a/core-java-modules/core-java-security-2/src/main/java/com/baeldung/checksums/ChecksumUtils.java b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/checksums/ChecksumUtils.java new file mode 100644 index 0000000000..d214a0f757 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/main/java/com/baeldung/checksums/ChecksumUtils.java @@ -0,0 +1,23 @@ +package com.baeldung.checksums; + +import java.io.IOException; +import java.io.InputStream; +import java.util.zip.CRC32; +import java.util.zip.CheckedInputStream; +import java.util.zip.Checksum; + +public class ChecksumUtils { + + public static long getChecksumCRC32(byte[] bytes) { + Checksum crc32 = new CRC32(); + crc32.update(bytes, 0, bytes.length); + return crc32.getValue(); + } + + public static long getChecksumCRC32(InputStream stream, int bufferSize) throws IOException { + CheckedInputStream checkedInputStream = new CheckedInputStream(stream, new CRC32()); + byte[] buffer = new byte[bufferSize]; + while (checkedInputStream.read(buffer, 0, buffer.length) >= 0) {} + return checkedInputStream.getChecksum().getValue(); + } +} diff --git a/core-java-modules/core-java-security-2/src/test/java/com/baeldung/checksums/ChecksumUtilsUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/checksums/ChecksumUtilsUnitTest.java new file mode 100644 index 0000000000..f5366917f6 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/checksums/ChecksumUtilsUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.checksums; + + +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +import static org.junit.jupiter.api.Assertions.*; + +class ChecksumUtilsUnitTest { + + byte[] arr; + + @Before + void setUp() { + arr = new byte[]{0,10,21,20,35,40,120,56,72,22}; + } + + @Test + void givenByteArray_whenChecksumCreated_checkCorrect() { + + long checksum = ChecksumUtils.getChecksumCRC32(arr); + + assertEquals(3915397664L, checksum); + } + + @Test + void givenTwoDifferentStrings_whenChecksumCreated_checkCollision() { + + String plumless = "plumless"; + String buckeroo = "buckeroo"; + + long plumlessChecksum = ChecksumUtils.getChecksumCRC32(plumless.getBytes()); + long buckerooChecksum = ChecksumUtils.getChecksumCRC32(buckeroo.getBytes()); + + assertEquals(plumlessChecksum, buckerooChecksum); + } + + @Test + void givenInputString_whenChecksumCreated_checkCorrect() throws IOException { + + InputStream inputStream = new ByteArrayInputStream(arr); + long checksum = ChecksumUtils.getChecksumCRC32(inputStream, 10); + + assertEquals(3915397664L, checksum); + + } +} \ No newline at end of file From 88cc732dc7bfffba9f086bd0d77f0487b56bd0bb Mon Sep 17 00:00:00 2001 From: Catalin Burcea Date: Thu, 9 Apr 2020 10:30:04 +0300 Subject: [PATCH 59/59] BAEL-3649 Quick Guide to Spring Cloud Circuit Breaker (#8819) --- .../spring-cloud-circuit-breaker/README.md | 5 ++ .../spring-cloud-circuit-breaker/pom.xml | 55 ++++++++++++++ .../baeldung/circuitbreaker/AlbumService.java | 40 +++++++++++ .../baeldung/circuitbreaker/Controller.java | 18 +++++ .../baeldung/circuitbreaker/SpringApp.java | 71 +++++++++++++++++++ .../main/resources/fallback-album-list.json | 12 ++++ 6 files changed, 201 insertions(+) create mode 100644 spring-cloud/spring-cloud-circuit-breaker/README.md create mode 100644 spring-cloud/spring-cloud-circuit-breaker/pom.xml create mode 100644 spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/AlbumService.java create mode 100644 spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/Controller.java create mode 100644 spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/SpringApp.java create mode 100644 spring-cloud/spring-cloud-circuit-breaker/src/main/resources/fallback-album-list.json diff --git a/spring-cloud/spring-cloud-circuit-breaker/README.md b/spring-cloud/spring-cloud-circuit-breaker/README.md new file mode 100644 index 0000000000..040eb0ccee --- /dev/null +++ b/spring-cloud/spring-cloud-circuit-breaker/README.md @@ -0,0 +1,5 @@ +## Spring Cloud Circuit Breaker + +This module contains articles about Spring Cloud Circuit Breaker + +### Relevant Articles: diff --git a/spring-cloud/spring-cloud-circuit-breaker/pom.xml b/spring-cloud/spring-cloud-circuit-breaker/pom.xml new file mode 100644 index 0000000000..188fc4bf8e --- /dev/null +++ b/spring-cloud/spring-cloud-circuit-breaker/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + spring-cloud-circuit-breaker + spring-cloud-gateway + jar + + + com.baeldung.spring.cloud + spring-cloud + 1.0.0-SNAPSHOT + .. + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/libs-snapshot + + true + + + false + + + + + + + + org.springframework.boot + spring-boot-dependencies + 2.2.4.RELEASE + pom + import + + + + + + + org.springframework.cloud + spring-cloud-starter-circuitbreaker-resilience4j + 1.0.2.RELEASE + + + org.springframework.boot + spring-boot-starter-web + + + + diff --git a/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/AlbumService.java b/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/AlbumService.java new file mode 100644 index 0000000000..67163c8c9a --- /dev/null +++ b/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/AlbumService.java @@ -0,0 +1,40 @@ +package com.baeldung.circuitbreaker; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.circuitbreaker.CircuitBreaker; +import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import java.nio.file.Files; +import java.nio.file.Paths; + +@Service +public class AlbumService { + + private static final Logger LOGGER = LoggerFactory.getLogger(AlbumService.class); + + @Autowired + private CircuitBreakerFactory circuitBreakerFactory; + + private RestTemplate restTemplate = new RestTemplate(); + + public String getAlbumList() { + CircuitBreaker circuitBreaker = circuitBreakerFactory.create("circuitbreaker"); + String url = "https://jsonplaceholder.typicode.com/albums"; + + return circuitBreaker.run(() -> restTemplate.getForObject(url, String.class), throwable -> getDefaultAlbumList()); + } + + private String getDefaultAlbumList() { + try { + return new String(Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource("fallback-album-list.json").toURI()))); + } catch (Exception e) { + LOGGER.error("error occurred while reading the file", e); + } + return null; + } + +} diff --git a/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/Controller.java b/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/Controller.java new file mode 100644 index 0000000000..10f7c57a7a --- /dev/null +++ b/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/Controller.java @@ -0,0 +1,18 @@ +package com.baeldung.circuitbreaker; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class Controller { + + @Autowired + private AlbumService service; + + @GetMapping("/albums") + public String albums() { + return service.getAlbumList(); + } + +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/SpringApp.java b/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/SpringApp.java new file mode 100644 index 0000000000..f891e7693f --- /dev/null +++ b/spring-cloud/spring-cloud-circuit-breaker/src/main/java/com/baeldung/circuitbreaker/SpringApp.java @@ -0,0 +1,71 @@ +package com.baeldung.circuitbreaker; + +import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig; +import io.github.resilience4j.timelimiter.TimeLimiterConfig; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JCircuitBreakerFactory; +import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder; +import org.springframework.cloud.client.circuitbreaker.Customizer; +import org.springframework.context.annotation.Bean; + +import java.time.Duration; + +@SpringBootApplication +public class SpringApp { + + public static void main(String[] args) { + SpringApplication.run(SpringApp.class, args); + } + + @Bean + public Customizer globalCustomConfiguration() { + TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom() + .timeoutDuration(Duration.ofSeconds(4)) + .build(); + CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom() + .failureRateThreshold(50) + .waitDurationInOpenState(Duration.ofMillis(1000)) + .slidingWindowSize(2) + .build(); + + return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id) + .timeLimiterConfig(timeLimiterConfig) + .circuitBreakerConfig(circuitBreakerConfig) + .build()); + } + + @Bean + public Customizer specificCustomConfiguration1() { + + TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom() + .timeoutDuration(Duration.ofSeconds(4)) + .build(); + CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom() + .failureRateThreshold(50) + .waitDurationInOpenState(Duration.ofMillis(1000)) + .slidingWindowSize(2) + .build(); + + return factory -> factory.configure(builder -> builder.circuitBreakerConfig(circuitBreakerConfig) + .timeLimiterConfig(timeLimiterConfig).build(), "circuitBreaker"); + } + + @Bean + public Customizer specificCustomConfiguration2() { + + TimeLimiterConfig timeLimiterConfig = TimeLimiterConfig.custom() + .timeoutDuration(Duration.ofSeconds(4)) + .build(); + CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom() + .failureRateThreshold(50) + .waitDurationInOpenState(Duration.ofMillis(1000)) + .slidingWindowSize(2) + .build(); + + return factory -> factory.configure(builder -> builder.circuitBreakerConfig(circuitBreakerConfig) + .timeLimiterConfig(timeLimiterConfig).build(), + "circuitBreaker1", "circuitBreaker2", "circuitBreaker3"); + } + +} diff --git a/spring-cloud/spring-cloud-circuit-breaker/src/main/resources/fallback-album-list.json b/spring-cloud/spring-cloud-circuit-breaker/src/main/resources/fallback-album-list.json new file mode 100644 index 0000000000..001df7610a --- /dev/null +++ b/spring-cloud/spring-cloud-circuit-breaker/src/main/resources/fallback-album-list.json @@ -0,0 +1,12 @@ +[ + { + "userId": 1, + "id": 1, + "title": "quidem molestiae enim" + }, + { + "userId": 1, + "id": 2, + "title": "sunt qui excepturi placeat culpa" + } +] \ No newline at end of file