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 001/187] 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 002/187] 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 003/187] 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 004/187] 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 005/187] 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 006/187] 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 007/187] 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 008/187] 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 009/187] 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 010/187] 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 2eded212580b3e810a79561a3adc227f633bc8ec Mon Sep 17 00:00:00 2001 From: Vikas Ramsingh Rajput Date: Sat, 14 Mar 2020 23:17:58 +0300 Subject: [PATCH 011/187] BAEL-3832: Difference between BeanFactory and ApplicationContext completed --- spring-core-3/pom.xml | 7 + .../bean/CustomBeanFactoryPostProcessor.java | 16 ++ .../bean/CustomBeanPostProcessor.java | 17 +++ .../baeldung/ioccontainer/bean/Student.java | 12 ++ .../ioccontainer/IOCContainerAppTest.java | 137 ++++++++++++++++++ .../ioc-container-difference-example.xml | 11 ++ 6 files changed, 200 insertions(+) create mode 100644 spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java create mode 100644 spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java create mode 100644 spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java create mode 100644 spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppTest.java create mode 100644 spring-core-3/src/test/resources/ioc-container-difference-example.xml diff --git a/spring-core-3/pom.xml b/spring-core-3/pom.xml index 205259e8e4..d1163a174c 100644 --- a/spring-core-3/pom.xml +++ b/spring-core-3/pom.xml @@ -67,6 +67,12 @@ ${junit-jupiter.version} test + + + log4j + log4j + ${log4j.version} + @@ -83,6 +89,7 @@ 2.22.1 1.3.2 2.2.2.RELEASE + 1.2.17 \ No newline at end of file diff --git a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java new file mode 100644 index 0000000000..d6e2c92144 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java @@ -0,0 +1,16 @@ +package com.baeldung.ioccontainer.bean; + +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; + +public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor { + static final Logger LOGGER = LogManager.getLogger(CustomBeanPostProcessor.class.getName()); + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + LOGGER.info("BeanFactoryPostProcessor is Registered"); + } +} diff --git a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java new file mode 100644 index 0000000000..bf34453388 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java @@ -0,0 +1,17 @@ +package com.baeldung.ioccontainer.bean; + +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.BeanPostProcessor; + +public class CustomBeanPostProcessor implements BeanPostProcessor { + + static final Logger LOGGER = LogManager.getLogger(CustomBeanPostProcessor.class.getName()); + + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + LOGGER.info("BeanPostProcessor is Registered Before Initialization"); + return bean; + } + +} diff --git a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java new file mode 100644 index 0000000000..e32b4ecc29 --- /dev/null +++ b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java @@ -0,0 +1,12 @@ +package com.baeldung.ioccontainer.bean; + +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; + +public class Student { + static final Logger LOGGER = LogManager.getLogger(Student.class.getName()); + + public void postConstruct() { + LOGGER.info("Student Bean is initialized"); + } +} diff --git a/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppTest.java b/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppTest.java new file mode 100644 index 0000000000..b97aa08f80 --- /dev/null +++ b/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppTest.java @@ -0,0 +1,137 @@ +package com.baeldung.ioccontainer; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.Logger; +import org.apache.log4j.spi.LoggingEvent; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.xml.XmlBeanFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +import com.baeldung.ioccontainer.bean.CustomBeanFactoryPostProcessor; +import com.baeldung.ioccontainer.bean.CustomBeanPostProcessor; +import com.baeldung.ioccontainer.bean.Student; + +public class IOCContainerAppTest { + + private LogAppender logAppender; + private List loggingEvents; + + @BeforeEach + public void initializeLogAppender() { + logAppender = new LogAppender(); + Logger.getRootLogger() + .addAppender(logAppender); + loggingEvents = logAppender.events; + } + + @AfterEach + public void removeLogAppender() { + Logger.getRootLogger() + .removeAppender(logAppender); + } + + @Test + public void whenBFInitialized_thenNoStudentLogPrinted() { + Resource res = new ClassPathResource("ioc-container-difference-example.xml"); + BeanFactory factory = new XmlBeanFactory(res); + + String expected = "Student Bean is initialized"; + assertFalse(checkWhetherLoggerContains(expected)); + } + + @Test + public void whenBFInitialized_thenStudentLogPrinted() { + + Resource res = new ClassPathResource("ioc-container-difference-example.xml"); + BeanFactory factory = new XmlBeanFactory(res); + Student student = (Student) factory.getBean("student"); + + String expected = "Student Bean is initialized"; + assertTrue(checkWhetherLoggerContains(expected)); + } + + @Test + public void whenAppContInitialized_thenStudentObjInitialized() { + ApplicationContext context = new ClassPathXmlApplicationContext("ioc-container-difference-example.xml"); + + String expected = "Student Bean is initialized"; + assertTrue(checkWhetherLoggerContains(expected)); + } + + @Test + public void whenBFInitialized_thenBFPProcessorAndBPProcessorNotRegAutomatically() { + Resource res = new ClassPathResource("ioc-container-difference-example.xml"); + ConfigurableListableBeanFactory factory = new XmlBeanFactory(res); + + String beanFactoryPostProcessorExpectedLog = "BeanFactoryPostProcessor is Registered"; + assertFalse(checkWhetherLoggerContains(beanFactoryPostProcessorExpectedLog)); + + String beanPostProcessorExpectedLog = "BeanPostProcessor is Registered Before Initialization"; + assertFalse(checkWhetherLoggerContains(beanPostProcessorExpectedLog)); + } + + @Test + public void whenAppContInitialized_thenBFPostProcessorAndBPostProcessorRegisteredAutomatically() { + ApplicationContext context = new ClassPathXmlApplicationContext("ioc-container-difference-example.xml"); + + String beanFactoryPostProcessorExpectedLog = "BeanFactoryPostProcessor is Registered"; + assertTrue(checkWhetherLoggerContains(beanFactoryPostProcessorExpectedLog)); + + String beanPostProcessorExpectedLog = "BeanPostProcessor is Registered Before Initialization"; + assertTrue(checkWhetherLoggerContains(beanPostProcessorExpectedLog)); + } + + @Test + public void whenBFPostProcessorAndBPProcessorRegisteredManually_thenReturnTrue() { + Resource res = new ClassPathResource("ioc-container-difference-example.xml"); + ConfigurableListableBeanFactory factory = new XmlBeanFactory(res); + + CustomBeanFactoryPostProcessor beanFactoryPostProcessor = new CustomBeanFactoryPostProcessor(); + beanFactoryPostProcessor.postProcessBeanFactory(factory); + String beanFactoryPostProcessorExpectedLog = "BeanFactoryPostProcessor is Registered"; + assertTrue(checkWhetherLoggerContains(beanFactoryPostProcessorExpectedLog)); + + CustomBeanPostProcessor beanPostProcessor = new CustomBeanPostProcessor(); + factory.addBeanPostProcessor(beanPostProcessor); + Student student = (Student) factory.getBean("student"); + String beanPostProcessorExpectedLog = "BeanPostProcessor is Registered Before Initialization"; + assertTrue(checkWhetherLoggerContains(beanPostProcessorExpectedLog)); + } + + private boolean checkWhetherLoggerContains(String expectedLogMessge) { + boolean isLogExist = loggingEvents.stream() + .anyMatch(logEvent -> logEvent.getMessage() + .equals(expectedLogMessge)); + return isLogExist; + } + + public static class LogAppender extends AppenderSkeleton { + public List events = new ArrayList(); + + public void close() { + } + + public boolean requiresLayout() { + return false; + } + + @Override + protected void append(LoggingEvent event) { + events.add(event); + } + + } +} diff --git a/spring-core-3/src/test/resources/ioc-container-difference-example.xml b/spring-core-3/src/test/resources/ioc-container-difference-example.xml new file mode 100644 index 0000000000..9bb01efe66 --- /dev/null +++ b/spring-core-3/src/test/resources/ioc-container-difference-example.xml @@ -0,0 +1,11 @@ + + + + + + + + \ No newline at end of file From 5ad0170cb6423a462d1f7d685ff51c8b8992ede0 Mon Sep 17 00:00:00 2001 From: Vikas Ramsingh Rajput Date: Sun, 15 Mar 2020 10:04:16 +0300 Subject: [PATCH 012/187] BAEL-3832: renamed the unit test case as per the naming convention --- .../{IOCContainerAppTest.java => IOCContainerAppUnitTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename spring-core-3/src/test/java/com/baeldung/ioccontainer/{IOCContainerAppTest.java => IOCContainerAppUnitTest.java} (99%) diff --git a/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppTest.java b/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java similarity index 99% rename from spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppTest.java rename to spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java index b97aa08f80..66b6842d0f 100644 --- a/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppTest.java +++ b/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java @@ -24,7 +24,7 @@ import com.baeldung.ioccontainer.bean.CustomBeanFactoryPostProcessor; import com.baeldung.ioccontainer.bean.CustomBeanPostProcessor; import com.baeldung.ioccontainer.bean.Student; -public class IOCContainerAppTest { +public class IOCContainerAppUnitTest { private LogAppender logAppender; private List loggingEvents; From 2c0cf3e2e02de86f36e65212248f8625657c8c28 Mon Sep 17 00:00:00 2001 From: mike b Date: Sun, 15 Mar 2020 14:14:46 -0400 Subject: [PATCH 013/187] [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 014/187] 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 015/187] [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_0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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 2dd0e5001b744b5902cc8e1478d1f325a8777837 Mon Sep 17 00:00:00 2001 From: Vikas Ramsingh Rajput Date: Wed, 18 Mar 2020 19:59:02 +0300 Subject: [PATCH 016/187] BAEL-3832: Removed logger checks from the test cases --- .../bean/CustomBeanFactoryPostProcessor.java | 8 +- .../bean/CustomBeanPostProcessor.java | 11 +-- .../baeldung/ioccontainer/bean/Student.java | 7 +- .../ioccontainer/IOCContainerAppUnitTest.java | 91 +++++-------------- 4 files changed, 30 insertions(+), 87 deletions(-) diff --git a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java index d6e2c92144..fe773ce2df 100644 --- a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java +++ b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java @@ -1,16 +1,14 @@ package com.baeldung.ioccontainer.bean; -import org.apache.log4j.LogManager; -import org.apache.log4j.Logger; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor { - static final Logger LOGGER = LogManager.getLogger(CustomBeanPostProcessor.class.getName()); - + public static boolean isBeanInstantiated = false; + @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { - LOGGER.info("BeanFactoryPostProcessor is Registered"); + isBeanInstantiated = true; } } diff --git a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java index bf34453388..1c2e011a6c 100644 --- a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java +++ b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java @@ -1,17 +1,14 @@ package com.baeldung.ioccontainer.bean; -import org.apache.log4j.LogManager; -import org.apache.log4j.Logger; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; public class CustomBeanPostProcessor implements BeanPostProcessor { - - static final Logger LOGGER = LogManager.getLogger(CustomBeanPostProcessor.class.getName()); - + public static boolean isBeanInstantiated = false; + + @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - LOGGER.info("BeanPostProcessor is Registered Before Initialization"); + isBeanInstantiated = true; return bean; } - } diff --git a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java index e32b4ecc29..03e0b049ba 100644 --- a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java +++ b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java @@ -1,12 +1,9 @@ package com.baeldung.ioccontainer.bean; -import org.apache.log4j.LogManager; -import org.apache.log4j.Logger; - public class Student { - static final Logger LOGGER = LogManager.getLogger(Student.class.getName()); + public static boolean isBeanInstantiated = false; public void postConstruct() { - LOGGER.info("Student Bean is initialized"); + isBeanInstantiated = true; } } diff --git a/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java b/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java index 66b6842d0f..3c0a5b3dbe 100644 --- a/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java +++ b/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java @@ -3,12 +3,6 @@ package com.baeldung.ioccontainer; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.AppenderSkeleton; -import org.apache.log4j.Logger; -import org.apache.log4j.spi.LoggingEvent; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -26,49 +20,37 @@ import com.baeldung.ioccontainer.bean.Student; public class IOCContainerAppUnitTest { - private LogAppender logAppender; - private List loggingEvents; - @BeforeEach - public void initializeLogAppender() { - logAppender = new LogAppender(); - Logger.getRootLogger() - .addAppender(logAppender); - loggingEvents = logAppender.events; - } - @AfterEach - public void removeLogAppender() { - Logger.getRootLogger() - .removeAppender(logAppender); + public void resetInstantiationFlag() { + Student.isBeanInstantiated = false; + CustomBeanPostProcessor.isBeanInstantiated = false; + CustomBeanFactoryPostProcessor.isBeanInstantiated = false; } @Test - public void whenBFInitialized_thenNoStudentLogPrinted() { + public void whenBFInitialized_thenStudentNotInitialized() { Resource res = new ClassPathResource("ioc-container-difference-example.xml"); BeanFactory factory = new XmlBeanFactory(res); - - String expected = "Student Bean is initialized"; - assertFalse(checkWhetherLoggerContains(expected)); + + assertFalse(Student.isBeanInstantiated); } @Test - public void whenBFInitialized_thenStudentLogPrinted() { - + public void whenBFInitialized_thenStudentInitialized() { + Resource res = new ClassPathResource("ioc-container-difference-example.xml"); BeanFactory factory = new XmlBeanFactory(res); Student student = (Student) factory.getBean("student"); - - String expected = "Student Bean is initialized"; - assertTrue(checkWhetherLoggerContains(expected)); + + assertTrue(Student.isBeanInstantiated); } - + @Test - public void whenAppContInitialized_thenStudentObjInitialized() { + public void whenAppContInitialized_thenStudentInitialized() { ApplicationContext context = new ClassPathXmlApplicationContext("ioc-container-difference-example.xml"); - - String expected = "Student Bean is initialized"; - assertTrue(checkWhetherLoggerContains(expected)); + + assertTrue(Student.isBeanInstantiated); } @Test @@ -76,22 +58,16 @@ public class IOCContainerAppUnitTest { Resource res = new ClassPathResource("ioc-container-difference-example.xml"); ConfigurableListableBeanFactory factory = new XmlBeanFactory(res); - String beanFactoryPostProcessorExpectedLog = "BeanFactoryPostProcessor is Registered"; - assertFalse(checkWhetherLoggerContains(beanFactoryPostProcessorExpectedLog)); - - String beanPostProcessorExpectedLog = "BeanPostProcessor is Registered Before Initialization"; - assertFalse(checkWhetherLoggerContains(beanPostProcessorExpectedLog)); + assertFalse(CustomBeanFactoryPostProcessor.isBeanInstantiated); + assertFalse(CustomBeanPostProcessor.isBeanInstantiated); } @Test public void whenAppContInitialized_thenBFPostProcessorAndBPostProcessorRegisteredAutomatically() { ApplicationContext context = new ClassPathXmlApplicationContext("ioc-container-difference-example.xml"); - String beanFactoryPostProcessorExpectedLog = "BeanFactoryPostProcessor is Registered"; - assertTrue(checkWhetherLoggerContains(beanFactoryPostProcessorExpectedLog)); - - String beanPostProcessorExpectedLog = "BeanPostProcessor is Registered Before Initialization"; - assertTrue(checkWhetherLoggerContains(beanPostProcessorExpectedLog)); + assertTrue(CustomBeanFactoryPostProcessor.isBeanInstantiated); + assertTrue(CustomBeanPostProcessor.isBeanInstantiated); } @Test @@ -101,37 +77,12 @@ public class IOCContainerAppUnitTest { CustomBeanFactoryPostProcessor beanFactoryPostProcessor = new CustomBeanFactoryPostProcessor(); beanFactoryPostProcessor.postProcessBeanFactory(factory); - String beanFactoryPostProcessorExpectedLog = "BeanFactoryPostProcessor is Registered"; - assertTrue(checkWhetherLoggerContains(beanFactoryPostProcessorExpectedLog)); + assertTrue(CustomBeanFactoryPostProcessor.isBeanInstantiated); CustomBeanPostProcessor beanPostProcessor = new CustomBeanPostProcessor(); factory.addBeanPostProcessor(beanPostProcessor); Student student = (Student) factory.getBean("student"); - String beanPostProcessorExpectedLog = "BeanPostProcessor is Registered Before Initialization"; - assertTrue(checkWhetherLoggerContains(beanPostProcessorExpectedLog)); + assertTrue(CustomBeanPostProcessor.isBeanInstantiated); } - private boolean checkWhetherLoggerContains(String expectedLogMessge) { - boolean isLogExist = loggingEvents.stream() - .anyMatch(logEvent -> logEvent.getMessage() - .equals(expectedLogMessge)); - return isLogExist; - } - - public static class LogAppender extends AppenderSkeleton { - public List events = new ArrayList(); - - public void close() { - } - - public boolean requiresLayout() { - return false; - } - - @Override - protected void append(LoggingEvent event) { - events.add(event); - } - - } } From cd23dbda280c7bd07a639c6d1d96151261633713 Mon Sep 17 00:00:00 2001 From: Vikas Ramsingh Rajput Date: Wed, 18 Mar 2020 20:53:30 +0300 Subject: [PATCH 017/187] BAEL-3832: Removed log4j dependency from the pom.xml and formatted the configuration xml file --- spring-core-3/pom.xml | 6 ------ .../src/test/resources/ioc-container-difference-example.xml | 3 +-- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/spring-core-3/pom.xml b/spring-core-3/pom.xml index d1163a174c..3bde25f561 100644 --- a/spring-core-3/pom.xml +++ b/spring-core-3/pom.xml @@ -68,11 +68,6 @@ test - - log4j - log4j - ${log4j.version} - @@ -89,7 +84,6 @@ 2.22.1 1.3.2 2.2.2.RELEASE - 1.2.17 \ No newline at end of file diff --git a/spring-core-3/src/test/resources/ioc-container-difference-example.xml b/spring-core-3/src/test/resources/ioc-container-difference-example.xml index 9bb01efe66..ba84aa635d 100644 --- a/spring-core-3/src/test/resources/ioc-container-difference-example.xml +++ b/spring-core-3/src/test/resources/ioc-container-difference-example.xml @@ -5,7 +5,6 @@ http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> - - + \ No newline at end of file From f82ce12686f40e896106fb3bc3f0367ed6de386b Mon Sep 17 00:00:00 2001 From: Vikas Ramsingh Rajput Date: Wed, 18 Mar 2020 20:56:04 +0300 Subject: [PATCH 018/187] BAEL-3832: removed unnecessary line from pom.xml --- spring-core-3/pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-core-3/pom.xml b/spring-core-3/pom.xml index 3bde25f561..205259e8e4 100644 --- a/spring-core-3/pom.xml +++ b/spring-core-3/pom.xml @@ -67,7 +67,6 @@ ${junit-jupiter.version} test - From 2261dd80d44ccea40fefc212930c5eb133a5fc49 Mon Sep 17 00:00:00 2001 From: Donato Rimenti Date: Wed, 18 Mar 2020 10:34:00 +0100 Subject: [PATCH 019/187] [JAVA-22] Moved articles not in ebook from spring-boot-rest to spring-boot-mvc-2 --- .../spring-boot-mvc-2/README.md | 4 + spring-boot-modules/spring-boot-mvc-2/pom.xml | 22 +++ .../src/main/java/com/baeldung/etag/Foo.java | 95 +++++++++ .../java/com/baeldung/etag/FooController.java | 58 ++++++ .../main/java/com/baeldung/etag/FooDao.java | 8 + .../etag/SpringBootEtagApplication.java | 13 ++ .../java/com/baeldung/etag/WebConfig.java | 28 +++ .../SpringBootStudentsApplication.java | 13 ++ .../java/com/baeldung/students/Student.java | 53 ++++++ .../baeldung/students/StudentController.java | 74 +++++++ .../com/baeldung/students/StudentService.java | 51 +++++ .../src/main/resources/WEB-INF/web.xml | 18 ++ .../foo_API_test.postman_collection.json | 180 ++++++++++++++++++ .../baeldung/etag/EtagIntegrationTest.java | 123 ++++++++++++ .../java/com/baeldung/mime/FooLiveTest.java | 82 ++++++++ .../java/com/baeldung/mime/IMarshaller.java | 15 ++ .../com/baeldung/mime/JacksonMarshaller.java | 75 ++++++++ .../baeldung/mime/TestMarshallerFactory.java | 48 +++++ .../com/baeldung/mime/XStreamMarshaller.java | 46 +++++ .../StudentControllerIntegrationTest.java | 73 +++++++ spring-boot-rest/README.md | 6 +- 21 files changed, 1080 insertions(+), 5 deletions(-) create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/Foo.java create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooController.java create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooDao.java create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/WebConfig.java create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/SpringBootStudentsApplication.java create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/Student.java create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentController.java create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentService.java create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/main/resources/WEB-INF/web.xml create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/main/resources/foo_API_test.postman_collection.json create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/etag/EtagIntegrationTest.java create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/IMarshaller.java create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/JacksonMarshaller.java create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/TestMarshallerFactory.java create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/XStreamMarshaller.java create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/students/StudentControllerIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-mvc-2/README.md b/spring-boot-modules/spring-boot-mvc-2/README.md index dc6a136131..d7341cca35 100644 --- a/spring-boot-modules/spring-boot-mvc-2/README.md +++ b/spring-boot-modules/spring-boot-mvc-2/README.md @@ -6,4 +6,8 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [Functional Controllers in Spring MVC](https://www.baeldung.com/spring-mvc-functional-controllers) - [Specify an Array of Strings as Body Parameters in Swagger](https://www.baeldung.com/swagger-body-array-of-strings) +- [ETags for REST with Spring](https://www.baeldung.com/etags-for-rest-with-spring) +- [Testing REST with multiple MIME types](https://www.baeldung.com/testing-rest-api-with-multiple-media-types) +- [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections) +- [Spring Boot Consuming and Producing JSON](https://www.baeldung.com/spring-boot-json) - More articles: [[prev -->]](/spring-boot-modules/spring-boot-mvc) diff --git a/spring-boot-modules/spring-boot-mvc-2/pom.xml b/spring-boot-modules/spring-boot-mvc-2/pom.xml index edebd41986..f527fd78f6 100644 --- a/spring-boot-modules/spring-boot-mvc-2/pom.xml +++ b/spring-boot-modules/spring-boot-mvc-2/pom.xml @@ -49,6 +49,27 @@ org.apache.commons commons-lang3 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.fasterxml.jackson.core + jackson-databind + + + + com.h2database + h2 + + + + com.thoughtworks.xstream + xstream + ${xstream.version} @@ -103,6 +124,7 @@ com.baeldung.swagger2boot.SpringBootSwaggerApplication 2.2.0.BUILD-SNAPSHOT + 1.4.11.1 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/Foo.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/Foo.java new file mode 100644 index 0000000000..e553ca1b72 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/Foo.java @@ -0,0 +1,95 @@ +package com.baeldung.etag; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Version; + +@Entity +public class Foo implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + @Column(nullable = false) + private String name; + + @Version + private long version; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + this.name = name; + } + + // API + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public long getVersion() { + return version; + } + + public void setVersion(long version) { + this.version = version; + } + + // + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Foo other = (Foo) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Foo [name=").append(name).append("]"); + return builder.toString(); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooController.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooController.java new file mode 100644 index 0000000000..58f366501d --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooController.java @@ -0,0 +1,58 @@ +package com.baeldung.etag; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +@RestController +@RequestMapping(value = "/foos") +public class FooController { + + @Autowired + private FooDao fooDao; + + @GetMapping(value = "/{id}") + public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { + return fooDao.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + } + + // Note: the global filter overrides the ETag value we set here. We can still + // analyze its behaviour in the Integration Test. + @GetMapping(value = "/{id}/custom-etag") + public ResponseEntity findByIdWithCustomEtag(@PathVariable("id") final Long id, + final HttpServletResponse response) { + final Foo foo = fooDao.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); + return ResponseEntity.ok().eTag(Long.toString(foo.getVersion())).body(foo); + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { + return fooDao.save(resource); + } + + @PutMapping(value = "/{id}") + @ResponseStatus(HttpStatus.OK) + public void update(@PathVariable("id") final Long id, @RequestBody final Foo resource) { + fooDao.save(resource); + } + + @DeleteMapping(value = "/{id}") + @ResponseStatus(HttpStatus.OK) + public void delete(@PathVariable("id") final Long id) { + fooDao.deleteById(id); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooDao.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooDao.java new file mode 100644 index 0000000000..aff011af4a --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/FooDao.java @@ -0,0 +1,8 @@ +package com.baeldung.etag; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface FooDao extends CrudRepository{ +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java new file mode 100644 index 0000000000..9e58a1550c --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/SpringBootEtagApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.etag; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootEtagApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootEtagApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/WebConfig.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/WebConfig.java new file mode 100644 index 0000000000..bef468452a --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/etag/WebConfig.java @@ -0,0 +1,28 @@ +package com.baeldung.etag; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.ShallowEtagHeaderFilter; + +@Configuration +public class WebConfig { + + // Etags + + // If we're not using Spring Boot we can make use of + // AbstractAnnotationConfigDispatcherServletInitializer#getServletFilters + @Bean + public FilterRegistrationBean shallowEtagHeaderFilter() { + FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean<>( new ShallowEtagHeaderFilter()); + filterRegistrationBean.addUrlPatterns("/foos/*"); + filterRegistrationBean.setName("etagFilter"); + return filterRegistrationBean; + } + + // We can also just declare the filter directly + // @Bean + // public ShallowEtagHeaderFilter shallowEtagHeaderFilter() { + // return new ShallowEtagHeaderFilter(); + // } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/SpringBootStudentsApplication.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/SpringBootStudentsApplication.java new file mode 100644 index 0000000000..9c499e6103 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/SpringBootStudentsApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.students; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootStudentsApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootStudentsApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/Student.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/Student.java new file mode 100644 index 0000000000..16d02fe14a --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/Student.java @@ -0,0 +1,53 @@ +package com.baeldung.students; + +public class Student { + + private long id; + private String firstName; + private String lastName; + + public Student() {} + + public Student(String firstName, String lastName) { + super(); + this.firstName = firstName; + this.lastName = lastName; + } + + public Student(long id, String firstName, String lastName) { + super(); + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + @Override + public String toString() { + return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]"; + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentController.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentController.java new file mode 100644 index 0000000000..c71bb6c6e6 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentController.java @@ -0,0 +1,74 @@ +package com.baeldung.students; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import com.baeldung.students.StudentService; + +@RestController +@RequestMapping("/students") +public class StudentController { + + @Autowired + private StudentService service; + + @GetMapping("/") + public List read() { + return service.readAll(); + } + + @GetMapping("/{id}") + public ResponseEntity read(@PathVariable("id") Long id) { + Student foundStudent = service.read(id); + if (foundStudent == null) { + return ResponseEntity.notFound().build(); + } else { + return ResponseEntity.ok(foundStudent); + } + } + + @PostMapping("/") + public ResponseEntity create(@RequestBody Student student) throws URISyntaxException { + Student createdStudent = service.create(student); + + URI uri = ServletUriComponentsBuilder.fromCurrentRequest() + .path("/{id}") + .buildAndExpand(createdStudent.getId()) + .toUri(); + + return ResponseEntity.created(uri) + .body(createdStudent); + + } + + @PutMapping("/{id}") + public ResponseEntity update(@RequestBody Student student, @PathVariable Long id) { + Student updatedStudent = service.update(id, student); + if (updatedStudent == null) { + return ResponseEntity.notFound().build(); + } else { + return ResponseEntity.ok(updatedStudent); + } + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteStudent(@PathVariable Long id) { + service.delete(id); + + return ResponseEntity.noContent().build(); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentService.java b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentService.java new file mode 100644 index 0000000000..80f6dfd514 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students/StudentService.java @@ -0,0 +1,51 @@ +package com.baeldung.students; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Function; +import java.util.stream.Collectors; + +import org.springframework.stereotype.Service; + +@Service +public class StudentService { + + // DB repository mock + private Map repository = Arrays.asList( + new Student[]{ + new Student(1, "Alan","Turing"), + new Student(2, "Sebastian","Bach"), + new Student(3, "Pablo","Picasso"), + }).stream() + .collect(Collectors.toConcurrentMap(s -> s.getId(), Function.identity())); + + // DB id sequence mock + private AtomicLong sequence = new AtomicLong(3); + + public List readAll() { + return repository.values().stream().collect(Collectors.toList()); + } + + public Student read(Long id) { + return repository.get(id); + } + + public Student create(Student student) { + long key = sequence.incrementAndGet(); + student.setId(key); + repository.put(key, student); + return student; + } + + public Student update(Long id, Student student) { + student.setId(id); + Student oldStudent = repository.replace(id, student); + return oldStudent == null ? null : student; + } + + public void delete(Long id) { + repository.remove(id); + } +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/WEB-INF/web.xml b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/WEB-INF/web.xml new file mode 100644 index 0000000000..7f36b33b38 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/WEB-INF/web.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/foo_API_test.postman_collection.json b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/foo_API_test.postman_collection.json new file mode 100644 index 0000000000..dc4acafab3 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/foo_API_test.postman_collection.json @@ -0,0 +1,180 @@ +{ + "info": { + "_postman_id": "9989b5be-13ba-4d22-8e43-d05dbf628e58", + "name": "foo API test", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "add a foo", + "event": [ + { + "listen": "test", + "script": { + "id": "a01534dc-6fc7-4c54-ba1d-6bcf311e5836", + "exec": [ + "pm.test(\"success status\", () => pm.response.to.be.success );", + "", + "pm.test(\"name is correct\", () => ", + " pm.expect(pm.response.json().name).to.equal(\"Transformers\"));", + "", + "pm.test(\"id was assigned\", () => ", + " pm.expect(pm.response.json().id).to.be.not.null );", + "", + "pm.variables.set(\"id\", pm.response.json().id);" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "name": "Content-Type", + "value": "application/json", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"name\": \"Transformers\"\n}" + }, + "url": { + "raw": "http://localhost:8080/spring-boot-rest/foos", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "spring-boot-rest", + "foos" + ] + } + }, + "response": [] + }, + { + "name": "get a foo", + "event": [ + { + "listen": "test", + "script": { + "id": "03de440c-b483-4ab8-a11a-d0c99b349963", + "exec": [ + "pm.test(\"success status\", () => pm.response.to.be.success );", + "", + "pm.test(\"name is correct\", () => ", + " pm.expect(pm.response.json().name).to.equal(\"Transformers\"));", + "", + "pm.test(\"id is correct\", () => ", + " pm.expect(pm.response.json().id).to.equal(pm.variables.get(\"id\")) );" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://localhost:8080/spring-boot-rest/foos/{{id}}", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "spring-boot-rest", + "foos", + "{{id}}" + ] + } + }, + "response": [] + }, + { + "name": "delete a foo", + "event": [ + { + "listen": "test", + "script": { + "id": "74c1bb0f-c06c-48b1-a545-459233541b14", + "exec": [ + "pm.test(\"success status\", () => pm.response.to.be.success );" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "DELETE", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://localhost:8080/spring-boot-rest/foos/{{id}}", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "spring-boot-rest", + "foos", + "{{id}}" + ] + } + }, + "response": [] + }, + { + "name": "verify delete", + "event": [ + { + "listen": "test", + "script": { + "id": "03de440c-b483-4ab8-a11a-d0c99b349963", + "exec": [ + "pm.test(\"status is 500\", () => pm.response.to.have.status(500) );", + "", + "pm.test(\"no value present\", () => ", + " pm.expect(pm.response.json().cause).to.equal(\"No value present\"));" + ], + "type": "text/javascript" + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "http://localhost:8080/spring-boot-rest/foos/{{id}}", + "protocol": "http", + "host": [ + "localhost" + ], + "port": "8080", + "path": [ + "spring-boot-rest", + "foos", + "{{id}}" + ] + } + }, + "response": [] + } + ] +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/etag/EtagIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/etag/EtagIntegrationTest.java new file mode 100644 index 0000000000..88c5ae1686 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/etag/EtagIntegrationTest.java @@ -0,0 +1,123 @@ +package com.baeldung.etag; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.assertj.core.util.Preconditions; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.restassured.RestAssured; +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +@ComponentScan(basePackageClasses = WebConfig.class) +@EnableAutoConfiguration +public class EtagIntegrationTest { + + @LocalServerPort + private int port; + + @Test + public void givenResourceExists_whenRetrievingResource_thenEtagIsAlsoReturned() { + // Given + final String uriOfResource = createAsUri(); + + // When + final Response findOneResponse = RestAssured.given().header("Accept", "application/json").get(uriOfResource); + + // Then + assertNotNull(findOneResponse.getHeader(HttpHeaders.ETAG)); + } + + @Test + public void givenResourceWasRetrieved_whenRetrievingAgainWithEtag_thenNotModifiedReturned() { + // Given + final String uriOfResource = createAsUri(); + final Response findOneResponse = RestAssured.given().header("Accept", "application/json").get(uriOfResource); + final String etagValue = findOneResponse.getHeader(HttpHeaders.ETAG); + + // When + final Response secondFindOneResponse = RestAssured.given().header("Accept", "application/json") + .headers("If-None-Match", etagValue).get(uriOfResource); + + // Then + assertTrue(secondFindOneResponse.getStatusCode() == 304); + } + + @Test + public void givenResourceWasRetrievedThenModified_whenRetrievingAgainWithEtag_thenResourceIsReturned() { + // Given + final String uriOfResource = createAsUri(); + final Response firstFindOneResponse = RestAssured.given().header("Accept", "application/json") + .get(uriOfResource); + final String etagValue = firstFindOneResponse.getHeader(HttpHeaders.ETAG); + final long createdId = firstFindOneResponse.jsonPath().getLong("id"); + + Foo updatedFoo = new Foo("updated value"); + updatedFoo.setId(createdId); + Response updatedResponse = RestAssured.given().contentType(ContentType.JSON).body(updatedFoo) + .put(uriOfResource); + assertThat(updatedResponse.getStatusCode() == 200); + + // When + final Response secondFindOneResponse = RestAssured.given().header("Accept", "application/json") + .headers("If-None-Match", etagValue).get(uriOfResource); + + // Then + assertTrue(secondFindOneResponse.getStatusCode() == 200); + } + + @Test + @Ignore("Not Yet Implemented By Spring - https://jira.springsource.org/browse/SPR-10164") + public void givenResourceExists_whenRetrievedWithIfMatchIncorrectEtag_then412IsReceived() { + // Given + final String uriOfResource = createAsUri(); + + // When + final Response findOneResponse = RestAssured.given().header("Accept", "application/json") + .headers("If-Match", randomAlphabetic(8)).get(uriOfResource); + + // Then + assertTrue(findOneResponse.getStatusCode() == 412); + } + + private final String createAsUri() { + final Response response = createAsResponse(new Foo(randomAlphabetic(6))); + Preconditions.checkState(response.getStatusCode() == 201, "create operation: " + response.getStatusCode()); + + return getURL() + "/" + response.getBody().as(Foo.class).getId(); + } + + private Response createAsResponse(final Foo resource) { + String resourceAsString; + try { + resourceAsString = new ObjectMapper().writeValueAsString(resource); + } catch (JsonProcessingException e) { + throw new AssertionError("Error during serialization"); + } + return RestAssured.given().contentType(MediaType.APPLICATION_JSON.toString()).body(resourceAsString) + .post(getURL()); + } + + private String getURL() { + return "http://localhost:" + port + "/foos"; + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java new file mode 100644 index 0000000000..e65b106ead --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/FooLiveTest.java @@ -0,0 +1,82 @@ +package com.baeldung.mime; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.etag.Foo; +import com.baeldung.etag.WebConfig; + +import io.restassured.RestAssured; +import io.restassured.response.Response; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes= WebConfig.class, webEnvironment = WebEnvironment.RANDOM_PORT) +@ComponentScan({"com.baeldung.mime", "com.baeldung.etag"}) +@EnableAutoConfiguration +@ActiveProfiles("test") +public class FooLiveTest { + + @LocalServerPort + private int port; + + @Autowired + protected IMarshaller marshaller; + + // API + + public final void create() { + create(new Foo(randomAlphabetic(6))); + } + + public final String createAsUri() { + return createAsUri(new Foo(randomAlphabetic(6))); + } + + protected final void create(final Foo resource) { + createAsUri(resource); + } + + private final String createAsUri(final Foo resource) { + final Response response = createAsResponse(resource); + return getURL() + "/" + response.getBody().as(Foo.class).getId(); + } + + private final Response createAsResponse(final Foo resource) { + + final String resourceAsString = marshaller.encode(resource); + return RestAssured.given() + .contentType(marshaller.getMime()) + .body(resourceAsString) + .post(getURL()); + } + + // + + protected String getURL() { + return "http://localhost:" + port + "/foos"; + } + + @Test + public void givenResourceExists_whenRetrievingResource_thenEtagIsAlsoReturned() { + // Given + final String uriOfResource = createAsUri(); + + // When + final Response findOneResponse = RestAssured.given().header("Accept", "application/json").get(uriOfResource); + + // Then + assertEquals(findOneResponse.getStatusCode(), 200); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/IMarshaller.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/IMarshaller.java new file mode 100644 index 0000000000..79c0616043 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/IMarshaller.java @@ -0,0 +1,15 @@ +package com.baeldung.mime; + +import java.util.List; + +public interface IMarshaller { + + String encode(final T entity); + + T decode(final String entityAsString, final Class clazz); + + List decodeList(final String entitiesAsString, final Class clazz); + + String getMime(); + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/JacksonMarshaller.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/JacksonMarshaller.java new file mode 100644 index 0000000000..9dee0ef2cd --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/JacksonMarshaller.java @@ -0,0 +1,75 @@ +package com.baeldung.mime; + +import java.io.IOException; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; + +import com.baeldung.etag.Foo; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +public final class JacksonMarshaller implements IMarshaller { + private final Logger logger = LoggerFactory.getLogger(JacksonMarshaller.class); + + private final ObjectMapper objectMapper; + + public JacksonMarshaller() { + super(); + + objectMapper = new ObjectMapper(); + } + + // API + + @Override + public final String encode(final T resource) { + String entityAsJSON = null; + try { + entityAsJSON = objectMapper.writeValueAsString(resource); + } catch (final IOException ioEx) { + logger.error("", ioEx); + } + + return entityAsJSON; + } + + @Override + public final T decode(final String resourceAsString, final Class clazz) { + T entity = null; + try { + entity = objectMapper.readValue(resourceAsString, clazz); + } catch (final IOException ioEx) { + logger.error("", ioEx); + } + + return entity; + } + + @SuppressWarnings("unchecked") + @Override + public final List decodeList(final String resourcesAsString, final Class clazz) { + List entities = null; + try { + if (clazz.equals(Foo.class)) { + entities = objectMapper.readValue(resourcesAsString, new TypeReference>() { + // ... + }); + } else { + entities = objectMapper.readValue(resourcesAsString, List.class); + } + } catch (final IOException ioEx) { + logger.error("", ioEx); + } + + return entities; + } + + @Override + public final String getMime() { + return MediaType.APPLICATION_JSON.toString(); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/TestMarshallerFactory.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/TestMarshallerFactory.java new file mode 100644 index 0000000000..d7cd875ae4 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/TestMarshallerFactory.java @@ -0,0 +1,48 @@ +package com.baeldung.mime; + +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Profile; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +@Profile("test") +public class TestMarshallerFactory implements FactoryBean { + + @Autowired + private Environment env; + + public TestMarshallerFactory() { + super(); + } + + // API + + @Override + public IMarshaller getObject() { + final String testMime = env.getProperty("test.mime"); + if (testMime != null) { + switch (testMime) { + case "json": + return new JacksonMarshaller(); + case "xml": + return new XStreamMarshaller(); + default: + throw new IllegalStateException(); + } + } + + return new JacksonMarshaller(); + } + + @Override + public Class getObjectType() { + return IMarshaller.class; + } + + @Override + public boolean isSingleton() { + return true; + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/XStreamMarshaller.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/XStreamMarshaller.java new file mode 100644 index 0000000000..2c67694e83 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/mime/XStreamMarshaller.java @@ -0,0 +1,46 @@ +package com.baeldung.mime; + +import java.util.List; + +import org.springframework.http.MediaType; + +import com.baeldung.etag.Foo; +import com.thoughtworks.xstream.XStream; + +public final class XStreamMarshaller implements IMarshaller { + + private XStream xstream; + + public XStreamMarshaller() { + super(); + + xstream = new XStream(); + xstream.autodetectAnnotations(true); + xstream.processAnnotations(Foo.class); + } + + // API + + @Override + public final String encode(final T resource) { + return xstream.toXML(resource); + } + + @SuppressWarnings("unchecked") + @Override + public final T decode(final String resourceAsString, final Class clazz) { + return (T) xstream.fromXML(resourceAsString); + } + + @SuppressWarnings("unchecked") + @Override + public List decodeList(final String resourcesAsString, final Class clazz) { + return this.decode(resourcesAsString, List.class); + } + + @Override + public final String getMime() { + return MediaType.APPLICATION_XML.toString(); + } + +} diff --git a/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/students/StudentControllerIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/students/StudentControllerIntegrationTest.java new file mode 100644 index 0000000000..577dbb6eb1 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/test/java/com/baeldung/students/StudentControllerIntegrationTest.java @@ -0,0 +1,73 @@ +package com.baeldung.students; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +public class StudentControllerIntegrationTest { + + private static final String STUDENTS_PATH = "/students/"; + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenReadAll_thenStatusIsOk() throws Exception { + this.mockMvc.perform(get(STUDENTS_PATH)) + .andExpect(status().isOk()); + } + + @Test + public void whenReadOne_thenStatusIsOk() throws Exception { + this.mockMvc.perform(get(STUDENTS_PATH + 1)) + .andExpect(status().isOk()); + } + + @Test + public void whenCreate_thenStatusIsCreated() throws Exception { + Student student = new Student(10, "Albert", "Einstein"); + this.mockMvc.perform(post(STUDENTS_PATH).content(asJsonString(student)) + .contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isCreated()); + } + + @Test + public void whenUpdate_thenStatusIsOk() throws Exception { + Student student = new Student(1, "Nikola", "Tesla"); + this.mockMvc.perform(put(STUDENTS_PATH + 1) + .content(asJsonString(student)) + .contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isOk()); + } + + @Test + public void whenDelete_thenStatusIsNoContent() throws Exception { + this.mockMvc.perform(delete(STUDENTS_PATH + 3)) + .andExpect(status().isNoContent()); + } + + private String asJsonString(final Object obj) { + try { + return new ObjectMapper().writeValueAsString(obj); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/spring-boot-rest/README.md b/spring-boot-rest/README.md index f78c88d30b..861181c53e 100644 --- a/spring-boot-rest/README.md +++ b/spring-boot-rest/README.md @@ -4,12 +4,7 @@ This module contains articles about Spring Boot RESTful APIs. ### Relevant Articles -- [HATEOAS for a Spring REST Service](https://www.baeldung.com/rest-api-discoverability-with-spring) - [Versioning a REST API](https://www.baeldung.com/rest-versioning) -- [ETags for REST with Spring](https://www.baeldung.com/etags-for-rest-with-spring) -- [Testing REST with multiple MIME types](https://www.baeldung.com/testing-rest-api-with-multiple-media-types) -- [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections) -- [Spring Boot Consuming and Producing JSON](https://www.baeldung.com/spring-boot-json) ### E-book @@ -25,6 +20,7 @@ These articles are part of the Spring REST E-book: 8. [An Intro to Spring HATEOAS](https://www.baeldung.com/spring-hateoas-tutorial) 9. [REST Pagination in Spring](https://www.baeldung.com/rest-api-pagination-in-spring) 10. [Test a REST API with Java](https://www.baeldung.com/integration-testing-a-rest-api) +11. [HATEOAS for a Spring REST Service](https://www.baeldung.com/rest-api-discoverability-with-spring) NOTE: Since this is a module tied to an e-book, it should not be moved or used to store the code for any further article. From f953196ddfeecbe61b285a4f6d702cb86119fcab Mon Sep 17 00:00:00 2001 From: mike b Date: Thu, 19 Mar 2020 20:15:52 -0400 Subject: [PATCH 020/187] [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 cf216b69d6b04da2e98d16fd0b35a6e4de915ca2 Mon Sep 17 00:00:00 2001 From: Vikas Ramsingh Rajput Date: Fri, 20 Mar 2020 11:58:47 +0300 Subject: [PATCH 021/187] BAEL-3832: added setters and getters and changed the testcases accordingly --- .../bean/CustomBeanFactoryPostProcessor.java | 15 +++++--- .../bean/CustomBeanPostProcessor.java | 15 +++++--- .../baeldung/ioccontainer/bean/Student.java | 12 +++++-- .../ioccontainer/IOCContainerAppUnitTest.java | 36 +++++++++---------- 4 files changed, 49 insertions(+), 29 deletions(-) diff --git a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java index fe773ce2df..65e249b15b 100644 --- a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java +++ b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanFactoryPostProcessor.java @@ -1,14 +1,21 @@ package com.baeldung.ioccontainer.bean; -import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor { - public static boolean isBeanInstantiated = false; + private static boolean isBeanFactoryPostProcessorRegistered = false; @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { - isBeanInstantiated = true; + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory){ + setBeanFactoryPostProcessorRegistered(true); + } + + public static boolean isBeanFactoryPostProcessorRegistered() { + return isBeanFactoryPostProcessorRegistered; + } + + public static void setBeanFactoryPostProcessorRegistered(boolean isBeanFactoryPostProcessorRegistered) { + CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered = isBeanFactoryPostProcessorRegistered; } } diff --git a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java index 1c2e011a6c..6f99a5f0db 100644 --- a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java +++ b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/CustomBeanPostProcessor.java @@ -1,14 +1,21 @@ package com.baeldung.ioccontainer.bean; -import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; public class CustomBeanPostProcessor implements BeanPostProcessor { - public static boolean isBeanInstantiated = false; + private static boolean isBeanPostProcessorRegistered = false; @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - isBeanInstantiated = true; + public Object postProcessBeforeInitialization(Object bean, String beanName){ + setBeanPostProcessorRegistered(true); return bean; } + + public static boolean isBeanPostProcessorRegistered() { + return isBeanPostProcessorRegistered; + } + + public static void setBeanPostProcessorRegistered(boolean isBeanPostProcessorRegistered) { + CustomBeanPostProcessor.isBeanPostProcessorRegistered = isBeanPostProcessorRegistered; + } } diff --git a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java index 03e0b049ba..404f323b66 100644 --- a/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java +++ b/spring-core-3/src/main/java/com/baeldung/ioccontainer/bean/Student.java @@ -1,9 +1,17 @@ package com.baeldung.ioccontainer.bean; public class Student { - public static boolean isBeanInstantiated = false; + private static boolean isBeanInstantiated = false; public void postConstruct() { - isBeanInstantiated = true; + setBeanInstantiated(true); + } + + public static boolean isBeanInstantiated() { + return isBeanInstantiated; + } + + public static void setBeanInstantiated(boolean isBeanInstantiated) { + Student.isBeanInstantiated = isBeanInstantiated; } } diff --git a/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java b/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java index 3c0a5b3dbe..e9b491813e 100644 --- a/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java +++ b/spring-core-3/src/test/java/com/baeldung/ioccontainer/IOCContainerAppUnitTest.java @@ -23,9 +23,9 @@ public class IOCContainerAppUnitTest { @BeforeEach @AfterEach public void resetInstantiationFlag() { - Student.isBeanInstantiated = false; - CustomBeanPostProcessor.isBeanInstantiated = false; - CustomBeanFactoryPostProcessor.isBeanInstantiated = false; + Student.setBeanInstantiated(false); + CustomBeanPostProcessor.setBeanPostProcessorRegistered(false); + CustomBeanFactoryPostProcessor.setBeanFactoryPostProcessorRegistered(false); } @Test @@ -33,24 +33,23 @@ public class IOCContainerAppUnitTest { Resource res = new ClassPathResource("ioc-container-difference-example.xml"); BeanFactory factory = new XmlBeanFactory(res); - assertFalse(Student.isBeanInstantiated); + assertFalse(Student.isBeanInstantiated()); } @Test public void whenBFInitialized_thenStudentInitialized() { - Resource res = new ClassPathResource("ioc-container-difference-example.xml"); BeanFactory factory = new XmlBeanFactory(res); Student student = (Student) factory.getBean("student"); - assertTrue(Student.isBeanInstantiated); + assertTrue(Student.isBeanInstantiated()); } @Test public void whenAppContInitialized_thenStudentInitialized() { ApplicationContext context = new ClassPathXmlApplicationContext("ioc-container-difference-example.xml"); - assertTrue(Student.isBeanInstantiated); + assertTrue(Student.isBeanInstantiated()); } @Test @@ -58,16 +57,8 @@ public class IOCContainerAppUnitTest { Resource res = new ClassPathResource("ioc-container-difference-example.xml"); ConfigurableListableBeanFactory factory = new XmlBeanFactory(res); - assertFalse(CustomBeanFactoryPostProcessor.isBeanInstantiated); - assertFalse(CustomBeanPostProcessor.isBeanInstantiated); - } - - @Test - public void whenAppContInitialized_thenBFPostProcessorAndBPostProcessorRegisteredAutomatically() { - ApplicationContext context = new ClassPathXmlApplicationContext("ioc-container-difference-example.xml"); - - assertTrue(CustomBeanFactoryPostProcessor.isBeanInstantiated); - assertTrue(CustomBeanPostProcessor.isBeanInstantiated); + assertFalse(CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered()); + assertFalse(CustomBeanPostProcessor.isBeanPostProcessorRegistered()); } @Test @@ -77,12 +68,19 @@ public class IOCContainerAppUnitTest { CustomBeanFactoryPostProcessor beanFactoryPostProcessor = new CustomBeanFactoryPostProcessor(); beanFactoryPostProcessor.postProcessBeanFactory(factory); - assertTrue(CustomBeanFactoryPostProcessor.isBeanInstantiated); + assertTrue(CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered()); CustomBeanPostProcessor beanPostProcessor = new CustomBeanPostProcessor(); factory.addBeanPostProcessor(beanPostProcessor); Student student = (Student) factory.getBean("student"); - assertTrue(CustomBeanPostProcessor.isBeanInstantiated); + assertTrue(CustomBeanPostProcessor.isBeanPostProcessorRegistered()); } + + @Test + public void whenAppContInitialized_thenBFPostProcessorAndBPostProcessorRegisteredAutomatically() { + ApplicationContext context = new ClassPathXmlApplicationContext("ioc-container-difference-example.xml"); + assertTrue(CustomBeanFactoryPostProcessor.isBeanFactoryPostProcessorRegistered()); + assertTrue(CustomBeanPostProcessor.isBeanPostProcessorRegistered()); + } } From d3b35f9f0cfb9ef49366f3b7f9db10f891fb0f6d Mon Sep 17 00:00:00 2001 From: Eduard Ardeleanu Date: Fri, 20 Mar 2020 17:28:47 +0200 Subject: [PATCH 022/187] 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 b13bb933750b70375a7f7353e8b22733efa2da13 Mon Sep 17 00:00:00 2001 From: Vikas Ramsingh Rajput Date: Sat, 21 Mar 2020 09:13:32 +0300 Subject: [PATCH 023/187] BAEL-3832: removed tab space --- .../src/test/resources/ioc-container-difference-example.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-core-3/src/test/resources/ioc-container-difference-example.xml b/spring-core-3/src/test/resources/ioc-container-difference-example.xml index ba84aa635d..e53dc11f89 100644 --- a/spring-core-3/src/test/resources/ioc-container-difference-example.xml +++ b/spring-core-3/src/test/resources/ioc-container-difference-example.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> - + \ No newline at end of file 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 024/187] 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 025/187] 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 026/187] 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 027/187] [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 028/187] 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 7ad1542856206c68c8817e28b0cbe9b49196beb9 Mon Sep 17 00:00:00 2001 From: Justin Albano Date: Tue, 24 Mar 2020 19:56:27 -0400 Subject: [PATCH 029/187] BAEL-3587: Added %n new line example. --- .../java/com/baeldung/newline/AddingNewLineToString.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java index f701ab2e45..45de6523f9 100644 --- a/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java @@ -38,6 +38,11 @@ public class AddingNewLineToString { System.out.println("6. Using System.getProperty(\"line.separator\")"); rhyme = line1 + System.getProperty("line.separator") + line2; System.out.println(rhyme); + + //6. Using %n + System.out.println("7. Using %n"); + rhyme = "Humpty Dumpty sat on a wall.%nHumpty Dumpty had a great fall."; + System.out.println(rhyme); System.out.println("***HTML to rendered in a browser***"); //1. Line break for HTML using
From a7cb075f7d8cb308d6ced810233abbd485efe9f6 Mon Sep 17 00:00:00 2001 From: mike b Date: Tue, 24 Mar 2020 19:57:00 -0400 Subject: [PATCH 030/187] [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 f239c41f5fc570c7d3db66f1b5a3c7758905cd13 Mon Sep 17 00:00:00 2001 From: Justin Albano Date: Tue, 24 Mar 2020 19:57:56 -0400 Subject: [PATCH 031/187] BAEL-3587: Corrected mis-numbering in comments. --- .../main/java/com/baeldung/newline/AddingNewLineToString.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java index 45de6523f9..dd8b3a420d 100644 --- a/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java +++ b/core-java-modules/core-java-string-operations/src/main/java/com/baeldung/newline/AddingNewLineToString.java @@ -39,7 +39,7 @@ public class AddingNewLineToString { rhyme = line1 + System.getProperty("line.separator") + line2; System.out.println(rhyme); - //6. Using %n + //7. Using %n System.out.println("7. Using %n"); rhyme = "Humpty Dumpty sat on a wall.%nHumpty Dumpty had a great fall."; System.out.println(rhyme); From c4ba08d9e5026059a3d070aafcf904a579cb86fe Mon Sep 17 00:00:00 2001 From: mike b Date: Tue, 24 Mar 2020 20:02:23 -0400 Subject: [PATCH 032/187] [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 033/187] [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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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 034/187] 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 035/187] 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 036/187] 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 037/187] 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 038/187] 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 039/187] 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 2ba09756f7fe2efdb8198d4cba4952e1e88a4314 Mon Sep 17 00:00:00 2001 From: Antonio Moreno Date: Tue, 24 Mar 2020 23:43:49 +0000 Subject: [PATCH 040/187] BAEL-3928 Comparing Long values in Java --- .../comparelong/CompareLongUnitTest.java | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparelong/CompareLongUnitTest.java 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 new file mode 100644 index 0000000000..ab4ea2b657 --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/comparelong/CompareLongUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.comparelong; + +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class CompareLongUnitTest { + + @Test + public void givenLongValuesLessThan128_whenUsingReferenceComparater_thenSuccess() { + + Long l1 = 127L; + Long l2 = 127L; + + assertThat(l1 == l2).isTrue(); + } + + @Test + public void givenLongValuesGreaterOrEqualsThan128_whenUsingReferenceComparater_thenFails() { + + Long l1 = 128L; + Long l2 = 128L; + + assertThat(l1 == l2).isFalse(); + } + + @Test + public void givenLongValuesGreaterOrEqualsThan128_whenUsingEquals_thenSuccess() { + + Long l1 = 128L; + Long l2 = 128L; + + assertThat(l1.equals(l2)).isTrue(); + } + + @Test + public void givenLongValuesGreaterOrEqualsThan128_whenUsingComparisonOperator_andLongValue_thenSuccess() { + + Long l1 = 128L; + Long l2 = 128L; + + assertThat(l1.longValue() == l2.longValue()).isTrue(); + } + + @Test + public void givenLongValuesGreaterOrEqualsThan128_whenUsingCasting_thenSuccess() { + + Long l1 = 128L; + Long l2 = 128L; + + assertThat((long) l1 == (long) l2).isTrue(); + } + +} \ No newline at end of file From c6f71e7ac7bae3587fdabcc49329fec817af38e7 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Thu, 26 Mar 2020 23:00:07 +0100 Subject: [PATCH 041/187] [BAEL-3934]shedlock update --- .../spring-boot-libraries/pom.xml | 8 +++- .../main/java/com/baeldung/Application.java | 15 +++++++ .../java/com/baeldung/boot/Application.java | 14 ------- ...eduler.java => BaeldungTaskScheduler.java} | 5 +-- .../shedlock/SchedulerConfiguration.java | 14 ++++--- .../src/main/resources/application.yml | 6 +++ .../BaeldungTaskSchedulerIntegrationTest.java | 39 +++++++++++++++++++ 7 files changed, 78 insertions(+), 23 deletions(-) create mode 100644 spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/Application.java delete mode 100644 spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/Application.java rename spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/{TaskScheduler.java => BaeldungTaskScheduler.java} (85%) create mode 100644 spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml create mode 100644 spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/scheduling/shedlock/BaeldungTaskSchedulerIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-libraries/pom.xml b/spring-boot-modules/spring-boot-libraries/pom.xml index e9d955edc0..2b1b1b7d12 100644 --- a/spring-boot-modules/spring-boot-libraries/pom.xml +++ b/spring-boot-modules/spring-boot-libraries/pom.xml @@ -52,7 +52,11 @@ shedlock-provider-jdbc-template ${shedlock.version} - + + com.h2database + h2 + ${h2.version} + net.sourceforge.barbecue @@ -79,6 +83,7 @@ javase ${zxing.version} + @@ -185,6 +190,7 @@ 2.2.4 2.3.2 0.23.0 + 1.4.200 2.1.0 1.5-beta1 2.1 diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/Application.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..15422e1065 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/Application.java @@ -0,0 +1,15 @@ +package com.baeldung; + +import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableScheduling; + +@SpringBootApplication +@EnableScheduling +@EnableSchedulerLock(defaultLockAtMostFor = "PT30S") +public class Application { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/Application.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/Application.java deleted file mode 100644 index cb0d0c1532..0000000000 --- a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/boot/Application.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.boot; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ApplicationContext; - -@SpringBootApplication -public class Application { - private static ApplicationContext applicationContext; - - public static void main(String[] args) { - applicationContext = SpringApplication.run(Application.class, args); - } -} diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java similarity index 85% rename from spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java index 060afe660e..cd5f63e962 100644 --- a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/TaskScheduler.java +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/BaeldungTaskScheduler.java @@ -5,9 +5,8 @@ import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component -class TaskScheduler { - - @Scheduled(cron = "*/15 * * * *") +class BaeldungTaskScheduler { + @Scheduled(cron = "0 0/15 * * * ?") @SchedulerLock(name = "TaskScheduler_scheduledTask", lockAtLeastForString = "PT5M", lockAtMostForString = "PT14M") public void scheduledTask() { System.out.println("Running ShedLock task"); diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java index 74ea39683d..440e1ffc6a 100644 --- a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SchedulerConfiguration.java @@ -1,12 +1,16 @@ package com.baeldung.scheduling.shedlock; +import net.javacrumbs.shedlock.core.LockProvider; +import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; -import org.springframework.scheduling.annotation.EnableScheduling; + +import javax.sql.DataSource; @Configuration -@EnableScheduling -@EnableSchedulerLock(defaultLockAtMostFor = "PT30S") public class SchedulerConfiguration { - + @Bean + public LockProvider lockProvider(DataSource dataSource) { + return new JdbcTemplateLockProvider(dataSource); + } } \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml b/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml new file mode 100644 index 0000000000..3477520208 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/resources/application.yml @@ -0,0 +1,6 @@ +spring: + datasource: + driverClassName: org.h2.Driver + url: jdbc:h2:mem:shedlock_DB;INIT=CREATE SCHEMA IF NOT EXISTS shedlock;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + username: sa + password: diff --git a/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/scheduling/shedlock/BaeldungTaskSchedulerIntegrationTest.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/scheduling/shedlock/BaeldungTaskSchedulerIntegrationTest.java new file mode 100644 index 0000000000..47f42c133f --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/scheduling/shedlock/BaeldungTaskSchedulerIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.scheduling.shedlock; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class BaeldungTaskSchedulerIntegrationTest { + @Autowired + private BaeldungTaskScheduler taskScheduler; + + @Test + public void whenShedLockConfigCorrect_thenSpringCtxtStartsWithoutError() { + // save the old out + PrintStream old = System.out; + + // Create a stream to hold the output for test + ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(consoleOutput); + System.setOut(ps); + //test + taskScheduler.scheduledTask(); + System.out.flush(); + String expected = "Running ShedLock task\n"; + assertThat(consoleOutput.toString()).isEqualTo(expected); + + //restore the old out + System.setOut(old); + } + +} \ No newline at end of file From 1bc12a57df47a42c36097bdbd0cc5247658666b1 Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Sun, 29 Mar 2020 13:16:38 +0430 Subject: [PATCH 042/187] Ignoring a Bad Flaky Test --- .../hibernate/criteria/HibernateCriteriaIntegrationTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java index 31877255b2..7d95e0f342 100644 --- a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java @@ -8,6 +8,7 @@ import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; +import org.junit.Ignore; import org.junit.Test; import com.baeldung.hibernate.criteria.model.Item; @@ -24,6 +25,7 @@ public class HibernateCriteriaIntegrationTest { final private ApplicationView av = new ApplicationView(); @Test + @Ignore public void testPerformanceOfCriteria() { assertFalse(av.checkIfCriteriaTimeLower()); } From 71fecd658963941c694f0528e981b2f88441999d Mon Sep 17 00:00:00 2001 From: Philippe Date: Sun, 29 Mar 2020 11:49:46 -0300 Subject: [PATCH 043/187] [BAEL-3793][BAEL-3935] Code snippets --- terraform/best-practices/README.md | 10 +++ .../best-practices/ec2-simple/.gitignore | 4 ++ terraform/best-practices/ec2-simple/SETUP.md | 23 +++++++ terraform/best-practices/ec2-simple/main.tf | 33 +++++++++ .../best-practices/ec2-simple/providers.tf | 6 ++ .../best-practices/ec2-simple/variables.tf | 15 ++++ terraform/best-practices/k8s-basic/.gitignore | 4 ++ terraform/best-practices/k8s-basic/SETUP.md | 15 ++++ terraform/best-practices/k8s-basic/main.tf | 12 ++++ .../best-practices/k8s-basic/providers.tf | 6 ++ .../best-practices/k8s-basic/variables.tf | 9 +++ .../best-practices/k8s-modules/.gitignore | 4 ++ terraform/best-practices/k8s-modules/SETUP.md | 21 ++++++ terraform/best-practices/k8s-modules/main.tf | 27 ++++++++ .../k8s-modules/modules/SvcCustomer/main.tf | 68 ++++++++++++++++++ .../modules/SvcCustomer/outputs.tf | 3 + .../modules/SvcCustomer/variables.tf | 5 ++ .../k8s-modules/modules/SvcFeedback/main.tf | 69 +++++++++++++++++++ .../modules/SvcFeedback/outputs.tf | 3 + .../modules/SvcFeedback/variables.tf | 5 ++ .../ingress/www.petshop.com.br/main.tf | 41 +++++++++++ .../ingress/www.petshop.com.br/outputs.tf | 5 ++ .../ingress/www.petshop.com.br/variables.tf | 20 ++++++ .../best-practices/k8s-modules/provider.tf | 13 ++++ terraform/hello-terraform/.gitignore | 6 ++ terraform/hello-terraform/main.tf | 7 ++ 26 files changed, 434 insertions(+) create mode 100644 terraform/best-practices/README.md create mode 100644 terraform/best-practices/ec2-simple/.gitignore create mode 100644 terraform/best-practices/ec2-simple/SETUP.md create mode 100644 terraform/best-practices/ec2-simple/main.tf create mode 100644 terraform/best-practices/ec2-simple/providers.tf create mode 100644 terraform/best-practices/ec2-simple/variables.tf create mode 100644 terraform/best-practices/k8s-basic/.gitignore create mode 100644 terraform/best-practices/k8s-basic/SETUP.md create mode 100644 terraform/best-practices/k8s-basic/main.tf create mode 100644 terraform/best-practices/k8s-basic/providers.tf create mode 100644 terraform/best-practices/k8s-basic/variables.tf create mode 100644 terraform/best-practices/k8s-modules/.gitignore create mode 100644 terraform/best-practices/k8s-modules/SETUP.md create mode 100644 terraform/best-practices/k8s-modules/main.tf create mode 100644 terraform/best-practices/k8s-modules/modules/SvcCustomer/main.tf create mode 100644 terraform/best-practices/k8s-modules/modules/SvcCustomer/outputs.tf create mode 100644 terraform/best-practices/k8s-modules/modules/SvcCustomer/variables.tf create mode 100644 terraform/best-practices/k8s-modules/modules/SvcFeedback/main.tf create mode 100644 terraform/best-practices/k8s-modules/modules/SvcFeedback/outputs.tf create mode 100644 terraform/best-practices/k8s-modules/modules/SvcFeedback/variables.tf create mode 100644 terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/main.tf create mode 100644 terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/outputs.tf create mode 100644 terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/variables.tf create mode 100644 terraform/best-practices/k8s-modules/provider.tf create mode 100644 terraform/hello-terraform/.gitignore create mode 100644 terraform/hello-terraform/main.tf diff --git a/terraform/best-practices/README.md b/terraform/best-practices/README.md new file mode 100644 index 0000000000..fd488b1afb --- /dev/null +++ b/terraform/best-practices/README.md @@ -0,0 +1,10 @@ +# Terraform Sample Code + +This folder contains Terraform project samples that illustrates topics covered in the +"Best practices when using Terraform" article. Setup instructions are available in each sample's folder. + +List of available samples: + + * k8s-basic: "Hello world" project that just connects to a Kubernetes cluster and create a new namespace. + * ec2-basic: "Hello world" project that creates a single EC2 instance + * k8s-modules: A more elaborate sample that creates a simple set of services in a Kubernetes cluster diff --git a/terraform/best-practices/ec2-simple/.gitignore b/terraform/best-practices/ec2-simple/.gitignore new file mode 100644 index 0000000000..a70da3ca16 --- /dev/null +++ b/terraform/best-practices/ec2-simple/.gitignore @@ -0,0 +1,4 @@ +*.tfvars +*.tfstate +*.tfstate.backup +.terraform diff --git a/terraform/best-practices/ec2-simple/SETUP.md b/terraform/best-practices/ec2-simple/SETUP.md new file mode 100644 index 0000000000..3f906b6933 --- /dev/null +++ b/terraform/best-practices/ec2-simple/SETUP.md @@ -0,0 +1,23 @@ +# EC2 Basic Sample + +This Terraform sample project creates a single EC2 instance in the configured region. + +IMPORTANT NOTICE: In order to run this sample you must have an active AWS Account. As you probably know, creating resources on AWS +may result in additional charges in your bill. We recommend creating a test account to run this test as you can then use AWS's free tier +to play around. When finished, ALWAYS REMEMBER TO DESTROY YOUR RESOURCES !!! + +# Setup instructions + +1. Make sure you have a working AWS environment. Use a simple command such as _aws ec2 describe-instances_ and check its output. + If you get a list of existing EC2 instances, you're good to go. Otherwise, please refer to AWS documentation in order to setup your CLI. +2. Download the Terraform package for your environment from Hashicorp's site. Unzip it and put the _terraform_ binary somewhere + in the OS's PATH. +3. Open a command prompt and _cd_ into this folder +4. Run the following commands: +''' + $ terraform init + $ terraform apply -auto-approve +''' +5. Wait until Terraform create all resources and run _aws ec2 describe-instances_. The output should list the newly creates EC2 instance +6. Run _terraform destroy_ to remove the previously creates namespace. + diff --git a/terraform/best-practices/ec2-simple/main.tf b/terraform/best-practices/ec2-simple/main.tf new file mode 100644 index 0000000000..57fb9d1757 --- /dev/null +++ b/terraform/best-practices/ec2-simple/main.tf @@ -0,0 +1,33 @@ +# +# Resource definitions +# + +data "aws_ami" "apache" { + filter { + name = "name" + values = [var.ami_name] + } + + filter { + name = "virtualization-type" + values = ["hvm"] + } + + owners = [var.ami_owner] + + most_recent = true +} + +resource "aws_instance" "web" { + ami = data.aws_ami.apache.id + instance_type = "t2.micro" + subnet_id = aws_subnet.frontend.id +} +resource "aws_subnet" "frontend" { + vpc_id = aws_vpc.apps.id + cidr_block = "10.0.1.0/24" +} + +resource "aws_vpc" "apps" { + cidr_block = "10.0.0.0/16" +} diff --git a/terraform/best-practices/ec2-simple/providers.tf b/terraform/best-practices/ec2-simple/providers.tf new file mode 100644 index 0000000000..fa5826b067 --- /dev/null +++ b/terraform/best-practices/ec2-simple/providers.tf @@ -0,0 +1,6 @@ +# +# Providers definitions +# +provider "aws" { + version = "~> 2.53" +} \ No newline at end of file diff --git a/terraform/best-practices/ec2-simple/variables.tf b/terraform/best-practices/ec2-simple/variables.tf new file mode 100644 index 0000000000..2a7fddcd33 --- /dev/null +++ b/terraform/best-practices/ec2-simple/variables.tf @@ -0,0 +1,15 @@ +# +# Variables +# + +variable "ami_name" { + type = string + description = "AMI name to use for our EC2 instance. Defaults to Ubuntu 18.04 (Bionic)" + default = "ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-*" +} + +variable "ami_owner" { + type = string + description = "AMI Owner ID to use for our EC2 instance. Defaults to 099720109477 (Canonical)" + default = "099720109477" +} \ No newline at end of file diff --git a/terraform/best-practices/k8s-basic/.gitignore b/terraform/best-practices/k8s-basic/.gitignore new file mode 100644 index 0000000000..a70da3ca16 --- /dev/null +++ b/terraform/best-practices/k8s-basic/.gitignore @@ -0,0 +1,4 @@ +*.tfvars +*.tfstate +*.tfstate.backup +.terraform diff --git a/terraform/best-practices/k8s-basic/SETUP.md b/terraform/best-practices/k8s-basic/SETUP.md new file mode 100644 index 0000000000..479bb75274 --- /dev/null +++ b/terraform/best-practices/k8s-basic/SETUP.md @@ -0,0 +1,15 @@ +# Setup instructions + +1. Mak sure you have a working Kubernetes environment. Use a simple command such as _kubectl get nodes_ and check its output. + If you get a list of nodes that contains at least one _ready_ module, you're good to go +2. Download the Terraform package for your environment from Hashicorp's site. Unzip it and put the _terraform_ binary somewhere + in the OS's PATH. +3. Open a command prompt and _cd_ into this folder +4. Run the following commands: +''' + $ terraform init + $ terraform apply -auto-approve +''' +5. Wait until Terraform create all resources and run _kubectl get namespaces_. The output should now have a new "hello-terraform" namespace. +6. Run _terraform destroy_ to remove the previously creates namespace. + diff --git a/terraform/best-practices/k8s-basic/main.tf b/terraform/best-practices/k8s-basic/main.tf new file mode 100644 index 0000000000..5eb3749930 --- /dev/null +++ b/terraform/best-practices/k8s-basic/main.tf @@ -0,0 +1,12 @@ +# +# Resource definitions +# + +resource "kubernetes_namespace" "hello" { + metadata { + labels = { + terraform = "true" + } + name = var.namespace_name + } +} \ No newline at end of file diff --git a/terraform/best-practices/k8s-basic/providers.tf b/terraform/best-practices/k8s-basic/providers.tf new file mode 100644 index 0000000000..385f857a11 --- /dev/null +++ b/terraform/best-practices/k8s-basic/providers.tf @@ -0,0 +1,6 @@ +# +# Providers definitions +# +provider "kubernetes" { + version = "~> 1.11" +} \ No newline at end of file diff --git a/terraform/best-practices/k8s-basic/variables.tf b/terraform/best-practices/k8s-basic/variables.tf new file mode 100644 index 0000000000..b9217079bf --- /dev/null +++ b/terraform/best-practices/k8s-basic/variables.tf @@ -0,0 +1,9 @@ +# +# Variables +# + +variable "namespace_name" { + type = string + description = "Name to use for the created namespace" + default = "hello-terraform" +} \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/.gitignore b/terraform/best-practices/k8s-modules/.gitignore new file mode 100644 index 0000000000..a70da3ca16 --- /dev/null +++ b/terraform/best-practices/k8s-modules/.gitignore @@ -0,0 +1,4 @@ +*.tfvars +*.tfstate +*.tfstate.backup +.terraform diff --git a/terraform/best-practices/k8s-modules/SETUP.md b/terraform/best-practices/k8s-modules/SETUP.md new file mode 100644 index 0000000000..b7e4c2764d --- /dev/null +++ b/terraform/best-practices/k8s-modules/SETUP.md @@ -0,0 +1,21 @@ +# Kubernetes multimodule sample + +This sample deploys two services behind a Kubernetes ingress. + +# Setup instructions + +1. Mak sure you have a working Kubernetes environment. Use a simple command such as _kubectl get nodes_ and check its output. + If you get a list of nodes that contains at least one _ready_ module, you're good to go +2. Download the Terraform package for your environment from Hashicorp's site. Unzip it and put the _terraform_ binary somewhere + in the OS's PATH. +3. Open a command prompt and _cd_ into this folder +4. Run the following commands: +''' + $ terraform init + $ terraform apply -auto-approve +''' +5. Wait until Terraform create all resources and run _kubectl get services_. The output should now have a few services. +6. Run _terraform destroy_ to remove the previously creates namespace. + + + diff --git a/terraform/best-practices/k8s-modules/main.tf b/terraform/best-practices/k8s-modules/main.tf new file mode 100644 index 0000000000..86426b33db --- /dev/null +++ b/terraform/best-practices/k8s-modules/main.tf @@ -0,0 +1,27 @@ +/* + * Top-level definitions + */ + +//================================================================== Ingress + +module "ingress_www_petshop_com_br" { + source = "./modules/ingress/www.petshop.com.br" + ingress_host = "www.petshop.com.br" +} + +//================================================================== Deployments + +module "SvcCustomer" { + source = "./modules/SvcCustomer" +} + +module "SvcFeedback" { + source = "./modules/SvcFeedback" +} + + + + + + + diff --git a/terraform/best-practices/k8s-modules/modules/SvcCustomer/main.tf b/terraform/best-practices/k8s-modules/modules/SvcCustomer/main.tf new file mode 100644 index 0000000000..1ca0c91545 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcCustomer/main.tf @@ -0,0 +1,68 @@ +/* + * SvcCustomer deployment resources + */ + +resource "kubernetes_deployment" "SvcCustomer" { + + metadata { + name = "svccustomer" + labels = { + app = "SvcCustomer" + } + } + + spec { + replicas = 1 + + selector { + match_labels = { + app = "SvcCustomer" + } + } + + template { + metadata { + labels = { + app = "SvcCustomer" + } + } + + spec { + image_pull_secrets { + name = "docker-config" + } + + + container { + image = "inanimate/echo-server" + name = "svccustomer-httpd" + env { + name = "PORT" + value = "80" + } + } + } + } + } +} + +resource "kubernetes_service" "SvcCustomer" { + metadata { + name = "svccustomer" + } + + spec { + + selector = { + app = "SvcCustomer" + } + + session_affinity = "ClientIP" + port { + port = 80 + } + + //type = "LoadBalancer" + } + } + \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/modules/SvcCustomer/outputs.tf b/terraform/best-practices/k8s-modules/modules/SvcCustomer/outputs.tf new file mode 100644 index 0000000000..8a37fdf375 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcCustomer/outputs.tf @@ -0,0 +1,3 @@ +/* + * SvcCustomer output values + */ diff --git a/terraform/best-practices/k8s-modules/modules/SvcCustomer/variables.tf b/terraform/best-practices/k8s-modules/modules/SvcCustomer/variables.tf new file mode 100644 index 0000000000..3dfcfcd264 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcCustomer/variables.tf @@ -0,0 +1,5 @@ +/* + * SvcCustomer deployment variables + */ + + \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/modules/SvcFeedback/main.tf b/terraform/best-practices/k8s-modules/modules/SvcFeedback/main.tf new file mode 100644 index 0000000000..0f84c9163e --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcFeedback/main.tf @@ -0,0 +1,69 @@ +/* + * SvcFeedback deployment resources + */ + +resource "kubernetes_deployment" "SvcFeedback" { + + metadata { + name = "svcfeedback" + labels = { + app = "SvcFeedback" + } + } + + spec { + replicas = 1 + + selector { + match_labels = { + app = "SvcFeedback" + } + } + + template { + metadata { + labels = { + app = "SvcFeedback" + } + } + + spec { + image_pull_secrets { + name = "docker-config" + } + + + container { + image = "inanimate/echo-server" + name = "svcfeedback-httpd" + env { + name = "PORT" + value = "80" + } + } + + } + } + } +} + +resource "kubernetes_service" "SvcFeedback" { + metadata { + name = "svcfeedback" + } + + spec { + + selector = { + app = "SvcFeedback" + } + + session_affinity = "ClientIP" + port { + port = 80 + } + + //type = "LoadBalancer" + } + } + \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/modules/SvcFeedback/outputs.tf b/terraform/best-practices/k8s-modules/modules/SvcFeedback/outputs.tf new file mode 100644 index 0000000000..e08c17d4b4 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcFeedback/outputs.tf @@ -0,0 +1,3 @@ +/* + * SvcFeedback output values + */ diff --git a/terraform/best-practices/k8s-modules/modules/SvcFeedback/variables.tf b/terraform/best-practices/k8s-modules/modules/SvcFeedback/variables.tf new file mode 100644 index 0000000000..d8076d41a4 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/SvcFeedback/variables.tf @@ -0,0 +1,5 @@ +/* + * SvcFeedback deployment variables + */ + + \ No newline at end of file diff --git a/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/main.tf b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/main.tf new file mode 100644 index 0000000000..0dbda48981 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/main.tf @@ -0,0 +1,41 @@ +/* + * Kubernetes Ingress module + */ +locals { + iname = var.ingress_name == "" ? join("-",["ingress",sha1(uuid())]) : var.ingress_name +} + +resource "kubernetes_ingress" "ingress" { + metadata { + name = local.iname + annotations = map( + "nginx.ingress.kubernetes.io/rewrite-target","/" + ) + } + spec { + rule { + http { + path { + backend { + service_name = "svccustomer" + service_port = 80 + } + path = "/customers" + } + path { + backend { + service_name = "svcfeedback" + service_port = 80 + } + path = "/feedback" + } + } + } +/* + tls { + secret_name = "tls-secret" + } +*/ + } +} + diff --git a/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/outputs.tf b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/outputs.tf new file mode 100644 index 0000000000..e604417b05 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/outputs.tf @@ -0,0 +1,5 @@ +/* + * Output variables + */ + + diff --git a/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/variables.tf b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/variables.tf new file mode 100644 index 0000000000..9b06128ec5 --- /dev/null +++ b/terraform/best-practices/k8s-modules/modules/ingress/www.petshop.com.br/variables.tf @@ -0,0 +1,20 @@ +/* + * Kubernetes Ingress module + */ + + +variable "ingress_name" { + type = string + description = "Ingress name. Defaults to a random name." + default = "" +} + +variable "ingress_host" { + type = string + description = "Ingress hostname" + default = "www.petshop.com.br" +} + + + + diff --git a/terraform/best-practices/k8s-modules/provider.tf b/terraform/best-practices/k8s-modules/provider.tf new file mode 100644 index 0000000000..bb90d66ecf --- /dev/null +++ b/terraform/best-practices/k8s-modules/provider.tf @@ -0,0 +1,13 @@ +# +# Provider configurations +# This file will *NOT* be overwriten upon regeneration, so it's safe +# to add your own customizations +# + +provider "kubernetes" { + version = "~> 1.10" +} + +provider "random" { + version = "~> 2.2" +} \ No newline at end of file diff --git a/terraform/hello-terraform/.gitignore b/terraform/hello-terraform/.gitignore new file mode 100644 index 0000000000..452502c50f --- /dev/null +++ b/terraform/hello-terraform/.gitignore @@ -0,0 +1,6 @@ +*.tfvars +*.tfstate +*.tfstate.backup +.terraform +hello.txt + diff --git a/terraform/hello-terraform/main.tf b/terraform/hello-terraform/main.tf new file mode 100644 index 0000000000..d6a726fa36 --- /dev/null +++ b/terraform/hello-terraform/main.tf @@ -0,0 +1,7 @@ +provider "local" { + version = "~> 1.4" +} +resource "local_file" "hello" { + content = "Hello, Terraform" + filename = "hello.txt" +} From 4382852a1731d9d06f838219ec176ddf89c04d3d Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Sun, 29 Mar 2020 19:00:40 +0200 Subject: [PATCH 044/187] 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 65e21d3f6a394cbfc34f6c6d8b49d92a02a4aa9e Mon Sep 17 00:00:00 2001 From: Seun Matt Date: Sun, 29 Mar 2020 21:36:54 +0100 Subject: [PATCH 045/187] example code for BAEL-3749 (#8815) * example code for BAEL-3749 * added live test * added live test * improved exception handling in response log filter * propage exception in example code * updated repo with upstream * added example code for BAEL-3293 * updated the example code for BAEL-3749 * updated the example code for BAEL-3749 * updated the example code for BAEL-3749 * updated the example code for BAEL-3749 --- cas/cas-secured-app/pom.xml | 8 +- .../CasSecuredAppApplication.java | 91 ------ .../cassecuredapp/CasSecuredApplication.java | 97 +++++++ .../cassecuredapp/config/SecurityConfig.java | 83 ------ .../config/WebSecurityConfig.java | 79 ++++++ .../controllers/AuthController.java | 29 +- .../controllers/IndexController.java | 8 +- .../controllers/SecuredController.java | 30 ++ .../controllers/SecuredPageController.java | 24 -- .../src/main/resources/application.properties | 3 +- ...CasSecuredApplicationIntegrationTest.java} | 2 +- cas/cas-server/.factorypath | 228 ---------------- cas/cas-server/.gitignore | 7 + cas/cas-server/.mergify.yml | 32 +++ cas/cas-server/.travis.yml | 62 +++++ cas/cas-server/Dockerfile | 40 +++ cas/cas-server/README.md | 151 ++++++---- cas/cas-server/build.cmd | 102 ------- cas/cas-server/build.gradle | 106 +++++++ cas/cas-server/build.sh | 189 ------------- cas/cas-server/docker-build.sh | 10 + cas/cas-server/docker-compose.yml | 7 + cas/cas-server/docker-push.sh | 12 + cas/cas-server/docker-run.sh | 7 + cas/cas-server/etc/cas/config/application.yml | 2 - cas/cas-server/etc/cas/config/cas.properties | 9 +- cas/cas-server/etc/cas/config/log4j2.xml | 120 ++++---- cas/cas-server/etc/cas/saml/.gitkeep | 1 + cas/cas-server/etc/cas/services/.donotdel | 0 cas/cas-server/etc/cas/thekeystore | Bin 0 -> 2266 bytes cas/cas-server/gradle.properties | 28 ++ cas/cas-server/gradle/dockerjib.gradle | 52 ++++ cas/cas-server/gradle/springboot.gradle | 24 ++ cas/cas-server/gradle/tasks.gradle | 258 ++++++++++++++++++ .../gradle/wrapper/gradle-wrapper.properties | 5 + cas/cas-server/gradlew | 188 +++++++++++++ cas/cas-server/gradlew.bat | 100 +++++++ cas/cas-server/maven/maven-wrapper.jar | Bin 71910 -> 0 bytes cas/cas-server/maven/maven-wrapper.properties | 3 - cas/cas-server/mvnw | 234 ---------------- cas/cas-server/mvnw.bat | 174 ------------ cas/cas-server/pom.xml | 208 -------------- cas/cas-server/settings.gradle | 1 + .../src/main/jib/docker/entrypoint.sh | 22 ++ .../src/main/resources/application.properties | 136 +-------- .../src/main/resources/cas.properties | 9 - .../create_test_db_and_users_tbl.sql | 12 +- .../resources/etc/cas/config/application.yml | 2 - .../resources/etc/cas/config/cas.properties | 18 +- .../main/resources/etc/cas/config/log4j2.xml | 117 -------- .../etc/cas/services/casSecuredApp-8900.json | 8 + .../src/main/resources/etc/cas/thekeystore | Bin 2258 -> 2251 bytes .../main/resources/etc/cas/thekeystore.crt | Bin 901 -> 0 bytes cas/cas-server/src/main/resources/log4j2.xml | 117 -------- .../services/casSecuredApp-19991.json | 8 - cas/pom.xml | 23 -- pom.xml | 2 - 57 files changed, 1390 insertions(+), 1898 deletions(-) delete mode 100644 cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java create mode 100644 cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java delete mode 100644 cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java create mode 100644 cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/WebSecurityConfig.java create mode 100644 cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredController.java delete mode 100644 cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java rename cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/{CasSecuredAppApplicationIntegrationTest.java => CasSecuredApplicationIntegrationTest.java} (84%) delete mode 100644 cas/cas-server/.factorypath mode change 100644 => 100755 cas/cas-server/.gitignore create mode 100644 cas/cas-server/.mergify.yml create mode 100644 cas/cas-server/.travis.yml create mode 100644 cas/cas-server/Dockerfile delete mode 100644 cas/cas-server/build.cmd create mode 100644 cas/cas-server/build.gradle delete mode 100644 cas/cas-server/build.sh create mode 100755 cas/cas-server/docker-build.sh create mode 100644 cas/cas-server/docker-compose.yml create mode 100755 cas/cas-server/docker-push.sh create mode 100755 cas/cas-server/docker-run.sh delete mode 100644 cas/cas-server/etc/cas/config/application.yml create mode 100644 cas/cas-server/etc/cas/saml/.gitkeep create mode 100644 cas/cas-server/etc/cas/services/.donotdel create mode 100644 cas/cas-server/etc/cas/thekeystore create mode 100644 cas/cas-server/gradle.properties create mode 100644 cas/cas-server/gradle/dockerjib.gradle create mode 100644 cas/cas-server/gradle/springboot.gradle create mode 100644 cas/cas-server/gradle/tasks.gradle create mode 100644 cas/cas-server/gradle/wrapper/gradle-wrapper.properties create mode 100755 cas/cas-server/gradlew create mode 100644 cas/cas-server/gradlew.bat delete mode 100644 cas/cas-server/maven/maven-wrapper.jar delete mode 100644 cas/cas-server/maven/maven-wrapper.properties delete mode 100644 cas/cas-server/mvnw delete mode 100644 cas/cas-server/mvnw.bat create mode 100644 cas/cas-server/settings.gradle create mode 100755 cas/cas-server/src/main/jib/docker/entrypoint.sh delete mode 100644 cas/cas-server/src/main/resources/cas.properties delete mode 100644 cas/cas-server/src/main/resources/etc/cas/config/application.yml delete mode 100644 cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml create mode 100644 cas/cas-server/src/main/resources/etc/cas/services/casSecuredApp-8900.json delete mode 100644 cas/cas-server/src/main/resources/etc/cas/thekeystore.crt delete mode 100644 cas/cas-server/src/main/resources/log4j2.xml delete mode 100644 cas/cas-server/src/main/resources/services/casSecuredApp-19991.json diff --git a/cas/cas-secured-app/pom.xml b/cas/cas-secured-app/pom.xml index 8e6f28e3a8..426d65c32b 100644 --- a/cas/cas-secured-app/pom.xml +++ b/cas/cas-secured-app/pom.xml @@ -11,11 +11,15 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 + + 2.2.6.RELEASE + + org.springframework.boot diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java deleted file mode 100644 index 25cbb9bc9b..0000000000 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredAppApplication.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.baeldung.cassecuredapp; - -import org.jasig.cas.client.session.SingleSignOutFilter; -import org.jasig.cas.client.session.SingleSignOutHttpSessionListener; -import org.jasig.cas.client.validation.Cas30ServiceTicketValidator; -import org.jasig.cas.client.validation.TicketValidator; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Primary; -import org.springframework.context.event.EventListener; -import org.springframework.security.cas.ServiceProperties; -import org.springframework.security.cas.authentication.CasAuthenticationProvider; -import org.springframework.security.cas.web.CasAuthenticationEntryPoint; -import org.springframework.security.core.authority.AuthorityUtils; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.security.web.authentication.logout.LogoutFilter; -import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; - -import javax.servlet.http.HttpSessionEvent; - -@SpringBootApplication -public class CasSecuredAppApplication { - - public static void main(String[] args) { - SpringApplication.run(CasSecuredAppApplication.class, args); - } - - @Bean - public ServiceProperties serviceProperties() { - ServiceProperties serviceProperties = new ServiceProperties(); - serviceProperties.setService("http://localhost:9000/login/cas"); - serviceProperties.setSendRenew(false); - return serviceProperties; - } - - @Bean - @Primary - public AuthenticationEntryPoint authenticationEntryPoint(ServiceProperties sP) { - CasAuthenticationEntryPoint entryPoint = new CasAuthenticationEntryPoint(); - entryPoint.setLoginUrl("https://localhost:6443/cas/login"); - entryPoint.setServiceProperties(sP); - return entryPoint; - } - - @Bean - public TicketValidator ticketValidator() { - return new Cas30ServiceTicketValidator("https://localhost:6443/cas"); - } - - @Bean - public CasAuthenticationProvider casAuthenticationProvider() { - CasAuthenticationProvider provider = new CasAuthenticationProvider(); - provider.setServiceProperties(serviceProperties()); - provider.setTicketValidator(ticketValidator()); - provider.setUserDetailsService((s) -> new User("test@test.com", "smatt", - true, true, true, true, - AuthorityUtils.createAuthorityList("ROLE_ADMIN"))); - provider.setKey("CAS_PROVIDER_LOCALHOST_9000"); - return provider; - } - - - @Bean - public SecurityContextLogoutHandler securityContextLogoutHandler() { - return new SecurityContextLogoutHandler(); - } - - @Bean - public LogoutFilter logoutFilter() { - LogoutFilter logoutFilter = new LogoutFilter( - "https://localhost:6443/cas/logout", securityContextLogoutHandler()); - logoutFilter.setFilterProcessesUrl("/logout/cas"); - return logoutFilter; - } - - @Bean - public SingleSignOutFilter singleSignOutFilter() { - SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); - singleSignOutFilter.setCasServerUrlPrefix("https://localhost:6443/cas"); - singleSignOutFilter.setIgnoreInitConfiguration(true); - return singleSignOutFilter; - } - - @EventListener - public SingleSignOutHttpSessionListener singleSignOutHttpSessionListener(HttpSessionEvent event) { - return new SingleSignOutHttpSessionListener(); - } -} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java new file mode 100644 index 0000000000..4a2c609758 --- /dev/null +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/CasSecuredApplication.java @@ -0,0 +1,97 @@ +package com.baeldung.cassecuredapp; + +import org.jasig.cas.client.session.SingleSignOutFilter; +import org.jasig.cas.client.session.SingleSignOutHttpSessionListener; +import org.jasig.cas.client.validation.Cas30ServiceTicketValidator; +import org.jasig.cas.client.validation.TicketValidator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.context.event.EventListener; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.cas.ServiceProperties; +import org.springframework.security.cas.authentication.CasAuthenticationProvider; +import org.springframework.security.cas.web.CasAuthenticationEntryPoint; +import org.springframework.security.cas.web.CasAuthenticationFilter; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; +import org.springframework.security.web.authentication.logout.LogoutFilter; +import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; + +import javax.servlet.http.HttpSessionEvent; + +@SpringBootApplication +public class CasSecuredApplication { + + private static final Logger logger = LoggerFactory.getLogger(CasSecuredApplication.class); + + public static void main(String... args) { + SpringApplication.run(CasSecuredApplication.class, args); + } + + @Bean + public CasAuthenticationFilter casAuthenticationFilter( + AuthenticationManager authenticationManager, + ServiceProperties serviceProperties) throws Exception { + CasAuthenticationFilter filter = new CasAuthenticationFilter(); + filter.setAuthenticationManager(authenticationManager); + filter.setServiceProperties(serviceProperties); + return filter; + } + + @Bean + public ServiceProperties serviceProperties() { + logger.info("service properties"); + ServiceProperties serviceProperties = new ServiceProperties(); + serviceProperties.setService("http://cas-client:8900/login/cas"); + serviceProperties.setSendRenew(false); + return serviceProperties; + } + + @Bean + public TicketValidator ticketValidator() { + return new Cas30ServiceTicketValidator("https://localhost:8443"); + } + + @Bean + public CasAuthenticationProvider casAuthenticationProvider( + TicketValidator ticketValidator, + ServiceProperties serviceProperties) { + CasAuthenticationProvider provider = new CasAuthenticationProvider(); + provider.setServiceProperties(serviceProperties); + provider.setTicketValidator(ticketValidator); + provider.setUserDetailsService( + s -> new User("test@test.com", "Mellon", true, true, true, true, + AuthorityUtils.createAuthorityList("ROLE_ADMIN"))); + provider.setKey("CAS_PROVIDER_LOCALHOST_8900"); + return provider; + } + + + @Bean + public SecurityContextLogoutHandler securityContextLogoutHandler() { + return new SecurityContextLogoutHandler(); + } + + @Bean + public LogoutFilter logoutFilter() { + LogoutFilter logoutFilter = new LogoutFilter("https://localhost:8443/logout", securityContextLogoutHandler()); + logoutFilter.setFilterProcessesUrl("/logout/cas"); + return logoutFilter; + } + + @Bean + public SingleSignOutFilter singleSignOutFilter() { + SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); + singleSignOutFilter.setCasServerUrlPrefix("https://localhost:8443"); + singleSignOutFilter.setLogoutCallbackPath("/exit/cas"); + singleSignOutFilter.setIgnoreInitConfiguration(true); + return singleSignOutFilter; + } + +} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java deleted file mode 100644 index 2eabed49e1..0000000000 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/SecurityConfig.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.baeldung.cassecuredapp.config; - -import org.jasig.cas.client.session.SingleSignOutFilter; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.ProviderManager; -import org.springframework.security.cas.ServiceProperties; -import org.springframework.security.cas.authentication.CasAuthenticationProvider; -import org.springframework.security.cas.web.CasAuthenticationFilter; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.security.web.authentication.logout.LogoutFilter; - -import java.util.Arrays; - -@EnableWebSecurity -@Configuration -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - private AuthenticationProvider authenticationProvider; - private AuthenticationEntryPoint authenticationEntryPoint; - private SingleSignOutFilter singleSignOutFilter; - private LogoutFilter logoutFilter; - - @Autowired - public SecurityConfig(CasAuthenticationProvider casAuthenticationProvider, AuthenticationEntryPoint eP, - LogoutFilter lF - , SingleSignOutFilter ssF - ) { - this.authenticationProvider = casAuthenticationProvider; - this.authenticationEntryPoint = eP; - - this.logoutFilter = lF; - this.singleSignOutFilter = ssF; - - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .regexMatchers("/secured.*", "/login") - .authenticated() - .and() - .authorizeRequests() - .regexMatchers("/") - .permitAll() - .and() - .httpBasic() - .authenticationEntryPoint(authenticationEntryPoint) - .and() - .logout().logoutSuccessUrl("/logout") - .and() - .addFilterBefore(singleSignOutFilter, CasAuthenticationFilter.class) - .addFilterBefore(logoutFilter, LogoutFilter.class); - - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.authenticationProvider(authenticationProvider); - } - - @Override - protected AuthenticationManager authenticationManager() throws Exception { - return new ProviderManager(Arrays.asList(authenticationProvider)); - } - - @Bean - public CasAuthenticationFilter casAuthenticationFilter(ServiceProperties sP) throws Exception { - CasAuthenticationFilter filter = new CasAuthenticationFilter(); - filter.setServiceProperties(sP); - filter.setAuthenticationManager(authenticationManager()); - return filter; - } - -} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/WebSecurityConfig.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/WebSecurityConfig.java new file mode 100644 index 0000000000..b0c3c68387 --- /dev/null +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/config/WebSecurityConfig.java @@ -0,0 +1,79 @@ +package com.baeldung.cassecuredapp.config; + +import org.jasig.cas.client.session.SingleSignOutFilter; +import org.jasig.cas.client.validation.Cas30ServiceTicketValidator; +import org.jasig.cas.client.validation.TicketValidator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.ProviderManager; +import org.springframework.security.cas.ServiceProperties; +import org.springframework.security.cas.authentication.CasAuthenticationProvider; +import org.springframework.security.cas.web.CasAuthenticationEntryPoint; +import org.springframework.security.cas.web.CasAuthenticationFilter; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.authentication.logout.LogoutFilter; + +import java.util.Collections; + +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + private Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class); + private SingleSignOutFilter singleSignOutFilter; + private LogoutFilter logoutFilter; + private CasAuthenticationProvider casAuthenticationProvider; + private ServiceProperties serviceProperties; + + @Autowired + public WebSecurityConfig(SingleSignOutFilter singleSignOutFilter, LogoutFilter logoutFilter, + CasAuthenticationProvider casAuthenticationProvider, + ServiceProperties serviceProperties) { + this.logoutFilter = logoutFilter; + this.singleSignOutFilter = singleSignOutFilter; + this.serviceProperties = serviceProperties; + this.casAuthenticationProvider = casAuthenticationProvider; + } + + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests().antMatchers( "/secured", "/login").authenticated() + .and() + .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()) + .and() + .addFilterBefore(singleSignOutFilter, CasAuthenticationFilter.class) + .addFilterBefore(logoutFilter, LogoutFilter.class) + .csrf().ignoringAntMatchers("/exit/cas"); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.authenticationProvider(casAuthenticationProvider); + } + + @Bean + @Override + protected AuthenticationManager authenticationManager() throws Exception { + return new ProviderManager(Collections.singletonList(casAuthenticationProvider)); + } + + public AuthenticationEntryPoint authenticationEntryPoint() { + CasAuthenticationEntryPoint entryPoint = new CasAuthenticationEntryPoint(); + entryPoint.setLoginUrl("https://localhost:8443/login"); + entryPoint.setServiceProperties(serviceProperties); + return entryPoint; + } + + + +} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java index 2c88b74a83..16254c8cbd 100644 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java @@ -1,7 +1,7 @@ package com.baeldung.cassecuredapp.controllers; -import org.apache.log4j.LogManager; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler; @@ -13,24 +13,27 @@ import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY; + @Controller public class AuthController { - private Logger logger = LogManager.getLogger(AuthController.class); - - @GetMapping("/logout") - public String logout( - HttpServletRequest request, HttpServletResponse response, SecurityContextLogoutHandler logoutHandler) { - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - logoutHandler.logout(request, response, auth ); - new CookieClearingLogoutHandler(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY).logout(request, response, auth); - return "auth/logout"; - } - + private Logger logger = LoggerFactory.getLogger(AuthController.class); @GetMapping("/login") public String login() { + logger.info("/login called"); return "redirect:/secured"; } + + @GetMapping("/logout") + public String logout(HttpServletRequest request, HttpServletResponse response, SecurityContextLogoutHandler logoutHandler) { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + CookieClearingLogoutHandler cookieClearingLogoutHandler = new CookieClearingLogoutHandler(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + cookieClearingLogoutHandler.logout(request, response, auth); + logoutHandler.logout(request, response, auth); + return "auth/logout"; + } + } diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java index 75956cf493..d4800206d4 100644 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/IndexController.java @@ -1,15 +1,19 @@ package com.baeldung.cassecuredapp.controllers; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - @Controller public class IndexController { + private Logger logger = LoggerFactory.getLogger(IndexController.class); + @GetMapping("/") public String index() { + logger.info("Index controller called"); return "index"; } + } diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredController.java new file mode 100644 index 0000000000..0b3ab6199f --- /dev/null +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredController.java @@ -0,0 +1,30 @@ +package com.baeldung.cassecuredapp.controllers; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class SecuredController { + + private Logger logger = LoggerFactory.getLogger(SecuredController.class); + + @GetMapping("/secured") + public String securedIndex(ModelMap modelMap) { + + logger.info("/secured called"); + + Authentication auth = SecurityContextHolder.getContext() + .getAuthentication(); + + if(auth.getPrincipal() instanceof UserDetails) + modelMap.put("username", ((UserDetails) auth.getPrincipal()).getUsername()); + + return "secure/index"; + } +} diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java deleted file mode 100644 index 9a872d1f40..0000000000 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/SecuredPageController.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.cassecuredapp.controllers; - -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -@Controller -@RequestMapping(value = "/secured") -public class SecuredPageController { - - @GetMapping - public String index(ModelMap modelMap) { - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - if( auth != null && auth.getPrincipal() != null - && auth.getPrincipal() instanceof UserDetails) { - modelMap.put("username", ((UserDetails) auth.getPrincipal()).getUsername()); - } - return "secure/index"; - } -} diff --git a/cas/cas-secured-app/src/main/resources/application.properties b/cas/cas-secured-app/src/main/resources/application.properties index 99802c632f..f8789997d5 100644 --- a/cas/cas-secured-app/src/main/resources/application.properties +++ b/cas/cas-secured-app/src/main/resources/application.properties @@ -1 +1,2 @@ -server.port=9000 \ No newline at end of file +server.port=8900 +spring.freemarker.suffix=.ftl \ No newline at end of file diff --git a/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java b/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredApplicationIntegrationTest.java similarity index 84% rename from cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java rename to cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredApplicationIntegrationTest.java index 2f2644e2ea..de13f6665d 100644 --- a/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredAppApplicationIntegrationTest.java +++ b/cas/cas-secured-app/src/test/java/com/baeldung/cassecuredapp/CasSecuredApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class CasSecuredAppApplicationIntegrationTest { +public class CasSecuredApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/cas/cas-server/.factorypath b/cas/cas-server/.factorypath deleted file mode 100644 index 006c761796..0000000000 --- a/cas/cas-server/.factorypath +++ /dev/null @@ -1,228 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cas/cas-server/.gitignore b/cas/cas-server/.gitignore old mode 100644 new mode 100755 index 5304519922..6121b5ea9d --- a/cas/cas-server/.gitignore +++ b/cas/cas-server/.gitignore @@ -2,6 +2,8 @@ !/.project .project .settings +.history +.vscode target/ .idea/ .DS_Store @@ -9,6 +11,11 @@ target/ overlays/ .gradle/ build/ +log/ bin/ +*.war *.iml *.log +tmp/ +./apache-tomcat +apache-tomcat.zip \ No newline at end of file diff --git a/cas/cas-server/.mergify.yml b/cas/cas-server/.mergify.yml new file mode 100644 index 0000000000..4fcbdbe4ac --- /dev/null +++ b/cas/cas-server/.mergify.yml @@ -0,0 +1,32 @@ +# +# Licensed to Apereo under one or more contributor license +# agreements. See the NOTICE file distributed with this work +# for additional information regarding copyright ownership. +# Apereo licenses this file to you under the Apache License, +# Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a +# copy of the License at the following location: +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# + +pull_request_rules: +- name: automatic merge by dependabot + conditions: + - status-success=continuous-integration/travis-ci/pr + - status-success=WIP + - "#changes-requested-reviews-by=0" + - base=master + - label=dependencies + actions: + merge: + method: merge + strict: true + delete_head_branch: \ No newline at end of file diff --git a/cas/cas-server/.travis.yml b/cas/cas-server/.travis.yml new file mode 100644 index 0000000000..8347dd1719 --- /dev/null +++ b/cas/cas-server/.travis.yml @@ -0,0 +1,62 @@ +language: java +sudo: required +dist: trusty +services: + - docker +branches: + only: + - master +before_cache: + - rm -rf $HOME/.gradle/caches/5.*/ + - rm -rf $HOME/.gradle/caches/4.*/ + - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ + - find ~/.gradle/caches/ -name "*.lock" -type f -delete +cache: + bundler: false + cargo: false + directories: + - $HOME/.m2 + - $HOME/.npm/ + - $HOME/.gradle/caches/ + - $HOME/.gradle/wrapper/ +env: + global: + - JAVA_OPTS="-Xms512m -Xmx4048m -Xss128m -XX:ReservedCodeCacheSize=512m -XX:+UseG1GC -Xverify:none -server" + - GRADLE_OPTS="-Xms512m -Xmx1024m -Xss128m -XX:ReservedCodeCacheSize=512m -XX:+UseG1GC -Xverify:none -server" +jdk: +- openjdk11 +before_install: +- echo -e "Configuring Gradle wrapper...\n" +- mkdir -p ~/.gradle && echo "org.gradle.daemon=false" >> ~/.gradle/gradle.properties +- chmod -R 777 ./gradlew +- chmod -R 777 *.sh +install: true +stages: + - build + - validate + - docker +jobs: + include: + - stage: build + script: ./gradlew clean build --stacktrace --no-daemon --refresh-dependencies -Dorg.gradle.internal.http.socketTimeout=600000 -Dorg.gradle.internal.http.connectionTimeout=600000 + name: "Build CAS" + ############################################ + - stage: validate + script: ./gradlew downloadShell + name: "Download CAS Shell" + - stage: validate + script: ./gradlew listTemplateViews + name: "List CAS Template Views" + - stage: validate + script: ./gradlew explodeWar + name: "Unzip CAS Web Application" + ############################################ + - stage: docker + script: ./gradlew build jibDockerBuild --stacktrace --no-daemon --refresh-dependencies + name: "Build Docker Image via Jib" + - stage: docker + script: docker-compose build + name: "Build Docker Image via Docker Compose" + - stage: docker + script: ./docker-build.sh + name: "Build Docker Image" \ No newline at end of file diff --git a/cas/cas-server/Dockerfile b/cas/cas-server/Dockerfile new file mode 100644 index 0000000000..b2f15ef4c3 --- /dev/null +++ b/cas/cas-server/Dockerfile @@ -0,0 +1,40 @@ +FROM adoptopenjdk/openjdk11:alpine-slim AS overlay + +RUN mkdir -p cas-overlay +COPY ./src cas-overlay/src/ +COPY ./gradle/ cas-overlay/gradle/ +COPY ./gradlew ./settings.gradle ./build.gradle ./gradle.properties /cas-overlay/ + +RUN mkdir -p ~/.gradle \ + && echo "org.gradle.daemon=false" >> ~/.gradle/gradle.properties \ + && echo "org.gradle.configureondemand=true" >> ~/.gradle/gradle.properties \ + && cd cas-overlay \ + && chmod 750 ./gradlew \ + && ./gradlew --version; + +RUN cd cas-overlay \ + && ./gradlew clean build --parallel; + +FROM adoptopenjdk/openjdk11:alpine-jre AS cas + +LABEL "Organization"="Apereo" +LABEL "Description"="Apereo CAS" + +RUN cd / \ + && mkdir -p /etc/cas/config \ + && mkdir -p /etc/cas/services \ + && mkdir -p /etc/cas/saml \ + && mkdir -p cas-overlay; + +COPY etc/cas/ /etc/cas/ +COPY etc/cas/config/ /etc/cas/config/ +COPY etc/cas/services/ /etc/cas/services/ +COPY etc/cas/saml/ /etc/cas/saml/ +COPY --from=overlay cas-overlay/build/libs/cas.war cas-overlay/ + +EXPOSE 8080 8443 + +ENV PATH $PATH:$JAVA_HOME/bin:. + +WORKDIR cas-overlay +ENTRYPOINT ["java", "-server", "-noverify", "-Xmx2048M", "-jar", "cas.war"] diff --git a/cas/cas-server/README.md b/cas/cas-server/README.md index 44cfa2246c..b224738732 100644 --- a/cas/cas-server/README.md +++ b/cas/cas-server/README.md @@ -1,105 +1,146 @@ -CAS Overlay Template -============================ +CAS Overlay Template [![Build Status](https://travis-ci.org/apereo/cas-overlay-template.svg?branch=master)](https://travis-ci.org/apereo/cas-overlay-template) +======================= -Generic CAS WAR overlay to exercise the latest versions of CAS. This overlay could be freely used as a starting template for local CAS war overlays. The CAS services management overlay is available [here](https://github.com/apereo/cas-services-management-overlay). +Generic CAS WAR overlay to exercise the latest versions of CAS. This overlay could be freely used as a starting template for local CAS war overlays. # Versions -```xml -5.3.x +- CAS `6.1.x` +- JDK `11` + +# Overview + +To build the project, use: + +```bash +# Use --refresh-dependencies to force-update SNAPSHOT versions +./gradlew[.bat] clean build ``` -# Requirements - -* JDK 1.8+ - -# Configuration - -The `etc` directory contains the configuration files and directories that need to be copied to `/etc/cas/config`. - -# Build - To see what commands are available to the build script, run: ```bash -./build.sh help +./gradlew[.bat] tasks ``` -To package the final web application, run: +To launch into the CAS command-line shell: ```bash -./build.sh package +./gradlew[.bat] downloadShell runShell ``` -To update `SNAPSHOT` versions run: +To fetch and overlay a CAS resource or view, use: ```bash -./build.sh package -U +./gradlew[.bat] getResource -PresourceName=[resource-name] ``` +To list all available CAS views and templates: + +```bash +./gradlew[.bat] listTemplateViews +``` + +To unzip and explode the CAS web application file and the internal resources jar: + +```bash +./gradlew[.bat] explodeWar +``` + +# Configuration + +- The `etc` directory contains the configuration files and directories that need to be copied to `/etc/cas/config`. + +```bash +./gradlew[.bat] copyCasConfiguration +``` + +- The specifics of the build are controlled using the `gradle.properties` file. + +## Adding Modules + +CAS modules may be specified under the `dependencies` block of the [Gradle build script](build.gradle): + +```gradle +dependencies { + compile "org.apereo.cas:cas-server-some-module:${project.casVersion}" + ... +} +``` + +To collect the list of all project modules and dependencies: + +```bash +./gradlew[.bat] allDependencies +``` + +### Clear Gradle Cache + +If you need to, on Linux/Unix systems, you can delete all the existing artifacts (artifacts and metadata) Gradle has downloaded using: + +```bash +# Only do this when absolutely necessary +rm -rf $HOME/.gradle/caches/ +``` + +Same strategy applies to Windows too, provided you switch `$HOME` to its equivalent in the above command. + # Deployment -- Create a keystore file `thekeystore` under `/etc/cas`. Use the password `changeit` for both the keystore and the key/certificate entries. +- Create a keystore file `thekeystore` under `/etc/cas`. Use the password `changeit` for both the keystore and the key/certificate entries. This can either be done using the JDK's `keytool` utility or via the following command: + +```bash +./gradlew[.bat] createKeystore +``` + - Ensure the keystore is loaded up with keys and certificates of the server. On a successful deployment via the following methods, CAS will be available at: -* `http://cas.server.name:8080/cas` * `https://cas.server.name:8443/cas` ## Executable WAR -Run the CAS web application as an executable WAR. +Run the CAS web application as an executable WAR: ```bash -./build.sh run +./gradlew[.bat] run ``` -## Spring Boot - -Run the CAS web application as an executable WAR via Spring Boot. This is most useful during development and testing. +Debug the CAS web application as an executable WAR: ```bash -./build.sh bootrun +./gradlew[.bat] debug ``` -### Warning! +Run the CAS web application as a *standalone* executable WAR: -Be careful with this method of deployment. `bootRun` is not designed to work with already executable WAR artifacts such that CAS server web application. YMMV. Today, uses of this mode ONLY work when there is **NO OTHER** dependency added to the build script and the `cas-server-webapp` is the only present module. See [this issue](https://github.com/spring-projects/spring-boot/issues/8320) for more info. - - -## Spring Boot App Server Selection - -There is an app.server property in the `pom.xml` that can be used to select a spring boot application server. -It defaults to `-tomcat` but `-jetty` and `-undertow` are supported. - -It can also be set to an empty value (nothing) if you want to deploy CAS to an external application server of your choice. - -```xml --tomcat -``` - -## Windows Build - -If you are building on windows, try `build.cmd` instead of `build.sh`. Arguments are similar but for usage, run: - -``` -build.cmd help +```bash +./gradlew[.bat] clean executable ``` ## External -Deploy resultant `target/cas.war` to a servlet container of choice. +Deploy the binary web application file `cas.war` after a successful build to a servlet container of choice. +## Docker -## Command Line Shell +The following strategies outline how to build and deploy CAS Docker images. -Invokes the CAS Command Line Shell. For a list of commands either use no arguments or use `-h`. To enter the interactive shell use `-sh`. +### Jib + +The overlay embraces the [Jib Gradle Plugin](https://github.com/GoogleContainerTools/jib) to provide easy-to-use out-of-the-box tooling for building CAS docker images. Jib is an open-source Java containerizer from Google that lets Java developers build containers using the tools they know. It is a container image builder that handles all the steps of packaging your application into a container image. It does not require you to write a Dockerfile or have Docker installed, and it is directly integrated into the overlay. ```bash -./build.sh cli +./gradlew build jibDockerBuild ``` -### Relevant Articles: +### Dockerfile -- [CAS SSO With Spring Security](https://www.baeldung.com/spring-security-cas-sso) +You can also use the native Docker tooling and the provided `Dockerfile` to build and run CAS. + +```bash +chmod +x *.sh +./docker-build.sh +./docker-run.sh +``` diff --git a/cas/cas-server/build.cmd b/cas/cas-server/build.cmd deleted file mode 100644 index 2cf9262afe..0000000000 --- a/cas/cas-server/build.cmd +++ /dev/null @@ -1,102 +0,0 @@ -@echo off - -@set JAVA_ARGS=-Xms500m -Xmx1g -@set CAS_DIR=\etc\cas -@set CONFIG_DIR=\etc\cas\config - -@rem Call this script with DNAME and CERT_SUBJ_ALT_NAMES already set to override -@if "%DNAME%" == "" set DNAME=CN=cas.example.org,OU=Example,OU=Org,C=US -@rem List other host names or ip addresses you want in your certificate, may help with host name verification, -@rem if client apps make https connection for ticket validation and compare name in cert (include sub. alt. names) -@rem to name used to access CAS -@if "%CERT_SUBJ_ALT_NAMES%" == "" set CERT_SUBJ_ALT_NAMES=dns:example.org,dns:localhost,dns:%COMPUTERNAME%,ip:127.0.0.1 - -@rem Check for mvn in path, use it if found, otherwise use maven wrapper -@set MAVEN_CMD=mvn -@where /q mvn -@if %ERRORLEVEL% neq 0 set MAVEN_CMD=.\mvnw.bat - -@if "%1" == "" call:help -@if "%1" == "copy" call:copy -@if "%1" == "clean" call:clean %2 %3 %4 -@if "%1" == "package" call:package %2 %3 %4 -@if "%1" == "bootrun" call:bootrun %2 %3 %4 -@if "%1" == "debug" call:debug %2 %3 %4 -@if "%1" == "run" call:run %2 %3 %4 -@if "%1" == "runalone" call:runalone %2 %3 %4 -@if "%1" == "help" call:help -@if "%1" == "gencert" call:gencert -@if "%1" == "cli" call:runcli %2 %3 %4 - -@rem function section starts here -@goto:eof - -:copy - @echo "Creating configuration directory under %CONFIG_DIR%" - if not exist %CONFIG_DIR% mkdir %CONFIG_DIR% - - @echo "Copying configuration files from etc/cas to /etc/cas" - xcopy /S /Y etc\cas\* \etc\cas -@goto:eof - -:help - @echo "Usage: build.bat [copy|clean|package|run|debug|bootrun|gencert|cli] [optional extra args for maven or cli]" - @echo "To get started on a clean system, run "build.bat copy" and "build.bat gencert", then "build.bat run" - @echo "Note that using the copy or gencert arguments will create and/or overwrite the %CAS_DIR% which is outside this project" -@goto:eof - -:clean - call %MAVEN_CMD% clean %1 %2 %3 - exit /B %ERRORLEVEL% -@goto:eof - -:package - call %MAVEN_CMD% clean package -T 5 %1 %2 %3 - exit /B %ERRORLEVEL% -@goto:eof - -:bootrun - call %MAVEN_CMD% clean package spring-boot:run -T 5 %1 %2 %3 - exit /B %ERRORLEVEL% -@goto:eof - -:debug - call:package %1 %2 %3 & java %JAVA_ARGS% -Xdebug -Xrunjdwp:transport=dt_socket,address=5000,server=y,suspend=n -jar target/cas.war -@goto:eof - -:run - call:package %1 %2 %3 & java %JAVA_ARGS% -jar target/cas.war -@goto:eof - -:runalone - call:package %1 %2 %3 & target/cas.war -@goto:eof - -:gencert - where /q keytool - if ERRORLEVEL 1 ( - @echo Java keytool.exe not found in path. - exit /b 1 - ) else ( - if not exist %CAS_DIR% mkdir %CAS_DIR% - @echo on - @echo Generating self-signed SSL cert for %DNAME% in %CAS_DIR%\thekeystore - keytool -genkeypair -alias cas -keyalg RSA -keypass changeit -storepass changeit -keystore %CAS_DIR%\thekeystore -dname %DNAME% -ext SAN=%CERT_SUBJ_ALT_NAMES% - @echo Exporting cert for use in trust store (used by cas clients) - keytool -exportcert -alias cas -storepass changeit -keystore %CAS_DIR%\thekeystore -file %CAS_DIR%\cas.cer - ) -@goto:eof - -:runcli - for /f %%i in ('call %MAVEN_CMD% -q --non-recursive "-Dexec.executable=cmd" "-Dexec.args=/C echo ${cas.version}" "org.codehaus.mojo:exec-maven-plugin:1.3.1:exec"') do set CAS_VERSION=%%i - @set CAS_VERSION=%CAS_VERSION: =% - @set DOWNLOAD_DIR=target - @set COMMAND_FILE=cas-server-support-shell-%CAS_VERSION%.jar - @if not exist %DOWNLOAD_DIR% mkdir %DOWNLOAD_DIR% - @if not exist %DOWNLOAD_DIR%\%COMMAND_FILE% ( - @call mvn org.apache.maven.plugins:maven-dependency-plugin:3.0.2:get -DgroupId=org.apereo.cas -DartifactId=cas-server-support-shell -Dversion=%CAS_VERSION% -Dpackaging=jar -DartifactItem.outputDirectory=%DOWNLOAD_DIR% -DartifactItem.destFileName=%COMMAND_FILE% -DremoteRepositories=central::default::http://repo1.maven.apache.org/maven2,snapshots::::https://oss.sonatype.org/content/repositories/snapshots -Dtransitive=false - @call mvn org.apache.maven.plugins:maven-dependency-plugin:3.0.2:copy -Dmdep.useBaseVersion=true -Dartifact=org.apereo.cas:cas-server-support-shell:%CAS_VERSION%:jar -DoutputDirectory=%DOWNLOAD_DIR% - ) - @call java %JAVA_ARGS% -jar %DOWNLOAD_DIR%\%COMMAND_FILE% %1 %2 %3 - -@goto:eof \ No newline at end of file diff --git a/cas/cas-server/build.gradle b/cas/cas-server/build.gradle new file mode 100644 index 0000000000..41381e2d8f --- /dev/null +++ b/cas/cas-server/build.gradle @@ -0,0 +1,106 @@ +buildscript { + repositories { + mavenLocal() + mavenCentral() + jcenter() + maven { url "https://repo.spring.io/libs-milestone" } + maven { url "https://repo.spring.io/libs-snapshot" } + maven { url "https://plugins.gradle.org/m2/" } + } + dependencies { + classpath "de.undercouch:gradle-download-task:${project.gradleDownloadTaskVersion}" + classpath "org.springframework.boot:spring-boot-gradle-plugin:${project.springBootVersion}" + classpath "gradle.plugin.com.google.cloud.tools:jib-gradle-plugin:${project.jibVersion}" + classpath "io.freefair.gradle:maven-plugin:${project.gradleMavenPluginVersion}" + } +} + +repositories { + mavenLocal() + mavenCentral() + jcenter() + maven { url "https://oss.sonatype.org/content/repositories/snapshots" } + maven { url "https://build.shibboleth.net/nexus/content/repositories/releases/" } + maven { url "https://repo.spring.io/milestone/" } + maven { url "https://repo.spring.io/snapshot/" } + maven { url "https://oss.jfrog.org/artifactory/oss-snapshot-local" } +} + +def casServerVersion = project.'cas.version' +def casWebApplicationBinaryName = "cas.war" + +project.ext."casServerVersion" = casServerVersion +project.ext."casWebApplicationBinaryName" = casWebApplicationBinaryName + +apply plugin: "io.freefair.war-overlay" +apply from: rootProject.file("gradle/tasks.gradle") + +apply plugin: "war" +apply plugin: "eclipse" +apply plugin: "idea" + +apply from: rootProject.file("gradle/springboot.gradle") +apply from: rootProject.file("gradle/dockerjib.gradle") + +dependencies { + // Other CAS dependencies/modules may be listed here... + compile "org.apereo.cas:cas-server-support-json-service-registry:${casServerVersion}" + compile "org.apereo.cas:cas-server-support-jdbc:${casServerVersion}" +} + +tasks.findByName("jibDockerBuild") + .dependsOn(copyWebAppIntoJib, copyConfigIntoJib) + .finalizedBy(deleteWebAppFromJib) + +tasks.findByName("jib") + .dependsOn(copyWebAppIntoJib, copyConfigIntoJib) + .finalizedBy(deleteWebAppFromJib) + +configurations.all { + resolutionStrategy { + cacheChangingModulesFor 0, "seconds" + cacheDynamicVersionsFor 0, "seconds" + + preferProjectModules() + + def failIfConflict = project.hasProperty("failOnVersionConflict") && Boolean.valueOf(project.getProperty("failOnVersionConflict")) + if (failIfConflict) { + failOnVersionConflict() + } + } +} + +eclipse { + classpath { + downloadSources = true + downloadJavadoc = true + } +} + +idea { + module { + downloadJavadoc = true + downloadSources = true + } +} + +bootWar { + entryCompression = ZipEntryCompression.STORED + overlays { + // https://docs.freefair.io/gradle-plugins/current/reference/#_io_freefair_war_overlay + // Note: The "excludes" property is only for files in the war dependency. + // If a jar is excluded from the war, it could be brought back into the final war as a dependency + // of non-war dependencies. Those should be excluded via normal gradle dependency exclusions. + cas { + from "org.apereo.cas:cas-server-webapp${project.appServer}:${casServerVersion}@war" + provided = false + //excludes = ["WEB-INF/lib/somejar-1.0*"] + } + } +} + + +wrapper { + distributionType = Wrapper.DistributionType.BIN + gradleVersion = "${project.gradleVersion}" +} diff --git a/cas/cas-server/build.sh b/cas/cas-server/build.sh deleted file mode 100644 index 4d80aa2593..0000000000 --- a/cas/cas-server/build.sh +++ /dev/null @@ -1,189 +0,0 @@ -#!/bin/bash - - -function copy() { - echo -e "Creating configuration directory under /etc/cas" - mkdir -p /etc/cas/config - - echo -e "Copying configuration files from etc/cas to /etc/cas" - cp -rfv etc/cas/* /etc/cas -} - -function help() { - echo "Usage: build.sh [copy|clean|package|run|debug|bootrun|gencert]" - echo " copy: Copy config from ./etc/cas/config to /etc/cas/config" - echo " clean: Clean Maven build directory" - echo " package: Clean and build CAS war" - echo " run: Build and run cas.war via Java (i.e. java -jar target/cas.war)" - echo " runalone: Build and run cas.war on its own as a standalone executable (target/cas.war)" - echo " debug: Run CAS.war and listen for Java debugger on port 5000" - echo " bootrun: Run with maven spring boot plugin" - echo " listviews: List all CAS views that ship with the web application and can be customized in the overlay" - echo " getview: Ask for a view name to be included in the overlay for customizations" - echo " gencert: Create keystore with SSL certificate in location where CAS looks by default" - echo " cli: Run the CAS command line shell and pass commands" -} - -function clean() { - shift - ./mvnw clean "$@" -} - -function package() { - shift - ./mvnw clean package -T 5 "$@" - # copy -} - -function bootrun() { - shift - ./mvnw clean package spring-boot:run -P bootiful -T 5 "$@" -} - -function debug() { - package && java -Xdebug -Xrunjdwp:transport=dt_socket,address=5000,server=y,suspend=n -jar target/cas.war -} - -function run() { - package && java -jar target/cas.war -} - -function runalone() { - shift - ./mvnw clean package -P default,exec "$@" - chmod +x target/cas.war - target/cas.war -} - -function listviews() { - shift - explodeapp - find $PWD/target/cas -type f -name "*.html" | xargs -n 1 basename | sort | more -} - -function explodeapp() { - if [ ! -d $PWD/target/cas ];then - echo "Building the CAS web application and exploding the final war file..." - ./mvnw clean package war:exploded "$@" - fi - echo "Exploded the CAS web application file." -} - -function getview() { - shift - explodeapp - echo "Searching for view name $@..." - results=`find $PWD/target/cas -type f -name "*.html" | grep -i "$@"` - echo -e "Found view(s): \n$results" - count=`wc -w <<< "$results"` - if [ "$count" -eq 1 ];then - # echo "Found view $results to include in the overlay" - firststring="target/cas/WEB-INF/classes" - secondstring="src/main/resources" - overlayfile=`echo "${results/$firststring/$secondstring}"` - overlaypath=`dirname "${overlayfile}"` - # echo "Overlay file is $overlayfile to be created at $overlaypath" - mkdir -p $overlaypath - cp $results $overlaypath - echo "Created view at $overlayfile" - ls $overlayfile - else - echo "More than one view file is found. Narrow down the search query..." - fi -} - - -function gencert() { - if [[ ! -d /etc/cas ]] ; then - copy - fi - which keytool - if [[ $? -ne 0 ]] ; then - echo Error: Java JDK \'keytool\' is not installed or is not in the path - exit 1 - fi - # override DNAME and CERT_SUBJ_ALT_NAMES before calling or use dummy values - DNAME="${DNAME:-CN=cas.example.org,OU=Example,OU=Org,C=US}" - CERT_SUBJ_ALT_NAMES="${CERT_SUBJ_ALT_NAMES:-dns:example.org,dns:localhost,ip:127.0.0.1}" - echo "Generating keystore for CAS with DN ${DNAME}" - keytool -genkeypair -alias cas -keyalg RSA -keypass changeit -storepass changeit -keystore /etc/cas/thekeystore -dname ${DNAME} -ext SAN=${CERT_SUBJ_ALT_NAMES} - keytool -exportcert -alias cas -storepass changeit -keystore /etc/cas/thekeystore -file /etc/cas/cas.cer -} - -function cli() { - - CAS_VERSION=$(./mvnw -q -Dexec.executable="echo" -Dexec.args='${cas.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec 2>/dev/null) - # echo "CAS version: $CAS_VERSION" - JAR_FILE_NAME="cas-server-support-shell-${CAS_VERSION}.jar" - # echo "JAR name: $JAR_FILE_NAME" - JAR_PATH="org/apereo/cas/cas-server-support-shell/${CAS_VERSION}/${JAR_FILE_NAME}" - # echo "JAR path: $JAR_PATH" - - JAR_FILE_LOCAL="$HOME/.m2/repository/$JAR_PATH"; - # echo "Local JAR file path: $JAR_FILE_LOCAL"; - if [ -f "$JAR_FILE_LOCAL" ]; then - # echo "Using JAR file locally at $JAR_FILE_LOCAL" - java -jar $JAR_FILE_LOCAL "$@" - exit 0; - fi - - DOWNLOAD_DIR=./target - COMMAND_FILE="${DOWNLOAD_DIR}/${JAR_FILE_NAME}" - if [ ! -f "$COMMAND_FILE" ]; then - mkdir -p $DOWNLOAD_DIR - ./mvnw org.apache.maven.plugins:maven-dependency-plugin:3.0.2:get -DgroupId=org.apereo.cas -DartifactId=cas-server-support-shell -Dversion=$CAS_VERSION -Dpackaging=jar -DartifactItem.outputDirectory=$DOWNLOAD_DIR -DremoteRepositories=central::default::http://repo1.maven.apache.org/maven2,snapshots::::https://oss.sonatype.org/content/repositories/snapshots -Dtransitive=false - ./mvnw org.apache.maven.plugins:maven-dependency-plugin:3.0.2:copy -Dmdep.useBaseVersion=true -Dartifact=org.apereo.cas:cas-server-support-shell:$CAS_VERSION:jar -DoutputDirectory=$DOWNLOAD_DIR - fi - java -jar $COMMAND_FILE "$@" - exit 0; - -} - -if [ $# -eq 0 ]; then - echo -e "No commands provided. Defaulting to [run]\n" - run - exit 0 -fi - -case "$1" in -"copy") - copy - ;; -"clean") - shift - clean "$@" - ;; -"package") - shift - package "$@" - ;; -"bootrun") - shift - bootrun "$@" - ;; -"debug") - debug "$@" - ;; -"run") - run "$@" - ;; -"runalone") - runalone "$@" - ;; -"listviews") - listviews "$@" - ;; -"gencert") - gencert "$@" - ;; -"getview") - getview "$@" - ;; -"cli") - shift - cli "$@" - ;; -*) - help - ;; -esac diff --git a/cas/cas-server/docker-build.sh b/cas/cas-server/docker-build.sh new file mode 100755 index 0000000000..8f2c2776bf --- /dev/null +++ b/cas/cas-server/docker-build.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +image_tag=(`cat gradle.properties | grep "cas.version" | cut -d= -f2`) + +echo "Building CAS docker image tagged as [$image_tag]" +# read -p "Press [Enter] to continue..." any_key; + +docker build --tag="org.apereo.cas/cas:$image_tag" . \ + && echo "Built CAS image successfully tagged as org.apereo.cas/cas:$image_tag" \ + && docker images "org.apereo.cas/cas:$image_tag" \ No newline at end of file diff --git a/cas/cas-server/docker-compose.yml b/cas/cas-server/docker-compose.yml new file mode 100644 index 0000000000..8f2e6ca7c9 --- /dev/null +++ b/cas/cas-server/docker-compose.yml @@ -0,0 +1,7 @@ +version: '3' +services: + cas: + build: . + ports: + - "8443:8443" + - "8080:8080" \ No newline at end of file diff --git a/cas/cas-server/docker-push.sh b/cas/cas-server/docker-push.sh new file mode 100755 index 0000000000..e04b107212 --- /dev/null +++ b/cas/cas-server/docker-push.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +read -p "Docker username: " docker_user +read -s -p "Docker password: " docker_psw + +echo "$docker_psw" | docker login --username "$docker_user" --password-stdin + +image_tag=(`cat gradle.properties | grep "cas.version" | cut -d= -f2`) + +echo "Pushing CAS docker image tagged as $image_tag to org.apereo.cas/cas..." +docker push org.apereo.cas/cas:"$image_tag" \ + && echo "Pushed org.apereo.cas/cas:$image_tag successfully."; \ No newline at end of file diff --git a/cas/cas-server/docker-run.sh b/cas/cas-server/docker-run.sh new file mode 100755 index 0000000000..f8627859f2 --- /dev/null +++ b/cas/cas-server/docker-run.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +docker stop cas > /dev/null 2>&1 +docker rm cas > /dev/null 2>&1 +image_tag=(`cat gradle.properties | grep "cas.version" | cut -d= -f2`) +docker run -d -p 8080:8080 -p 8443:8443 --name="cas" org.apereo.cas/cas:"${image_tag}" +docker logs -f cas \ No newline at end of file diff --git a/cas/cas-server/etc/cas/config/application.yml b/cas/cas-server/etc/cas/config/application.yml deleted file mode 100644 index be1f7c3edd..0000000000 --- a/cas/cas-server/etc/cas/config/application.yml +++ /dev/null @@ -1,2 +0,0 @@ -info: - description: CAS Configuration \ No newline at end of file diff --git a/cas/cas-server/etc/cas/config/cas.properties b/cas/cas-server/etc/cas/config/cas.properties index 47a1477308..a3be0e1388 100644 --- a/cas/cas-server/etc/cas/config/cas.properties +++ b/cas/cas-server/etc/cas/config/cas.properties @@ -1,7 +1,6 @@ -cas.server.name: https://cas.example.org:8443 -cas.server.prefix: https://cas.example.org:8443/cas - -cas.adminPagesSecurity.ip=127\.0\.0\.1 +cas.server.name=https://cas.example.org:8443 +cas.server.prefix=${cas.server.name}/cas logging.config: file:/etc/cas/config/log4j2.xml -# cas.serviceRegistry.config.location: classpath:/services + +# cas.authn.accept.users= diff --git a/cas/cas-server/etc/cas/config/log4j2.xml b/cas/cas-server/etc/cas/config/log4j2.xml index e688cc0350..685dfab245 100644 --- a/cas/cas-server/etc/cas/config/log4j2.xml +++ b/cas/cas-server/etc/cas/config/log4j2.xml @@ -2,20 +2,26 @@ - - . - - warn + /var/log + + info + warn + info + warn + debug + warn + warn + warn + warn + warn + warn - + - + @@ -23,8 +29,8 @@ - + @@ -33,16 +39,6 @@ - - - - - - - - - @@ -52,52 +48,58 @@ - - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cas/cas-server/etc/cas/saml/.gitkeep b/cas/cas-server/etc/cas/saml/.gitkeep new file mode 100644 index 0000000000..882c99944d --- /dev/null +++ b/cas/cas-server/etc/cas/saml/.gitkeep @@ -0,0 +1 @@ +This directory is references in the Dockerfile so it needs to be here. \ No newline at end of file diff --git a/cas/cas-server/etc/cas/services/.donotdel b/cas/cas-server/etc/cas/services/.donotdel new file mode 100644 index 0000000000..e69de29bb2 diff --git a/cas/cas-server/etc/cas/thekeystore b/cas/cas-server/etc/cas/thekeystore new file mode 100644 index 0000000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) { + casRunArgs.addAll(project.args.split('\\s+')) + } + javaexec { + main = "-jar" + jvmArgs = casRunArgs + args = ["build/libs/${casWebApplicationBinaryName}"] + logger.info "Started ${commandLine}" + } + } +} + +task setExecutable(group: "build", description: "Configure the project to run in executable mode") { + doFirst { + project.setProperty("executable", "true") + logger.info "Configuring the project as executable" + } +} + +task executable(type:Exec, group: "build", description: "Run the CAS web application in standalone executable mode") { + dependsOn setExecutable, 'build' + doFirst { + workingDir "." + if (!Os.isFamily(Os.FAMILY_WINDOWS)) { + commandLine "chmod", "+x", bootWar.archivePath + } + logger.info "Running ${bootWar.archivePath}" + commandLine bootWar.archivePath + } +} + +task debug(group: "build", description: "Debug the CAS web application in embedded mode on port 5005") { + dependsOn 'build' + doLast { + logger.info "Debugging process is started in a suspended state, listening on port 5005." + def casArgs = Arrays.asList("-Xmx2048M".split(" ")) + javaexec { + main = "-jar" + jvmArgs = casArgs + debug = true + args = ["build/libs/${casWebApplicationBinaryName}"] + logger.info "Started ${commandLine}" + } + } +} + +task downloadShell(group: "shell", description: "Download CAS shell jar from snapshot or release maven repo") { + doFirst { + mkdir "${project.shellDir}" + } + doLast { + def downloadFile + if (isRunningCasServerSnapshot(casServerVersion)) { + def snapshotDir = "https://oss.sonatype.org/content/repositories/snapshots/org/apereo/cas/cas-server-support-shell/${casServerVersion}/" + def files = new ApacheURLLister().listFiles(new URL(snapshotDir)) + files = files.sort{it.path} + files.each { + if (it.path.endsWith(".jar")) { + downloadFile = it + } + } + } else { + downloadFile = "https://repo1.maven.org/maven2/org/apereo/cas/cas-server-support-shell/${casServerVersion}/cas-server-support-shell-${casServerVersion}.jar" + } + logger.info "Downloading file: ${downloadFile}" + download { + src downloadFile + dest new File("${project.shellDir}", "cas-server-support-shell-${casServerVersion}.jar") + overwrite false + } + } +} + +task runShell(group: "shell", description: "Run the CAS shell") { + dependsOn downloadShell + doLast { + println "Run the following command to launch the shell:\n\tjava -jar ${project.shellDir}/cas-server-support-shell-${casServerVersion}.jar" + } +} + +task debugShell(group: "shell", description: "Run the CAS shell with debug options, wait for debugger on port 5005") { + dependsOn downloadShell + doLast { + println """ + Run the following command to launch the shell:\n\t + java -Xrunjdwp:transport=dt_socket,address=5000,server=y,suspend=y -jar ${project.shellDir}/cas-server-support-shell-${casServerVersion}.jar + """ + } +} + +task showConfiguration(group: "build", description: "Show configurations for each dependency, etc") { + doLast() { + def cfg = project.hasProperty("configuration") ? project.property("configuration") : "compile" + configurations.getByName(cfg).each { println it } + } +} + +task allDependenciesInsight(group: "build", type: DependencyInsightReportTask, description: "Produce insight information for all dependencies") {} + +task allDependencies(group: "build", type: DependencyReportTask, description: "Display a graph of all project dependencies") {} + +task casVersion (group: "build", description: "Display the current CAS version") { + doFirst { + def verbose = project.hasProperty("verbose") && Boolean.valueOf(project.getProperty("verbose")) + if (verbose) { + def out = services.get(StyledTextOutputFactory).create("CAS") + println "******************************************************************" + out.withStyle(Style.Info).println "Apereo CAS $casServerVersion" + out.withStyle(Style.Description).println "Enterprise Single SignOn for all earthlings and beyond" + out.withStyle(Style.SuccessHeader).println "- GitHub: " + out.withStyle(Style.Success).println "https://github.com/apereo/cas" + out.withStyle(Style.SuccessHeader).println "- Docs: " + out.withStyle(Style.Success).println "https://apereo.github.io/cas" + out.withStyle(Style.SuccessHeader).println "- Blog: " + out.withStyle(Style.Success).println "https://apereo.github.io" + println "******************************************************************" + } else { + println casServerVersion + } + } +} + +task createKeystore(group: "build", description: "Create CAS keystore") { + doFirst { + mkdir "/etc/cas" + + def keystorePath = "/etc/cas/thekeystore" + + def dn = "CN=cas.example.org,OU=Example,OU=Org,C=US" + if (project.hasProperty("certificateDn")) { + dn = project.getProperty("certificateDn") + } + def subjectAltName = "dns:example.org,dns:localhost,ip:127.0.0.1" + if (project.hasProperty("certificateSubAltName")) { + subjectAltName = project.getProperty("certificateSubAltName") + } + // this will fail if thekeystore exists and has cert with cas alias already (so delete if you want to recreate) + logger.info "Generating keystore for CAS with DN ${dn}" + exec { + workingDir "." + commandLine "keytool", "-genkeypair", "-alias", "cas", + "-keyalg", "RSA", + "-keypass", "changeit", "-storepass", "changeit", + "-keystore", keystorePath, + "-dname", dn, "-ext", "SAN=${subjectAltName}" + } + logger.info "Exporting cert from keystore..." + exec { + workingDir "." + commandLine "keytool", "-exportcert", "-alias", "cas", + "-storepass", "changeit", "-keystore", keystorePath, + "-file", "/etc/cas/cas.cer" + } + logger.info "Import /etc/cas/cas.cer into your Java truststore (JAVA_HOME/lib/security/cacerts)" + } +} + +task listTemplateViews (group: "build", description: "List all CAS views") { + dependsOn explodeWar + + doFirst { + fileTree(explodedResourcesDir).matching { + include "**/*.html" + } + .collect { it.name } + .toSorted() + .each { println it } + } +} + +task getResource(group: "build", description: "Fetch a CAS resource and move it into the overlay") { + dependsOn explodeWar + + doFirst { + def resourceName = project.getProperty("resourceName") + + def results = fileTree(explodedResourcesDir).matching { + include "**/${resourceName}.*" + } + if (results.isEmpty()) { + println "No resources could be found matching ${resourceName}" + return + } + if (results.size() > 1) { + println "Multiple resources found matching ${resourceName}: ${results}" + return + } + + def fromFile = explodedResourcesDir + def resourcesDir = "src/main/resources" + mkdir resourcesDir + + def resourceFile = results[0].canonicalPath + def toResourceFile = resourceFile.replace(fromFile, resourcesDir) + + def parent = file(toResourceFile).getParent() + mkdir parent + + Files.copy(Paths.get(resourceFile), Paths.get(toResourceFile), StandardCopyOption.REPLACE_EXISTING) + println "Copied file ${resourceFile} to ${toResourceFile}" + } +} + +def isRunningCasServerSnapshot(casServerVersion) { + return "${casServerVersion}".contains("-SNAPSHOT") +} \ No newline at end of file diff --git a/cas/cas-server/gradle/wrapper/gradle-wrapper.properties b/cas/cas-server/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..f04d6a20ae --- /dev/null +++ b/cas/cas-server/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.3-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/cas/cas-server/gradlew b/cas/cas-server/gradlew new file mode 100755 index 0000000000..83f2acfdc3 --- /dev/null +++ b/cas/cas-server/gradlew @@ -0,0 +1,188 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/cas/cas-server/gradlew.bat b/cas/cas-server/gradlew.bat new file mode 100644 index 0000000000..24467a141f --- /dev/null +++ b/cas/cas-server/gradlew.bat @@ -0,0 +1,100 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/cas/cas-server/maven/maven-wrapper.jar b/cas/cas-server/maven/maven-wrapper.jar deleted file mode 100644 index 18ba302c65c4f71f57e0daa0ea1b59cb85759b5c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 71910 zcmb@t1#nzTk}fR97BgAQ%wRDyGoytqwpg+xics%_`HC{i2v=+-@jl#e&xheh3KW^#Tga8TMq8G2zD=z{|F1Wei1 zP_t5ZxFL@rk09iG>Nb7qRU%rtJHVct@57ZND9C>p2Li(Pmp(vz7-wP!{7>`$tHdAX z{~_UM2{d!GbF#Df>TGFe>+~-)aQ`nFKqD73+kc@)@-Ox5ZN8dY{>yf0{-5++9gXbm z%^d&1j;Ftj3DU=N{?o7j&S>WUD*Q2841XCdhQB?A;lK9buWkP^!T!?rzkl4{yF~xD zM(F=+V}v z%l|YG=5O;m0fyU-_(O&8<6{4~{=3=xr=|blkN+?M=wjH^QLz*e z$q@i!j}Z3g0JwL0utz9UQ&e_P+ynd1nEJC#*YlE;1W*tVG;k0Q?*DC@48}&zfy(2y z>rBWU@G}B*5H+m@aE|nbISmufC}*J0vG{PvbdxK>=*mQ^MQ<;09t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t=ayXwtA3Pvj#8)2EgP6ewPdQo$u=kSjRtA-fyD)Li?*C?f;r? zU~_7Y7%=*9!02CmM;9jeujvF0jjZhq|B;x|;F;n&fS5vnohW?Aiz@oBd4+WC4S_uV zhF12b4yI0q@<0r}l`)`Y8(kn6;`d$AA6=o|aV2CF=~){ zxxXs zdFod$3RnLhDgRbX&pX4HEr6Ifz`**w=jLkukDR|+@?V<~v5@X`F+jHnc+mIF*{bt@ zqWe4Dwh(HdJ^_fC0Al{{nsZeDUlaeWR>@!CUwi=AjDh~}>q`FbPrfgg(Z6O>v@-t} zjykS8E}#j#1`q*nci)d=VW$6<`mfut`SwMEAm9~n0L%9b&w$m8pSt8PiZl3aDET_O z`D=zs#38(GKz+JEV*x|sA5XsTnBTu;_|@nCnup3rdN~MiI96c96#IkatHZ$t{T+{; zwV9#5!~ZgO3Phic4hC4s0anrPSTBSBhV{n);6G{dZ>Be{4ZOAG0NFM0Vfv1AGxR5< z&kc=q9W5N5|8cSUf17yBohfwC0Zld!^j-4b;je}LEBqft1T^g8D&Xi~0?ZRl_5b_G zh?0FDvhmd_fz=0w?<(LO`EM%l*Ov0*74*Lo9P0Z&;ZXkd_#n^&{TRyoBf*a$g5L;~j{ctD`+&heWB=9e`8Vw3tN&OY(EmT} urT>}wuNLyZQ3r#7{{LDW0c!khSzlHH0+_G?%iF*|4PXJr;p \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Migwn, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` -fi - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - local basedir=$(pwd) - local wdir=$(pwd) - while [ "$wdir" != '/' ] ; do - wdir=$(cd "$wdir/.."; pwd) - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER="org.apache.maven.wrapper.MavenWrapperMain" - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - -classpath \ -"$MAVEN_PROJECTBASEDIR/maven/maven-wrapper.jar" \ - ${WRAPPER_LAUNCHER} "$@" diff --git a/cas/cas-server/mvnw.bat b/cas/cas-server/mvnw.bat deleted file mode 100644 index d391151aa7..0000000000 --- a/cas/cas-server/mvnw.bat +++ /dev/null @@ -1,174 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto chkMHome - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:chkMHome -if not "%M2_HOME%"=="" goto valMHome - -SET "M2_HOME=%~dp0.." -if not "%M2_HOME%"=="" goto valMHome - -echo. -echo Error: M2_HOME not found in your environment. >&2 -echo Please set the M2_HOME variable in your environment to match the >&2 -echo location of the Maven installation. >&2 -echo. -goto error - -:valMHome - -:stripMHome -if not "_%M2_HOME:~-1%"=="_\" goto checkMCmd -set "M2_HOME=%M2_HOME:~0,-1%" -goto stripMHome - -:checkMCmd -if exist "%M2_HOME%\bin\mvn.cmd" goto init - -echo. -echo Error: M2_HOME is set to an invalid directory. >&2 -echo M2_HOME = "%M2_HOME%" >&2 -echo Please set the M2_HOME variable in your environment to match the >&2 -echo location of the Maven installation >&2 -echo. -goto error -@REM ==== END VALIDATION ==== - -:init - -set MAVEN_CMD_LINE_ARGS=%* - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\maven\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% - -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/cas/cas-server/pom.xml b/cas/cas-server/pom.xml index abcf251667..e69de29bb2 100644 --- a/cas/cas-server/pom.xml +++ b/cas/cas-server/pom.xml @@ -1,208 +0,0 @@ - - - 4.0.0 - cas-server - 1.0 - cas-server - war - - - com.baeldung - parent-boot-1 - 0.0.1-SNAPSHOT - ../../parent-boot-1 - - - - - org.apereo.cas - cas-server-support-json-service-registry - ${cas.version} - - - org.apereo.cas - cas-server-support-jdbc - ${cas.version} - - - org.apereo.cas - cas-server-support-jdbc-drivers - ${cas.version} - - - - - - - com.rimerosolutions.maven.plugins - wrapper-maven-plugin - ${wrapper-maven-plugin.version} - - true - MD5 - - - - org.springframework.boot - spring-boot-maven-plugin - - ${mainClassName} - true - ${isExecutable} - WAR - - - - - repackage - - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - cas - false - false - - false - ${manifestFileToUse} - - - - org.apereo.cas - cas-server-webapp${app.server} - - - - - - cas - - - - - - true - - default - - - org.apereo.cas - cas-server-webapp${app.server} - ${cas.version} - war - runtime - - - - - - - - false - - exec - - org.apereo.cas.web.CasWebApplication - true - - - - - - com.soebes.maven.plugins - echo-maven-plugin - ${echo-maven-plugin.version} - - - prepare-package - - echo - - - - - - Executable profile to make the generated CAS web application executable. - - - - - - - - - - false - - bootiful - - -tomcat - false - - - - org.apereo.cas - cas-server-webapp${app.server} - ${cas.version} - war - runtime - - - - - - - false - - pgp - - - - com.github.s4u.plugins - pgpverify-maven-plugin - ${pgpverify-maven-plugin.version} - - - - check - - - - - hkp://pool.sks-keyservers.net - ${settings.localRepository}/pgpkeys-cache - test - true - false - - - - - - - - - 5.3.3 - - -tomcat - - org.springframework.boot.loader.WarLauncher - false - ${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF - - 0.0.4 - 2.6 - - 0.3.0 - 1.1.0 - - - diff --git a/cas/cas-server/settings.gradle b/cas/cas-server/settings.gradle new file mode 100644 index 0000000000..3ad50900ea --- /dev/null +++ b/cas/cas-server/settings.gradle @@ -0,0 +1 @@ +rootProject.name='cas' \ No newline at end of file diff --git a/cas/cas-server/src/main/jib/docker/entrypoint.sh b/cas/cas-server/src/main/jib/docker/entrypoint.sh new file mode 100755 index 0000000000..a3a0895b04 --- /dev/null +++ b/cas/cas-server/src/main/jib/docker/entrypoint.sh @@ -0,0 +1,22 @@ +#!/bin/sh + +#echo -e "\nChecking java..." +#java -version + +#echo -e "\nCreating CAS configuration directories..." +mkdir -p /etc/cas/config +mkdir -p /etc/cas/services + +#echo "Listing provided CAS docker artifacts..." +#ls -R docker/cas + +#echo -e "\nMoving CAS configuration artifacts..." +mv docker/cas/thekeystore /etc/cas 2>/dev/null +mv docker/cas/config/*.* /etc/cas/config 2>/dev/null +mv docker/cas/services/*.* /etc/cas/services 2>/dev/null + +#echo -e "\nListing CAS configuration under /etc/cas..." +#ls -R /etc/cas + +echo -e "\nRunning CAS..." +exec java -Xms512m -Xmx2048M -XX:+TieredCompilation -XX:TieredStopAtLevel=1 -jar docker/cas/war/cas.war diff --git a/cas/cas-server/src/main/resources/application.properties b/cas/cas-server/src/main/resources/application.properties index 7735fcabdc..185532f943 100644 --- a/cas/cas-server/src/main/resources/application.properties +++ b/cas/cas-server/src/main/resources/application.properties @@ -1,134 +1,4 @@ -## -# CAS Server Context Configuration -# -server.context-path=/cas -server.port=6443 - +server.port=8443 +spring.main.allow-bean-definition-overriding=true server.ssl.key-store=classpath:/etc/cas/thekeystore -server.ssl.key-store-password=changeit -server.ssl.key-password=changeit -# server.ssl.ciphers= -# server.ssl.client-auth= -# server.ssl.enabled= -# server.ssl.key-alias= -# server.ssl.key-store-provider= -# server.ssl.key-store-type= -# server.ssl.protocol= -# server.ssl.trust-store= -# server.ssl.trust-store-password= -# server.ssl.trust-store-provider= -# server.ssl.trust-store-type= - -server.max-http-header-size=2097152 -server.use-forward-headers=true -server.connection-timeout=20000 -server.error.include-stacktrace=NEVER - -server.tomcat.max-http-post-size=2097152 -server.tomcat.basedir=build/tomcat -server.tomcat.accesslog.enabled=true -server.tomcat.accesslog.pattern=%t %a "%r" %s (%D ms) -server.tomcat.accesslog.suffix=.log -server.tomcat.max-threads=10 -server.tomcat.port-header=X-Forwarded-Port -server.tomcat.protocol-header=X-Forwarded-Proto -server.tomcat.protocol-header-https-value=https -server.tomcat.remote-ip-header=X-FORWARDED-FOR -server.tomcat.uri-encoding=UTF-8 - -spring.http.encoding.charset=UTF-8 -spring.http.encoding.enabled=true -spring.http.encoding.force=true - -## -#CAS CONFIG LOCATION -# -standalone.config=classpath:/etc/cas/config - - -## -# CAS Cloud Bus Configuration -# -spring.cloud.bus.enabled=false -# spring.cloud.bus.refresh.enabled=true -# spring.cloud.bus.env.enabled=true -# spring.cloud.bus.destination=CasCloudBus -# spring.cloud.bus.ack.enabled=true - -endpoints.enabled=false -endpoints.sensitive=true - -endpoints.restart.enabled=false -endpoints.shutdown.enabled=false - -management.security.enabled=true -management.security.roles=ACTUATOR,ADMIN -management.security.sessions=if_required -management.context-path=/status -management.add-application-context-header=false - -security.basic.authorize-mode=role -security.basic.enabled=false -security.basic.path=/cas/status/** - -## -# CAS Web Application Session Configuration -# -server.session.timeout=300 -server.session.cookie.http-only=true -server.session.tracking-modes=COOKIE - -## -# CAS Thymeleaf View Configuration -# -spring.thymeleaf.encoding=UTF-8 -spring.thymeleaf.cache=true -spring.thymeleaf.mode=HTML -## -# CAS Log4j Configuration -# -# logging.config=file:/etc/cas/log4j2.xml - -server.context-parameters.isLog4jAutoInitializationDisabled=true - -## -# CAS AspectJ Configuration -# -spring.aop.auto=true -spring.aop.proxy-target-class=true - -## -# CAS Authentication Credentials -# -#cas.authn.accept.users=casuser::Mellon -cas.authn.accept.users= -cas.authn.accept.name= - -#CAS Database Authentication Property -cas.authn.jdbc.query[0].sql=SELECT * FROM users WHERE email = ? -cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC -cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect -cas.authn.jdbc.query[0].user=root -cas.authn.jdbc.query[0].password=1234 -cas.authn.jdbc.query[0].ddlAuto=none -#cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver -cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver -cas.authn.jdbc.query[0].fieldPassword=password -cas.authn.jdbc.query[0].passwordEncoder.type=NONE - - -## -# CAS Delegated Authentication -# -cas.authn.pac4j.bitbucket.clientName=Bitbucket -cas.authn.pac4j.dropbox.clientName=Dropbox -cas.authn.pac4j.facebook.clientName=Facebook -cas.authn.pac4j.foursquare.clientName=Foursquare -cas.authn.pac4j.github.clientName=Github -cas.authn.pac4j.google.clientName=Google -cas.authn.pac4j.linkedIn.clientName=LinkedIn -cas.authn.pac4j.paypal.clientName=PayPal -cas.authn.pac4j.twitter.clientName=Twitter -cas.authn.pac4j.yahoo.clientName=Yahoo -cas.authn.pac4j.windowsLive.clientName=Windows Live -cas.authn.pac4j.wordpress.clientName=WordPress +server.ssl.key-store-password=changeit \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/cas.properties b/cas/cas-server/src/main/resources/cas.properties deleted file mode 100644 index e39d68f312..0000000000 --- a/cas/cas-server/src/main/resources/cas.properties +++ /dev/null @@ -1,9 +0,0 @@ -cas.server.name: https://localhost:6443 -cas.server.prefix: https://localhost:643/cas - -cas.adminPagesSecurity.ip=127\.0\.0\.1 - -logging.config: file:/etc/cas/config/log4j2.xml - -cas.serviceRegistry.initFromJson=true -cas.serviceRegistry.config.location=classpath:/services \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql b/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql index 79a4a48a82..104b515813 100644 --- a/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql +++ b/cas/cas-server/src/main/resources/create_test_db_and_users_tbl.sql @@ -4,13 +4,13 @@ USE `test`; -- Dumping structure for table test.users CREATE TABLE IF NOT EXISTS `users` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `email` varchar(50) DEFAULT NULL, - `password` text DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; + `id` int(11) NOT NULL AUTO_INCREMENT, + `email` varchar(50) DEFAULT NULL, + `password` text DEFAULT NULL, + PRIMARY KEY (`id`) + ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; /*!40000 ALTER TABLE `users` DISABLE KEYS */; INSERT INTO `users` (`id`, `email`, `password`) VALUES - (1, 'test@test.com', 'Mellon'); + (1, 'test@test.com', 'Mellon'); /*!40000 ALTER TABLE `users` ENABLE KEYS */; \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/config/application.yml b/cas/cas-server/src/main/resources/etc/cas/config/application.yml deleted file mode 100644 index be1f7c3edd..0000000000 --- a/cas/cas-server/src/main/resources/etc/cas/config/application.yml +++ /dev/null @@ -1,2 +0,0 @@ -info: - description: CAS Configuration \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/config/cas.properties b/cas/cas-server/src/main/resources/etc/cas/config/cas.properties index 47a1477308..dda939bc1d 100644 --- a/cas/cas-server/src/main/resources/etc/cas/config/cas.properties +++ b/cas/cas-server/src/main/resources/etc/cas/config/cas.properties @@ -1,7 +1,15 @@ -cas.server.name: https://cas.example.org:8443 -cas.server.prefix: https://cas.example.org:8443/cas +cas.serviceRegistry.initFromJson=true +cas.serviceRegistry.json.location=classpath:/etc/cas/services -cas.adminPagesSecurity.ip=127\.0\.0\.1 -logging.config: file:/etc/cas/config/log4j2.xml -# cas.serviceRegistry.config.location: classpath:/services +cas.authn.accept.users= + +cas.authn.jdbc.query[0].sql=SELECT * FROM users WHERE email = ? +cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC +cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect +cas.authn.jdbc.query[0].user=root +cas.authn.jdbc.query[0].password=smattroot +cas.authn.jdbc.query[0].ddlAuto=none +cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver +cas.authn.jdbc.query[0].fieldPassword=password +cas.authn.jdbc.query[0].passwordEncoder.type=NONE \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml b/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml deleted file mode 100644 index e688cc0350..0000000000 --- a/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - . - - warn - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cas/cas-server/src/main/resources/etc/cas/services/casSecuredApp-8900.json b/cas/cas-server/src/main/resources/etc/cas/services/casSecuredApp-8900.json new file mode 100644 index 0000000000..5d468945ff --- /dev/null +++ b/cas/cas-server/src/main/resources/etc/cas/services/casSecuredApp-8900.json @@ -0,0 +1,8 @@ +{ + "@class" : "org.apereo.cas.services.RegexRegisteredService", + "serviceId" : "http://cas-client:8900/login/cas", + "name" : "casSecuredApp", + "id" : 8900, + "logoutType" : "BACK_CHANNEL", + "logoutUrl" : "http://cas-client:8900/exit/cas" +} \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/thekeystore b/cas/cas-server/src/main/resources/etc/cas/thekeystore index 77bf895249a044c3320c6dd79003dd108c369c3b..a361bf03f9f77a8356cd0f5369f29e6965aa8cee 100644 GIT binary patch delta 1998 zcmV;<2Qm245z7&O{_Xzl00002000010000100U!Ta{vGVaH)mM2LJ#C0x*IE{xA*( z3M&Qy1OX}n5di@O00e>r>JTevl?8iHU**OQuXwP_equ#0yJWpYt6vAcu(G-#DdgT(@6f9j_Di@G1{c9Ud@9nzJB*274?7O9+;%L(aiLju)5vjga{5 zPOP~&?DHXiJd_gi?ALS)VY*u;NRKvdviqjbkaNggdvzj-MA?c^j9o6y^fE3oq8}Sb zZI0mI*SBFh>@)<_z4$}F?- z^8*D{=2I|FpyW?udqvC!ik%1ua_d5fiI_CHsi0@FNdF+;u=*in6%l|1A-I z=-IGehUETa(&YU9>rV_RsDTeFqm_Rg*n>zM@wYo1H2gZ>{0}kj^hd0v+}|(thG{%z z(v?lLttAHYf_CXPuio?*|A^8(In@j2Ei7mZ^V1TXiZ0(Zv^Ilgn~LTwX%xh92=*YOf(Ou{37~S@`EmZ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ef688a08439af5a75accd1cf5d4bedfce3bd9a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 901 zcmXqLVs12OV#-{=%*4pV#FD?sAkl!AjZ>@5qwPB{BO^B}gF&Gow*e;`b0`a&FjG;! zp^$+9h{GYwnUkNKn3IuTTmlng$0EjsMT{GZ7&DTXft)z6p@o5|k%gg&k-4d56p(8P zuimboeq`zQ69QGU z6Ux18*X$`=Te0j~Yv)#ABD-l#nCoa=Ow5c7jEfZwzj*}F0-agOPYL6FZJSWllzuu6ekFzDZOsdn^valvVGIxKPs#KZCDcX zYeU_kr=prmpDb7>sw-|%Se=z}&9U25zH6IWMbl%o^_op?3Rxy<$MX7aCZ$WiS~klz zMVuqVdZC1{SohYqn>=e{f2KaIb9CTR$XIaik8d4g%GNZ#ini+3$NKu$?)1Lw)MgWY zBgqz>xrs&ZT!FOwg$-OSzb|_|eX{+3@#55T5BF@WZVz8{VlBHk?~$$RPMsIJp8r?& zr=;HTe1|iR|J70(dMB;ya4*U<_;WeogLdF56QO_0AEsYF-!9qhH}j#e#Ep0WqPkU< diff --git a/cas/cas-server/src/main/resources/log4j2.xml b/cas/cas-server/src/main/resources/log4j2.xml deleted file mode 100644 index e688cc0350..0000000000 --- a/cas/cas-server/src/main/resources/log4j2.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - . - - warn - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/cas/cas-server/src/main/resources/services/casSecuredApp-19991.json b/cas/cas-server/src/main/resources/services/casSecuredApp-19991.json deleted file mode 100644 index 336007e484..0000000000 --- a/cas/cas-server/src/main/resources/services/casSecuredApp-19991.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "@class" : "org.apereo.cas.services.RegexRegisteredService", - "serviceId" : "^http://localhost:9000/login/cas", - "name" : "CAS Spring Secured App", - "description": "This is a Spring App that usses the CAS Server for it's authentication", - "id" : 19991, - "evaluationOrder" : 1 -} \ No newline at end of file diff --git a/cas/pom.xml b/cas/pom.xml index 77fae3b50a..e69de29bb2 100644 --- a/cas/pom.xml +++ b/cas/pom.xml @@ -1,23 +0,0 @@ - - - 4.0.0 - cas - cas - pom - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - .. - - - - cas-secured-app - cas-server - - - diff --git a/pom.xml b/pom.xml index 04a2ce054c..e82390a37e 100644 --- a/pom.xml +++ b/pom.xml @@ -388,7 +388,6 @@ blade bootique - cas cdi checker-plugin @@ -899,7 +898,6 @@ blade bootique - cas cdi checker-plugin From 35bbf9c8845c7c6091afdefb5fb49e8f54035f1c Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Mon, 30 Mar 2020 01:29:02 +0430 Subject: [PATCH 046/187] 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 047/187] 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 048/187] 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 1734250d97b95af9f44e02cf6933bc22ed1a9355 Mon Sep 17 00:00:00 2001 From: Mona Mohamadinia Date: Mon, 30 Mar 2020 21:44:37 +0430 Subject: [PATCH 049/187] Added the Static Resource Examples (#8786) --- .../src/main/resources/application.properties | 5 ++++- .../src/main/resources/files/about.html | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 spring-boot-modules/spring-boot-mvc-2/src/main/resources/files/about.html diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/application.properties index 709574239b..7070d4c2f0 100644 --- a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/application.properties @@ -1 +1,4 @@ -spring.main.allow-bean-definition-overriding=true \ No newline at end of file +spring.main.allow-bean-definition-overriding=true +spring.mvc.static-path-pattern=/content/** +spring.webflux.static-path-pattern=/content/** +spring.resources.static-locations=classpath:/files/,classpath:/static-files \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc-2/src/main/resources/files/about.html b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/files/about.html new file mode 100644 index 0000000000..15df316612 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc-2/src/main/resources/files/about.html @@ -0,0 +1,10 @@ + + + + + Hello World! + + +Hello World! + + \ No newline at end of file From 8bfb7df3b2c2463e9ea584bf79c9c19c8ef525ff Mon Sep 17 00:00:00 2001 From: Roman <32590063+oskar9247@users.noreply.github.com> Date: Mon, 30 Mar 2020 22:25:55 +0200 Subject: [PATCH 050/187] BAEL-3822 Spring Boot MVC controller return HTML (#8988) Co-authored-by: Oskar <> --- .../com/baeldung/html/HtmlApplication.java | 12 ++++++++ .../com/baeldung/html/HtmlController.java | 17 +++++++++++ .../com/baeldung/html/HtmlControllerTest.java | 30 +++++++++++++++++++ 3 files changed, 59 insertions(+) create mode 100644 spring-5-mvc/src/main/java/com/baeldung/html/HtmlApplication.java create mode 100644 spring-5-mvc/src/main/java/com/baeldung/html/HtmlController.java create mode 100644 spring-5-mvc/src/test/java/com/baeldung/html/HtmlControllerTest.java diff --git a/spring-5-mvc/src/main/java/com/baeldung/html/HtmlApplication.java b/spring-5-mvc/src/main/java/com/baeldung/html/HtmlApplication.java new file mode 100644 index 0000000000..ad660559c7 --- /dev/null +++ b/spring-5-mvc/src/main/java/com/baeldung/html/HtmlApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.html; + +import org.springframework.boot.*; +import org.springframework.boot.autoconfigure.*; + +@SpringBootApplication +public class HtmlApplication +{ + public static void main(String[] args) { + SpringApplication.run(HtmlApplication.class, args); + } +} diff --git a/spring-5-mvc/src/main/java/com/baeldung/html/HtmlController.java b/spring-5-mvc/src/main/java/com/baeldung/html/HtmlController.java new file mode 100644 index 0000000000..23674d165e --- /dev/null +++ b/spring-5-mvc/src/main/java/com/baeldung/html/HtmlController.java @@ -0,0 +1,17 @@ +package com.baeldung.html; + +import org.springframework.http.*; +import org.springframework.stereotype.*; +import org.springframework.web.bind.annotation.*; + +@Controller +public class HtmlController +{ + @GetMapping(value = "/welcome", produces = MediaType.TEXT_HTML_VALUE) + @ResponseBody + public String welcomeAsHTML() + { + return "\n" + "

Welcome
\n" + + "\n" + "Hello world\n" + "\n" + ""; + } +} diff --git a/spring-5-mvc/src/test/java/com/baeldung/html/HtmlControllerTest.java b/spring-5-mvc/src/test/java/com/baeldung/html/HtmlControllerTest.java new file mode 100644 index 0000000000..8eba4e8cf9 --- /dev/null +++ b/spring-5-mvc/src/test/java/com/baeldung/html/HtmlControllerTest.java @@ -0,0 +1,30 @@ +package com.baeldung.html; + +import org.junit.jupiter.api.*; +import org.springframework.beans.factory.annotation.*; +import org.springframework.boot.test.autoconfigure.web.servlet.*; +import org.springframework.test.web.servlet.*; +import org.springframework.test.web.servlet.request.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@WebMvcTest(HtmlController.class) +class HtmlControllerUnitTest { + + @Autowired + private MockMvc mockMvc; + + private final String expectedHtmlResponse = + "\n" + "
Welcome
\n" + + "\n" + "Hello world\n" + "\n" + ""; + + @Test + void whenGETRequestToCorrectURL_thenReturnCorrectWelcomeMessage() throws Exception { + MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/welcome")) + .andExpect(status().isOk()) + .andReturn(); + + String resultDOW = result.getResponse().getContentAsString(); + assertEquals(expectedHtmlResponse, resultDOW); + } +} From 2d5782d4327ed494bef6cc30903abf4bdbf092ec Mon Sep 17 00:00:00 2001 From: Mihai238 Date: Mon, 30 Mar 2020 22:59:12 +0200 Subject: [PATCH 051/187] add guava throwables example (#8984) Co-authored-by: Mihai Lepadat --- .../baeldung/guava/ThrowablesUnitTest.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 guava/src/test/java/com/baeldung/guava/ThrowablesUnitTest.java diff --git a/guava/src/test/java/com/baeldung/guava/ThrowablesUnitTest.java b/guava/src/test/java/com/baeldung/guava/ThrowablesUnitTest.java new file mode 100644 index 0000000000..7d33b38a0e --- /dev/null +++ b/guava/src/test/java/com/baeldung/guava/ThrowablesUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.guava; + +import com.google.common.base.Throwables; +import org.junit.Test; + +import java.util.function.Supplier; + +public class ThrowablesUnitTest { + + @Test(expected = RuntimeException.class) + public void whenThrowable_shouldWrapItInRuntimeException() throws Exception { + try { + throwThrowable(Throwable::new); + } catch (Throwable t) { + Throwables.propagateIfPossible(t, Exception.class); + throw new RuntimeException(t); + } + } + + @Test(expected = Error.class) + public void whenError_shouldPropagateAsIs() throws Exception { + try { + throwThrowable(Error::new); + } catch (Throwable t) { + Throwables.propagateIfPossible(t, Exception.class); + throw new RuntimeException(t); + } + } + + @Test(expected = Exception.class) + public void whenException_shouldPropagateAsIs() throws Exception { + try { + throwThrowable(Exception::new); + } catch (Throwable t) { + Throwables.propagateIfPossible(t, Exception.class); + throw new RuntimeException(t); + } + } + + private void throwThrowable(Supplier exceptionSupplier) throws Throwable { + throw exceptionSupplier.get(); + } + +} From 2fb2f89bd4d443dbbc5c1205b57e9dcdc6870479 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Mon, 30 Mar 2020 23:06:47 +0200 Subject: [PATCH 052/187] BAEL-3477: Add usage example for the mutable key (#8987) --- .../com/baeldung/map/ProductUnitTest.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java b/java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java index 2015909870..ba29d5c454 100644 --- a/java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java +++ b/java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java @@ -3,6 +3,8 @@ package com.baeldung.map; import org.junit.jupiter.api.Test; import java.util.HashMap; +import java.util.Map; +import java.util.Objects; import static org.junit.jupiter.api.Assertions.*; @@ -121,4 +123,52 @@ class ProductUnitTest { assertNull(productsByName.get("E-Bike")); } + @Test + public void givenMutableKeyWhenKeyChangeThenValueNotFound() { + // Given + MutableKey key = new MutableKey("initial"); + + Map items = new HashMap<>(); + items.put(key, "success"); + + // When + key.setName("changed"); + + // Then + assertNull(items.get(key)); + } + + static class MutableKey { + private String name; + + public MutableKey(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MutableKey that = (MutableKey) o; + return Objects.equals(name, that.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + } + } From 16e6ddc2e3e8749f26b22be495234ef3ab119e21 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Mon, 30 Mar 2020 23:10:57 +0200 Subject: [PATCH 053/187] BAEL-3060: Cleanup JMXTutorialMainlauncher (#8991) --- .../baeldung/jmx/JMXTutorialMainlauncher.java | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java index 21044f82c4..e2a60ac384 100644 --- a/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java +++ b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmx/JMXTutorialMainlauncher.java @@ -3,7 +3,12 @@ package com.baeldung.jmx; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.management.*; +import javax.management.InstanceAlreadyExistsException; +import javax.management.MBeanRegistrationException; +import javax.management.MBeanServer; +import javax.management.MalformedObjectNameException; +import javax.management.NotCompliantMBeanException; +import javax.management.ObjectName; import java.lang.management.ManagementFactory; public class JMXTutorialMainlauncher { @@ -11,24 +16,21 @@ public class JMXTutorialMainlauncher { private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class); public static void main(String[] args) { - // TODO Auto-generated method stub LOG.debug("This is basic JMX tutorial"); - ObjectName objectName = null; + try { - objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game"); - } catch (MalformedObjectNameException e) { - e.printStackTrace(); - } - MBeanServer server = ManagementFactory.getPlatformMBeanServer(); - Game gameObj = new Game(); - try { - server.registerMBean(gameObj, objectName); - } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) { + ObjectName objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game"); + MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + server.registerMBean(new Game(), objectName); + } catch (MalformedObjectNameException | InstanceAlreadyExistsException | + MBeanRegistrationException | NotCompliantMBeanException e) { e.printStackTrace(); } + LOG.debug("Registration for Game mbean with the platform server is successfull"); LOG.debug("Please open jconsole to access Game mbean"); + while (true) { // to ensure application does not terminate } From 3f83ed67d3511a057bbf5b0db8e56f214ffd88a7 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Mon, 30 Mar 2020 23:27:11 +0200 Subject: [PATCH 054/187] 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 055/187] 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 056/187] 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 b2a07b9fdf4ba1183da7dd2294432bf1a414ab9c Mon Sep 17 00:00:00 2001 From: kwoyke Date: Tue, 31 Mar 2020 08:54:14 +0200 Subject: [PATCH 057/187] BAEL-2681: Upgrade core-java-collections-set to Java 11 (#8998) * BAEL-2681: Upgrade core-java-collections-set to Java 11 * BAEL-2681: Comment out core-java-collections-set from the pom.xml --- .../core-java-collections-set/pom.xml | 16 ++++++++++++++++ core-java-modules/pom.xml | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-collections-set/pom.xml b/core-java-modules/core-java-collections-set/pom.xml index 8ba1b2400d..c89ba0c091 100644 --- a/core-java-modules/core-java-collections-set/pom.xml +++ b/core-java-modules/core-java-collections-set/pom.xml @@ -34,7 +34,23 @@ + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + 11 + 11 4.3 2.8.5 diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 5e7ffa37b9..ebdb11925b 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -42,7 +42,7 @@ core-java-collections-list core-java-collections-list-2 core-java-collections-list-3 - core-java-collections-set + core-java-concurrency-2 core-java-concurrency-advanced From 8c69054becc77089a9cc7d27ea7959617e440736 Mon Sep 17 00:00:00 2001 From: Amit Pandey Date: Tue, 31 Mar 2020 19:25:52 +0530 Subject: [PATCH 058/187] renamed integration test to manual test (#8934) * renamed integration test to manual test * added comments in manual test case --- ...tegrationTest.java => JGitBugManualTest.java} | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) rename jgit/src/test/java/com/baeldung/jgit/{JGitBugIntegrationTest.java => JGitBugManualTest.java} (67%) diff --git a/jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/jgit/src/test/java/com/baeldung/jgit/JGitBugManualTest.java similarity index 67% rename from jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java rename to jgit/src/test/java/com/baeldung/jgit/JGitBugManualTest.java index ad34890996..bcfe615bc7 100644 --- a/jgit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java +++ b/jgit/src/test/java/com/baeldung/jgit/JGitBugManualTest.java @@ -10,10 +10,18 @@ import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertNotNull; -/** - * Tests which show issues with JGit that we reported upstream. - */ -public class JGitBugIntegrationTest { +public class JGitBugManualTest { + + /** + * This test case expects one git repository to be present in local file system. + * Currently this test uses the Baeldung repository i.e. the current checkout repository. + * It finds the repository by tracking back and scan file system to find .git folder in + * the file system. + * + * Before running the test case ensure that the .git folder is present. + * + * @throws IOException + */ @Test public void testRevWalkDisposeClosesReader() throws IOException { try (Repository repo = Helper.openJGitRepository()) { From 1e052c5a721be544899a146080b5103f1af2c8d5 Mon Sep 17 00:00:00 2001 From: Amy DeGregorio Date: Tue, 31 Mar 2020 12:02:54 -0400 Subject: [PATCH 059/187] BAEL-3827 Add CSS and JS to Thymeleaf (#8985) * BAEL-3827 Add CSS and JS to Thymeleaf * BAEL-3827 Add integration tests * BAEL-3827 Add new spring-thymeleaf-3 module to the parent pom.xml * BAEL-3827 Add new spring-thymeleaf-3 module to the parent pom.xml in both places --- pom.xml | 2 + spring-thymeleaf-3/README.md | 5 ++ spring-thymeleaf-3/pom.xml | 78 +++++++++++++++++++ .../com/baeldung/thymeleaf/Application.java | 11 +++ .../cssandjs/CssAndJsApplication.java | 11 +++ .../cssandjs/CssAndJsController.java | 15 ++++ .../resources/static/js/cssandjs/actions.js | 7 ++ .../resources/static/styles/cssandjs/main.css | 18 +++++ .../templates/cssandjs/styledPage.html | 20 +++++ .../thymeleaf/ApplicationIntegrationTest.java | 13 ++++ .../CssAndJsControllerIntegrationTest.java | 41 ++++++++++ 11 files changed, 221 insertions(+) create mode 100644 spring-thymeleaf-3/README.md create mode 100644 spring-thymeleaf-3/pom.xml create mode 100644 spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/Application.java create mode 100644 spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsApplication.java create mode 100644 spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsController.java create mode 100644 spring-thymeleaf-3/src/main/resources/static/js/cssandjs/actions.js create mode 100644 spring-thymeleaf-3/src/main/resources/static/styles/cssandjs/main.css create mode 100644 spring-thymeleaf-3/src/main/resources/templates/cssandjs/styledPage.html create mode 100644 spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/ApplicationIntegrationTest.java create mode 100644 spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/cssandjs/CssAndJsControllerIntegrationTest.java diff --git a/pom.xml b/pom.xml index e82390a37e..9f132ca7a8 100644 --- a/pom.xml +++ b/pom.xml @@ -729,6 +729,7 @@ spring-threads spring-thymeleaf spring-thymeleaf-2 + spring-thymeleaf-3 spring-vault spring-vertx @@ -1229,6 +1230,7 @@ spring-thymeleaf spring-thymeleaf-2 + spring-thymeleaf-3 spring-vault spring-vertx diff --git a/spring-thymeleaf-3/README.md b/spring-thymeleaf-3/README.md new file mode 100644 index 0000000000..e1ddd727d7 --- /dev/null +++ b/spring-thymeleaf-3/README.md @@ -0,0 +1,5 @@ +## Spring Thymeleaf 3 + +This module contains articles about Spring with Thymeleaf + +## Relevant Articles: \ No newline at end of file diff --git a/spring-thymeleaf-3/pom.xml b/spring-thymeleaf-3/pom.xml new file mode 100644 index 0000000000..7677e50d79 --- /dev/null +++ b/spring-thymeleaf-3/pom.xml @@ -0,0 +1,78 @@ + + + 4.0.0 + spring-thymeleaf-3 + spring-thymeleaf-3 + war + + + 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-thymeleaf + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.thymeleaf.cssandjs.CssAndJsApplication + JAR + + + + org.apache.maven.plugins + maven-war-plugin + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + ${tomcat7-maven-plugin.version} + + + tomcat-run + + exec-war-only + + package + + / + false + webapp.jar + utf-8 + + + + + + spring-thymeleaf-3 + + + + 1.8 + 1.8 + 2.2 + + + diff --git a/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/Application.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/Application.java new file mode 100644 index 0000000000..2ccca82497 --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/Application.java @@ -0,0 +1,11 @@ +package com.baeldung.thymeleaf; + +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-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsApplication.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsApplication.java new file mode 100644 index 0000000000..fc6c142b8b --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.thymeleaf.cssandjs; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CssAndJsApplication { + public static void main(String[] args) { + SpringApplication.run(CssAndJsApplication.class, args); + } +} diff --git a/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsController.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsController.java new file mode 100644 index 0000000000..b56a7b468e --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/cssandjs/CssAndJsController.java @@ -0,0 +1,15 @@ +package com.baeldung.thymeleaf.cssandjs; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class CssAndJsController { + + @GetMapping("/styled-page") + public String getStyledPage(Model model) { + model.addAttribute("name", "Baeldung Reader"); + return "cssandjs/styledPage"; + } +} diff --git a/spring-thymeleaf-3/src/main/resources/static/js/cssandjs/actions.js b/spring-thymeleaf-3/src/main/resources/static/js/cssandjs/actions.js new file mode 100644 index 0000000000..e192e6358e --- /dev/null +++ b/spring-thymeleaf-3/src/main/resources/static/js/cssandjs/actions.js @@ -0,0 +1,7 @@ +function showAlert() { + alert("The button was clicked!"); +} + +function showName(name) { + alert("Here's the name: " + name); +} \ No newline at end of file diff --git a/spring-thymeleaf-3/src/main/resources/static/styles/cssandjs/main.css b/spring-thymeleaf-3/src/main/resources/static/styles/cssandjs/main.css new file mode 100644 index 0000000000..1f57b4616a --- /dev/null +++ b/spring-thymeleaf-3/src/main/resources/static/styles/cssandjs/main.css @@ -0,0 +1,18 @@ +h2 { + font-family: sans-serif; + font-size: 1.5em; + text-transform: uppercase; +} + +strong { + font-weight: 700; + background-color: yellow; +} + +p { + font-family: sans-serif; +} + +label { + font-weight: 600; +} \ No newline at end of file diff --git a/spring-thymeleaf-3/src/main/resources/templates/cssandjs/styledPage.html b/spring-thymeleaf-3/src/main/resources/templates/cssandjs/styledPage.html new file mode 100644 index 0000000000..12e4fc9227 --- /dev/null +++ b/spring-thymeleaf-3/src/main/resources/templates/cssandjs/styledPage.html @@ -0,0 +1,20 @@ + + + + + Add CSS and JS to Thymeleaf + + + + + +

Carefully Styled Heading

+

+ This is text on which we want to apply very special styling. +

+

+ + + \ No newline at end of file diff --git a/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/ApplicationIntegrationTest.java b/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/ApplicationIntegrationTest.java new file mode 100644 index 0000000000..b7cfa140f0 --- /dev/null +++ b/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/ApplicationIntegrationTest.java @@ -0,0 +1,13 @@ +package com.baeldung.thymeleaf; + +import org.junit.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +public class ApplicationIntegrationTest { + + @Test + public void contextLoads() { + + } +} diff --git a/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/cssandjs/CssAndJsControllerIntegrationTest.java b/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/cssandjs/CssAndJsControllerIntegrationTest.java new file mode 100644 index 0000000000..365608bd2a --- /dev/null +++ b/spring-thymeleaf-3/src/test/java/com/baeldung/thymeleaf/cssandjs/CssAndJsControllerIntegrationTest.java @@ -0,0 +1,41 @@ +package com.baeldung.thymeleaf.cssandjs; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = CssAndJsApplication.class) +public class CssAndJsControllerIntegrationTest { + @Autowired + private WebApplicationContext context; + + private MockMvc mockMvc; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); + } + + @Test + public void whenCalledGetStyledPage_thenReturnContent() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/styled-page")) + .andExpect(status().isOk()) + .andExpect(view().name("cssandjs/styledPage")) + .andExpect(content().string(containsString("Carefully Styled Heading"))); + } +} From dc5f7efe47ca47050a4e6f5a0534a0fd1bb870be Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Tue, 31 Mar 2020 22:04:57 +0430 Subject: [PATCH 060/187] Fixing the False Sharing of the Data.sql File --- .../main/resources/application-lazy-load-no-trans-off.properties | 1 + .../main/resources/application-lazy-load-no-trans-on.properties | 1 + .../src/main/resources/{data.sql => data-trans.sql} | 0 3 files changed, 2 insertions(+) rename persistence-modules/spring-boot-persistence-h2/src/main/resources/{data.sql => data-trans.sql} (100%) diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-off.properties b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-off.properties index b5fb841685..1055806ecf 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-off.properties +++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-off.properties @@ -5,6 +5,7 @@ spring.datasource.password= spring.jpa.hibernate.ddl-auto=create-drop spring.h2.console.enabled=true spring.h2.console.path=/h2-console +spring.datasource.data=data-trans.sql logging.level.org.hibernate.SQL=INFO logging.level.org.hibernate.type=TRACE diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-on.properties b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-on.properties index 04579e1dae..77aacf0d77 100644 --- a/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-on.properties +++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/application-lazy-load-no-trans-on.properties @@ -5,6 +5,7 @@ spring.datasource.password= spring.jpa.hibernate.ddl-auto=create-drop spring.h2.console.enabled=true spring.h2.console.path=/h2-console +spring.datasource.data=data-trans.sql logging.level.org.hibernate.SQL=INFO logging.level.org.hibernate.type=TRACE diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/data.sql b/persistence-modules/spring-boot-persistence-h2/src/main/resources/data-trans.sql similarity index 100% rename from persistence-modules/spring-boot-persistence-h2/src/main/resources/data.sql rename to persistence-modules/spring-boot-persistence-h2/src/main/resources/data-trans.sql From d1b40a0c026a07b5780e85bd8170f3a397967189 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Tue, 31 Mar 2020 22:55:19 +0200 Subject: [PATCH 061/187] 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 408d19ffe96953c96a551e143d4f8f412617ae5c Mon Sep 17 00:00:00 2001 From: Krzysztof Woyke Date: Wed, 1 Apr 2020 09:35:52 +0200 Subject: [PATCH 062/187] BAEL-3181: Add bytebuddy dependency --- spring-5-mvc/pom.xml | 7 ++++++- spring-5-mvc/src/main/resources/application.properties | 3 --- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 2f8ef05bff..4b42528d0f 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -42,6 +42,11 @@ org.slf4j jcl-over-slf4j + + net.bytebuddy + byte-buddy + ${byte-buddy.version} + org.jetbrains.kotlin @@ -175,8 +180,8 @@ 2.9.0 2.9.9 1.2.71 - com.baeldung.Spring5Application 4.5.8 + com.baeldung.Spring5Application diff --git a/spring-5-mvc/src/main/resources/application.properties b/spring-5-mvc/src/main/resources/application.properties index 886ea1978b..ccec014c2b 100644 --- a/spring-5-mvc/src/main/resources/application.properties +++ b/spring-5-mvc/src/main/resources/application.properties @@ -1,6 +1,3 @@ server.port=8081 -security.user.name=user -security.user.password=pass - logging.level.root=INFO \ 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 063/187] 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 064/187] 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 b56b71cf5f223ec31965844d5601ab319aa3ba2b Mon Sep 17 00:00:00 2001 From: kwoyke Date: Wed, 1 Apr 2020 20:42:54 +0200 Subject: [PATCH 065/187] BAEL-2682: Move java-immutable-set article to core-java-collections-set module (#9001) --- core-java-modules/core-java-9/README.md | 1 - core-java-modules/core-java-collections-set/README.md | 1 + .../src/main/java/com/baeldung}/set/UnmodifiableSet.java | 2 +- .../src/test/java/com/baeldung/set}/SetExamplesUnitTest.java | 5 +++-- 4 files changed, 5 insertions(+), 4 deletions(-) rename core-java-modules/{core-java-9/src/main/java/com/baeldung/java9 => core-java-collections-set/src/main/java/com/baeldung}/set/UnmodifiableSet.java (97%) rename core-java-modules/{core-java-9/src/test/java/com/baeldung/java9 => core-java-collections-set/src/test/java/com/baeldung/set}/SetExamplesUnitTest.java (97%) diff --git a/core-java-modules/core-java-9/README.md b/core-java-modules/core-java-9/README.md index 2dbf159750..0a9bf76ac4 100644 --- a/core-java-modules/core-java-9/README.md +++ b/core-java-modules/core-java-9/README.md @@ -8,5 +8,4 @@ This module contains articles about Java 9 core features - [Introduction to Chronicle Queue](https://www.baeldung.com/java-chronicle-queue) - [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range) - [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) -- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set) - [Immutable ArrayList in Java](https://www.baeldung.com/java-immutable-list) diff --git a/core-java-modules/core-java-collections-set/README.md b/core-java-modules/core-java-collections-set/README.md index 2b34ef3449..b97cd3216f 100644 --- a/core-java-modules/core-java-collections-set/README.md +++ b/core-java-modules/core-java-collections-set/README.md @@ -11,3 +11,4 @@ This module contains articles about the Java Set collection - [Guide to EnumSet](https://www.baeldung.com/java-enumset) - [Set Operations in Java](https://www.baeldung.com/java-set-operations) - [Copying Sets in Java](https://www.baeldung.com/java-copy-sets) +- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set) diff --git a/core-java-modules/core-java-9/src/main/java/com/baeldung/java9/set/UnmodifiableSet.java b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/UnmodifiableSet.java similarity index 97% rename from core-java-modules/core-java-9/src/main/java/com/baeldung/java9/set/UnmodifiableSet.java rename to core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/UnmodifiableSet.java index 7dbcd2a3a3..2af040b13e 100644 --- a/core-java-modules/core-java-9/src/main/java/com/baeldung/java9/set/UnmodifiableSet.java +++ b/core-java-modules/core-java-collections-set/src/main/java/com/baeldung/set/UnmodifiableSet.java @@ -1,4 +1,4 @@ -package com.baeldung.java9.set; +package com.baeldung.set; import com.google.common.collect.ImmutableSet; diff --git a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java b/core-java-modules/core-java-collections-set/src/test/java/com/baeldung/set/SetExamplesUnitTest.java similarity index 97% rename from core-java-modules/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java rename to core-java-modules/core-java-collections-set/src/test/java/com/baeldung/set/SetExamplesUnitTest.java index 28e71affcc..d89927dfd6 100644 --- a/core-java-modules/core-java-9/src/test/java/com/baeldung/java9/SetExamplesUnitTest.java +++ b/core-java-modules/core-java-collections-set/src/test/java/com/baeldung/set/SetExamplesUnitTest.java @@ -1,9 +1,10 @@ -package com.baeldung.java9; +package com.baeldung.set; + +import org.junit.Test; import java.util.Collections; import java.util.HashSet; import java.util.Set; -import org.junit.Test; import static org.junit.Assert.assertEquals; From b4610e110f34e6a394640928fa52da8efdd22827 Mon Sep 17 00:00:00 2001 From: Kumar Chandrakant Date: Thu, 2 Apr 2020 00:23:38 +0530 Subject: [PATCH 066/187] Adding code for article tracked under BAEL-3573. (#8999) Co-authored-by: CHANDRAKANT Kumar --- .../core-java-concurrency-testing/.gitignore | 26 ++++++ .../core-java-concurrency-testing/README.md | 7 ++ .../core-java-concurrency-testing/pom.xml | 93 +++++++++++++++++++ .../com/baeldung/concurrent/MyCounter.java | 22 +++++ .../src/main/resources/logback.xml | 19 ++++ .../concurrent/MyCounterJCStressUnitTest.java | 36 +++++++ .../MyCounterMultithreadedTCUnitTest.java | 35 +++++++ .../concurrent/MyCounterSimpleUnitTest.java | 57 ++++++++++++ .../MyCounterTempusFugitUnitTest.java | 35 +++++++ .../MyCounterThreadWeaverUnitTest.java | 42 +++++++++ .../src/test/resources/.gitignore | 13 +++ 11 files changed, 385 insertions(+) create mode 100644 core-java-modules/core-java-concurrency-testing/.gitignore create mode 100644 core-java-modules/core-java-concurrency-testing/README.md create mode 100644 core-java-modules/core-java-concurrency-testing/pom.xml create mode 100644 core-java-modules/core-java-concurrency-testing/src/main/java/com/baeldung/concurrent/MyCounter.java create mode 100644 core-java-modules/core-java-concurrency-testing/src/main/resources/logback.xml create mode 100644 core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterJCStressUnitTest.java create mode 100644 core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java create mode 100644 core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java create mode 100644 core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java create mode 100644 core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java create mode 100644 core-java-modules/core-java-concurrency-testing/src/test/resources/.gitignore diff --git a/core-java-modules/core-java-concurrency-testing/.gitignore b/core-java-modules/core-java-concurrency-testing/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/.gitignore @@ -0,0 +1,26 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +*.txt +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-testing/README.md b/core-java-modules/core-java-concurrency-testing/README.md new file mode 100644 index 0000000000..fef74a6750 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/README.md @@ -0,0 +1,7 @@ +========= + +## Core Java Concurrency Testing Examples + +### Relevant Articles: +- [Testing Multi-Threaded Code in Java](https://www.baeldung.com/java-testing-multithreaded) + diff --git a/core-java-modules/core-java-concurrency-testing/pom.xml b/core-java-modules/core-java-concurrency-testing/pom.xml new file mode 100644 index 0000000000..bb3e6f5152 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/pom.xml @@ -0,0 +1,93 @@ + + + 4.0.0 + core-java-concurrency-testing + 0.1.0-SNAPSHOT + core-java-concurrency-testing + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + junit + junit + 4.13 + test + + + com.googlecode.thread-weaver + threadweaver + 0.2 + test + + + com.google.code.tempus-fugit + tempus-fugit + 1.1 + test + + + com.googlecode.multithreadedtc + multithreadedtc + 1.01 + test + + + org.openjdk.jcstress + jcstress-core + 0.5 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${javac.target} + ${javac.target} + ${javac.target} + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.2 + + + main + package + + shade + + + jcstress + + + org.openjdk.jcstress.Main + + + META-INF/TestList + + + + + + + + + + diff --git a/core-java-modules/core-java-concurrency-testing/src/main/java/com/baeldung/concurrent/MyCounter.java b/core-java-modules/core-java-concurrency-testing/src/main/java/com/baeldung/concurrent/MyCounter.java new file mode 100644 index 0000000000..a678b047a8 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/main/java/com/baeldung/concurrent/MyCounter.java @@ -0,0 +1,22 @@ +package com.baeldung.concurrent; + +public class MyCounter { + + private int count; + + public void increment() { + int temp = count; + count = temp + 1; + } + + public synchronized void incrementWithWait() throws InterruptedException { + int temp = count; + wait(100); + count = temp + 1; + } + + public int getCount() { + return count; + } + +} diff --git a/core-java-modules/core-java-concurrency-testing/src/main/resources/logback.xml b/core-java-modules/core-java-concurrency-testing/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterJCStressUnitTest.java b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterJCStressUnitTest.java new file mode 100644 index 0000000000..6c76505347 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterJCStressUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.concurrent; + +import static org.openjdk.jcstress.annotations.Expect.ACCEPTABLE; +import static org.openjdk.jcstress.annotations.Expect.ACCEPTABLE_INTERESTING; + +import org.openjdk.jcstress.annotations.Actor; +import org.openjdk.jcstress.annotations.Arbiter; +import org.openjdk.jcstress.annotations.JCStressTest; +import org.openjdk.jcstress.annotations.Outcome; +import org.openjdk.jcstress.annotations.State; +import org.openjdk.jcstress.infra.results.I_Result; + +@JCStressTest +@Outcome(id = "1", expect = ACCEPTABLE_INTERESTING, desc = "One update lost.") +@Outcome(id = "2", expect = ACCEPTABLE, desc = "Both updates.") +@State +public class MyCounterJCStressUnitTest { + + private MyCounter counter; + + @Actor + public void actor1() { + counter.increment(); + } + + @Actor + public void actor2() { + counter.increment(); + } + + @Arbiter + public void arbiter(I_Result r) { + r.r1 = counter.getCount(); + } + +} diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java new file mode 100644 index 0000000000..eb4e77cae9 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterMultithreadedTCUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.concurrent; + +import org.junit.Test; + +import edu.umd.cs.mtc.MultithreadedTestCase; +import edu.umd.cs.mtc.TestFramework; + +public class MyCounterMultithreadedTCUnitTest extends MultithreadedTestCase { + + private MyCounter counter; + + @Override + public void initialize() { + counter = new MyCounter(); + } + + public void thread1() throws InterruptedException { + counter.increment(); + } + + public void thread2() throws InterruptedException { + counter.increment(); + } + + @SuppressWarnings("deprecation") + @Override + public void finish() { + assertEquals(2, counter.getCount()); + } + + @Test + public void testCounter() throws Throwable { + TestFramework.runManyTimes(new MyCounterMultithreadedTCUnitTest(), 1000); + } +} diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java new file mode 100644 index 0000000000..4f3409b923 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterSimpleUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.concurrent; + +import static org.junit.Assert.assertEquals; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.junit.Test; + +public class MyCounterSimpleUnitTest { + + @Test + public void testCounter() { + MyCounter counter = new MyCounter(); + for (int i = 0; i < 500; i++) + counter.increment(); + assertEquals(500, counter.getCount()); + } + + // @Test + public void testCounterWithConcurrency() throws InterruptedException { + int numberOfThreads = 100; + ExecutorService service = Executors.newFixedThreadPool(10); + CountDownLatch latch = new CountDownLatch(numberOfThreads); + MyCounter counter = new MyCounter(); + for (int i = 0; i < numberOfThreads; i++) { + service.execute(() -> { + counter.increment(); + latch.countDown(); + }); + } + latch.await(); + assertEquals(numberOfThreads, counter.getCount()); + } + + // @Test + public void testSummationWithConcurrencyAndWait() throws InterruptedException { + int numberOfThreads = 2; + ExecutorService service = Executors.newFixedThreadPool(10); + CountDownLatch latch = new CountDownLatch(numberOfThreads); + MyCounter counter = new MyCounter(); + for (int i = 0; i < numberOfThreads; i++) { + service.submit(() -> { + try { + counter.incrementWithWait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + latch.countDown(); + }); + } + latch.await(); + assertEquals(numberOfThreads, counter.getCount()); + } + +} diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java new file mode 100644 index 0000000000..360c61b4f4 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterTempusFugitUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.concurrent; + +import static org.junit.Assert.assertEquals; + +import org.junit.AfterClass; +import org.junit.Rule; +import org.junit.Test; + +import com.google.code.tempusfugit.concurrency.ConcurrentRule; +import com.google.code.tempusfugit.concurrency.RepeatingRule; +import com.google.code.tempusfugit.concurrency.annotations.Concurrent; +import com.google.code.tempusfugit.concurrency.annotations.Repeating; + +public class MyCounterTempusFugitUnitTest { + + @Rule + public ConcurrentRule concurrently = new ConcurrentRule(); + @Rule + public RepeatingRule rule = new RepeatingRule(); + + private static MyCounter counter = new MyCounter(); + + @Test + @Concurrent(count = 2) + @Repeating(repetition = 10) + public void runsMultipleTimes() { + counter.increment(); + } + + @AfterClass + public static void annotatedTestRunsMultipleTimes() throws InterruptedException { + assertEquals(counter.getCount(), 20); + } + +} diff --git a/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java new file mode 100644 index 0000000000..29b08996cd --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/test/java/com/baeldung/concurrent/MyCounterThreadWeaverUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.concurrent; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.google.testing.threadtester.AnnotatedTestRunner; +import com.google.testing.threadtester.ThreadedAfter; +import com.google.testing.threadtester.ThreadedBefore; +import com.google.testing.threadtester.ThreadedMain; +import com.google.testing.threadtester.ThreadedSecondary; + +public class MyCounterThreadWeaverUnitTest { + + private MyCounter counter; + + @ThreadedBefore + public void before() { + counter = new MyCounter(); + } + + @ThreadedMain + public void mainThread() { + counter.increment(); + } + + @ThreadedSecondary + public void secondThread() { + counter.increment(); + } + + @ThreadedAfter + public void after() { + assertEquals(2, counter.getCount()); + } + + @Test + public void testCounter() { + new AnnotatedTestRunner().runTests(this.getClass(), MyCounter.class); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-testing/src/test/resources/.gitignore b/core-java-modules/core-java-concurrency-testing/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/core-java-modules/core-java-concurrency-testing/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file From 7187cb0dfbd3487877248742309519bed0f55d49 Mon Sep 17 00:00:00 2001 From: ramkumarvenkat Date: Thu, 2 Apr 2020 07:13:19 +0530 Subject: [PATCH 067/187] 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 068/187] 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 069/187] 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 902bb5308945cc37b148ee630832071209ce9361 Mon Sep 17 00:00:00 2001 From: Marius Catalin Munteanu Date: Wed, 11 Mar 2020 10:56:13 +0200 Subject: [PATCH 070/187] [BAEL-3011] Accesing Spring MVC Data from Thymeleaf - Code example for https://jira.baeldung.com/browse/BAEL-3012 --- .../thymeleaf/mvcdata/BeanConfig.java | 14 ++++ .../thymeleaf/mvcdata/EmailController.java | 63 ++++++++++++++++ .../mvcdata/repository/EmailData.java | 48 +++++++++++++ .../templates/mvcdata/email-bean-data.html | 14 ++++ .../mvcdata/email-model-attributes.html | 16 +++++ .../mvcdata/email-request-parameters.html | 20 ++++++ .../mvcdata/email-servlet-context.html | 14 ++++ .../mvcdata/email-session-attributes.html | 14 ++++ .../mvcdata/EmailControllerUnitTest.java | 72 +++++++++++++++++++ 9 files changed, 275 insertions(+) create mode 100644 spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java create mode 100644 spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java create mode 100644 spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java create mode 100644 spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-bean-data.html create mode 100644 spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-model-attributes.html create mode 100644 spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-request-parameters.html create mode 100644 spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-servlet-context.html create mode 100644 spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-session-attributes.html create mode 100644 spring-thymeleaf-2/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java new file mode 100644 index 0000000000..19f0101cf2 --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/BeanConfig.java @@ -0,0 +1,14 @@ +package com.baeldung.thymeleaf.mvcdata; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.thymeleaf.mvcdata.repository.EmailData; + +@Configuration +public class BeanConfig { + @Bean + public EmailData emailData() { + return new EmailData(); + } +} diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java new file mode 100644 index 0000000000..1bfe3f3428 --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/EmailController.java @@ -0,0 +1,63 @@ +package com.baeldung.thymeleaf.mvcdata; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpSession; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.RequestParam; + +import com.baeldung.thymeleaf.mvcdata.repository.EmailData; + +@Controller +public class EmailController { + private EmailData emailData = new EmailData(); + private ServletContext servletContext; + + public EmailController(ServletContext servletContext) { + this.servletContext = servletContext; + } + + @GetMapping(value = "/email/modelattributes") + public String emailModel(Model model) { + model.addAttribute("emaildata", emailData); + return "mvcdata/email-model-attributes"; + } + + @ModelAttribute("emailModelAttribute") + EmailData emailModelAttribute() { + return emailData; + } + + @GetMapping(value = "/email/requestparameters") + public String emailRequestParameters( + @RequestParam(value = "emailsubject") String emailSubject, + @RequestParam(value = "emailcontent") String emailContent, + @RequestParam(value = "emailaddress") String emailAddress1, + @RequestParam(value = "emailaddress") String emailAddress2, + @RequestParam(value = "emaillocale") String emailLocale) { + return "mvcdata/email-request-parameters"; + } + + @GetMapping("/email/sessionattributes") + public String emailSessionAttributes(HttpSession httpSession) { + httpSession.setAttribute("emaildata", emailData); + return "mvcdata/email-session-attributes"; + } + + @GetMapping("/email/servletcontext") + public String emailServletContext() { + servletContext.setAttribute("emailsubject", emailData.getEmailSubject()); + servletContext.setAttribute("emailcontent", emailData.getEmailBody()); + servletContext.setAttribute("emailaddress", emailData.getEmailAddress1()); + servletContext.setAttribute("emaillocale", emailData.getEmailLocale()); + return "mvcdata/email-servlet-context"; + } + + @GetMapping("/email/beandata") + public String emailBeanData() { + return "mvcdata/email-bean-data"; + } +} diff --git a/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java new file mode 100644 index 0000000000..9dc25bdaa7 --- /dev/null +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/mvcdata/repository/EmailData.java @@ -0,0 +1,48 @@ +package com.baeldung.thymeleaf.mvcdata.repository; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class EmailData implements Serializable { + private String emailSubject; + private String emailBody; + private String emailLocale; + private String emailAddress1; + private String emailAddress2; + + public EmailData() { + this.emailSubject = "You have received a new message"; + this.emailBody = "Good morning !"; + this.emailLocale = "en-US"; + this.emailAddress1 = "jhon.doe@example.com"; + this.emailAddress2 = "mark.jakob@example.com"; + } + + public String getEmailSubject() { + return this.emailSubject; + } + + public String getEmailBody() { + return this.emailBody; + } + + public String getEmailLocale() { + return this.emailLocale; + } + + public String getEmailAddress1() { + return this.emailAddress1; + } + + public String getEmailAddress2() { + return this.emailAddress2; + } + + public List getEmailAddresses() { + List emailAddresses = new ArrayList<>(); + emailAddresses.add(getEmailAddress1()); + emailAddresses.add(getEmailAddress2()); + return emailAddresses; + } +} diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-bean-data.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-bean-data.html new file mode 100644 index 0000000000..59073b51c6 --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-bean-data.html @@ -0,0 +1,14 @@ + + + +

Subject

+

Subject

+

Content

+

Body

+

Email address

+

Email address

+

Language

+

Language

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-model-attributes.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-model-attributes.html new file mode 100644 index 0000000000..caf136383a --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-model-attributes.html @@ -0,0 +1,16 @@ + + + +

Subject

+

Subject

+

Content

+

+

Email addresses

+

+ +

+

Language

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-request-parameters.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-request-parameters.html new file mode 100644 index 0000000000..8bcd3e1c62 --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-request-parameters.html @@ -0,0 +1,20 @@ + + + +

Subject

+

Subject

+

Content

+

+

Email addresses

+

+ +

+

Email address 1

+

+

Email address 2

+

+

Language

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-servlet-context.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-servlet-context.html new file mode 100644 index 0000000000..b07573047e --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-servlet-context.html @@ -0,0 +1,14 @@ + + + +

Subject

+

+

Content

+

+

Email address

+

+

Language

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-session-attributes.html b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-session-attributes.html new file mode 100644 index 0000000000..9227171fc6 --- /dev/null +++ b/spring-thymeleaf-2/src/main/resources/templates/mvcdata/email-session-attributes.html @@ -0,0 +1,14 @@ + + + +

Subject

+

+

Content

+

+

Email address

+

+

Language

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf-2/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java b/spring-thymeleaf-2/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java new file mode 100644 index 0000000000..5e1190e174 --- /dev/null +++ b/spring-thymeleaf-2/src/test/java/com/baeldung/thymeleaf/mvcdata/EmailControllerUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.thymeleaf.mvcdata; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; + +import com.baeldung.thymeleaf.mvcdata.repository.EmailData; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc(printOnlyOnFailure = false) +public class EmailControllerUnitTest { + + EmailData emailData = new EmailData(); + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenCallModelAttributes_thenReturnEmailData() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/email/modelattributes")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("You have received a new message"))); + } + + @Test + public void whenCallRequestParameters_thenReturnEmailData() throws Exception { + MultiValueMap params = new LinkedMultiValueMap<>(); + params.add("emailsubject", emailData.getEmailSubject()); + params.add("emailcontent", emailData.getEmailBody()); + params.add("emailaddress", emailData.getEmailAddress1()); + params.add("emailaddress", emailData.getEmailAddress2()); + params.add("emaillocale", emailData.getEmailLocale()); + mockMvc.perform(MockMvcRequestBuilders.get("/email/requestparameters") + .params(params)) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("en-US"))); + } + + @Test + public void whenCallSessionAttributes_thenReturnEmailData() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/email/sessionattributes")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("Good morning !"))); + } + + @Test + public void whenCallServletContext_thenReturnEmailData() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/email/servletcontext")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("jhon.doe@example.com"))); + } + + @Test + public void whenCallBeanData_thenReturnEmailData() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/email/beandata")) + .andExpect(status().isOk()) + .andExpect(content().string(containsString("jhon.doe@example.com"))); + } + +} From ffc854e2f0d92d531aae9d576c387bfb3ee078d5 Mon Sep 17 00:00:00 2001 From: Waldemar Date: Sat, 4 Apr 2020 11:38:24 +0200 Subject: [PATCH 071/187] 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 072/187] 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 073/187] 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 074/187] 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 075/187] 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 076/187] 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 (97%) 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 97% 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 ba65e099896cce714f3616329971d58c47dfa99d Mon Sep 17 00:00:00 2001 From: gindex Date: Sat, 28 Mar 2020 19:01:54 +0100 Subject: [PATCH 077/187] Add blocking and non-blocking mono examples Add article reference Fix url --- reactor-core/README.md | 1 + .../java/com/baeldung/mono/MonoUnitTest.java | 39 +++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java diff --git a/reactor-core/README.md b/reactor-core/README.md index e3cca35f86..f2dbd77981 100644 --- a/reactor-core/README.md +++ b/reactor-core/README.md @@ -7,3 +7,4 @@ This module contains articles about Reactor Core. - [Intro To Reactor Core](https://www.baeldung.com/reactor-core) - [Combining Publishers in Project Reactor](https://www.baeldung.com/reactor-combine-streams) - [Programmatically Creating Sequences with Project Reactor](https://www.baeldung.com/flux-sequences-reactor) +- [How To Get String From Mono In Reactive Java](http://baeldung.com/string-from-mono/) \ No newline at end of file diff --git a/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java b/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java new file mode 100644 index 0000000000..b493cd1159 --- /dev/null +++ b/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.mono; + +import org.junit.Test; +import reactor.core.publisher.Mono; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; + +public class MonoUnitTest { + @Test + public void whenMonoProducesString_thenBlockAndConsume() { + String expected = "hello world!"; + + String result1 = Mono.just(expected).block(); + assertEquals(expected, result1); + + String result2 = Mono.just(expected).block(Duration.of(1000, ChronoUnit.MILLIS)); + assertEquals(expected, result2); + + Optional result3 = Mono.empty().blockOptional(); + assertEquals(Optional.empty(), result3); + } + + @Test + public void whenMonoProducesString_thenConsumeNonBlocking() { + String expected = "hello world!"; + + Mono.just(expected) + .doOnNext(result -> assertEquals(expected, result)) + .subscribe(); + + Mono.just(expected) + .subscribe(result -> assertEquals(expected, result)); + + } +} From 641956f87db3f02e3291cc684e868b9d19b808ad Mon Sep 17 00:00:00 2001 From: mikr Date: Sat, 4 Apr 2020 21:16:51 +0200 Subject: [PATCH 078/187] 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 079/187] 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 080/187] 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 a3c69eba43cd3e32dfa6d78532736a7211e2f824 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Sun, 22 Mar 2020 18:36:02 +0100 Subject: [PATCH 081/187] [BAEL-2808] Added tests for physical naming strategies --- .../spring-data-jpa-4/create.sql | 2 + .../default-naming-strategy-ddl.sql | 1 + persistence-modules/spring-data-jpa-4/pom.xml | 5 ++ .../com/baeldung/namingstrategy/Person.java | 36 ++++++++ .../namingstrategy/PersonRepository.java | 6 ++ .../QuotedLowerCaseNamingStrategy.java | 12 +++ ...DataJpaTableAndColumnNamesApplication.java | 7 ++ .../UnquotedLowerCaseNamingStrategy.java | 12 +++ ...owerCaseNamingStrategyIntegrationTest.java | 78 +++++++++++++++++ ...PhysicalNamingStrategyIntegrationTest.java | 82 ++++++++++++++++++ ...owerCaseNamingStrategyIntegrationTest.java | 83 +++++++++++++++++++ ...oted-lower-case-naming-strategy.properties | 9 ++ ...spring-physical-naming-strategy.properties | 9 ++ ...oted-lower-case-naming-strategy.properties | 9 ++ .../upper-case-naming-strategy-ddl.sql | 1 + 15 files changed, 352 insertions(+) create mode 100644 persistence-modules/spring-data-jpa-4/create.sql create mode 100644 persistence-modules/spring-data-jpa-4/default-naming-strategy-ddl.sql create mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java create mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java create mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java create mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaTableAndColumnNamesApplication.java create mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties create mode 100644 persistence-modules/spring-data-jpa-4/upper-case-naming-strategy-ddl.sql diff --git a/persistence-modules/spring-data-jpa-4/create.sql b/persistence-modules/spring-data-jpa-4/create.sql new file mode 100644 index 0000000000..1bbe1640a7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/create.sql @@ -0,0 +1,2 @@ +create table PERSON (ID int8 not null, FIRST_NAME varchar(255), LAST_NAME varchar(255), primary key (ID)) +create table person (id int8 not null, first_name varchar(255), last_name varchar(255), primary key (id)) diff --git a/persistence-modules/spring-data-jpa-4/default-naming-strategy-ddl.sql b/persistence-modules/spring-data-jpa-4/default-naming-strategy-ddl.sql new file mode 100644 index 0000000000..34d5bd1867 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/default-naming-strategy-ddl.sql @@ -0,0 +1 @@ +create table person (id int8 not null, firstname varchar(255), last_name varchar(255), primary key (id)) diff --git a/persistence-modules/spring-data-jpa-4/pom.xml b/persistence-modules/spring-data-jpa-4/pom.xml index 8a476012c7..71fc21527f 100644 --- a/persistence-modules/spring-data-jpa-4/pom.xml +++ b/persistence-modules/spring-data-jpa-4/pom.xml @@ -33,6 +33,11 @@ mysql-connector-java + + org.postgresql + postgresql + + com.h2database h2 diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java new file mode 100644 index 0000000000..c3e7f50403 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java @@ -0,0 +1,36 @@ +package com.baeldung.namingstrategy; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Person { + @Id + private Long id; + + @Column(name = "FIRSTNAME") + private String firstName; + + private String lastName; + + public Person() {} + + public Person(Long id, String firstName, String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public Long id() { + return id; + } + + public String firstName() { + return firstName; + } + + public String lastName() { + return lastName; + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java new file mode 100644 index 0000000000..3c7c25bbcb --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.namingstrategy; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PersonRepository extends JpaRepository { +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java new file mode 100644 index 0000000000..16b01e50e3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class QuotedLowerCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toLowerCase(), true); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaTableAndColumnNamesApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaTableAndColumnNamesApplication.java new file mode 100644 index 0000000000..09aaf12b60 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaTableAndColumnNamesApplication.java @@ -0,0 +1,7 @@ +package com.baeldung.namingstrategy; + +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringDataJpaTableAndColumnNamesApplication { +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java new file mode 100644 index 0000000000..69e96aee27 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class UnquotedLowerCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toLowerCase(), false); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyIntegrationTest.java new file mode 100644 index 0000000000..ffa282da72 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyIntegrationTest.java @@ -0,0 +1,78 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-lower-case-naming-strategy.properties") +class QuotedLowerCaseNamingStrategyIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyIntegrationTest.java new file mode 100644 index 0000000000..8ad59fe2db --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyIntegrationTest.java @@ -0,0 +1,82 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("spring-physical-naming-strategy.properties") +class SpringPhysicalNamingStrategyIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndDefaultNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndDefaultNamingStrategyAndH2Database_whenQueryPersonQuotedUpperCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndDefaultNamingStrategyAndH2Database_whenQueryPersonQuotedLowerCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyIntegrationTest.java new file mode 100644 index 0000000000..2d84a17526 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyIntegrationTest.java @@ -0,0 +1,83 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-lower-case-naming-strategy.properties") +class UnquotedLowerCaseNamingStrategyIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties new file mode 100644 index 0000000000..dce43e2da5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:custom-lower-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties new file mode 100644 index 0000000000..a8ba1a3e4d --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:spring-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create +spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=default-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties new file mode 100644 index 0000000000..63f400db0b --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:custom-lower-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/upper-case-naming-strategy-ddl.sql b/persistence-modules/spring-data-jpa-4/upper-case-naming-strategy-ddl.sql new file mode 100644 index 0000000000..b26697ac66 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/upper-case-naming-strategy-ddl.sql @@ -0,0 +1 @@ +create table "PERSON" ("ID" int8 not null, "FIRSTNAME" varchar(255), "LAST_NAME" varchar(255), primary key ("ID")) From aebba04be7812a3ba020cfddfbc38da245dca10b Mon Sep 17 00:00:00 2001 From: dupirefr Date: Tue, 24 Mar 2020 08:09:31 +0100 Subject: [PATCH 082/187] [BAEL-2808] Added a few tests to illustrate my problem --- .../QuotedUpperCaseNamingStrategy.java | 12 +++ .../UnquotedUpperCaseNamingStrategy.java | 12 +++ ...rCaseNamingStrategyH2IntegrationTest.java} | 5 +- ...NamingStrategyPostgresIntegrationTest.java | 85 +++++++++++++++++++ ...erCaseNamingStrategyH2IntegrationTest.java | 85 +++++++++++++++++++ ...NamingStrategyPostgresIntegrationTest.java | 81 ++++++++++++++++++ ...sicalNamingStrategyH2IntegrationTest.java} | 11 ++- ...NamingStrategyPostgresIntegrationTest.java | 85 +++++++++++++++++++ ...rCaseNamingStrategyH2IntegrationTest.java} | 11 ++- ...NamingStrategyPostgresIntegrationTest.java | 85 +++++++++++++++++++ ...erCaseNamingStrategyH2IntegrationTest.java | 85 +++++++++++++++++++ ...NamingStrategyPostgresIntegrationTest.java | 85 +++++++++++++++++++ ...ase-naming-strategy-on-postgres.properties | 9 ++ ...oted-lower-case-naming-strategy.properties | 4 +- ...ase-naming-strategy-on-postgres.properties | 9 ++ ...oted-upper-case-naming-strategy.properties | 9 ++ ...cal-naming-strategy-on-postgres.properties | 9 ++ ...spring-physical-naming-strategy.properties | 2 +- ...ase-naming-strategy-on-postgres.properties | 9 ++ ...oted-lower-case-naming-strategy.properties | 4 +- ...ase-naming-strategy-on-postgres.properties | 9 ++ ...oted-upper-case-naming-strategy.properties | 9 ++ 22 files changed, 701 insertions(+), 14 deletions(-) create mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java create mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java rename persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/{QuotedLowerCaseNamingStrategyIntegrationTest.java => QuotedLowerCaseNamingStrategyH2IntegrationTest.java} (95%) create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresIntegrationTest.java rename persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/{SpringPhysicalNamingStrategyIntegrationTest.java => SpringPhysicalNamingStrategyH2IntegrationTest.java} (85%) create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresIntegrationTest.java rename persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/{UnquotedLowerCaseNamingStrategyIntegrationTest.java => UnquotedLowerCaseNamingStrategyH2IntegrationTest.java} (91%) create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties create mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java new file mode 100644 index 0000000000..3cb62aa5a2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class QuotedUpperCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toUpperCase(), true); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java new file mode 100644 index 0000000000..cb87af10f4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class UnquotedUpperCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toUpperCase(), false); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java similarity index 95% rename from persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyIntegrationTest.java rename to persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java index ffa282da72..71a4dbda3f 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("quoted-lower-case-naming-strategy.properties") -class QuotedLowerCaseNamingStrategyIntegrationTest { +class QuotedLowerCaseNamingStrategyH2IntegrationTest { @PersistenceContext private EntityManager entityManager; @@ -45,6 +45,7 @@ class QuotedLowerCaseNamingStrategyIntegrationTest { void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { Query query = entityManager.createNativeQuery("select * from " + tableName); + // Unexpected result assertThrows(SQLGrammarException.class, query::getResultStream); } @@ -52,6 +53,7 @@ class QuotedLowerCaseNamingStrategyIntegrationTest { void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + // Expected result assertThrows(SQLGrammarException.class, query::getResultStream); } @@ -59,6 +61,7 @@ class QuotedLowerCaseNamingStrategyIntegrationTest { void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { Query query = entityManager.createNativeQuery("select * from \"person\""); + // Expected result List result = (List) query.getResultStream() .map(this::fromDatabase) .collect(Collectors.toList()); diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresIntegrationTest.java new file mode 100644 index 0000000000..79c47e86e0 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresIntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-lower-case-naming-strategy-on-postgres.properties") +class QuotedLowerCaseNamingStrategyPostgresIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..f819327a5c --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-upper-case-naming-strategy.properties") +class QuotedUpperCaseNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresIntegrationTest.java new file mode 100644 index 0000000000..20250a7ecb --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresIntegrationTest.java @@ -0,0 +1,81 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-upper-case-naming-strategy-on-postgres.properties") +class QuotedUpperCaseNamingStrategyPostgresIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java similarity index 85% rename from persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyIntegrationTest.java rename to persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java index 8ad59fe2db..1850fea173 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("spring-physical-naming-strategy.properties") -class SpringPhysicalNamingStrategyIntegrationTest { +class SpringPhysicalNamingStrategyH2IntegrationTest { @PersistenceContext private EntityManager entityManager; @@ -42,9 +42,10 @@ class SpringPhysicalNamingStrategyIntegrationTest { @ParameterizedTest @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndDefaultNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + void givenPeopleAndSpringNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { Query query = entityManager.createNativeQuery("select * from " + tableName); + // Expected result List result = (List) query.getResultStream() .map(this::fromDatabase) .collect(Collectors.toList()); @@ -53,9 +54,10 @@ class SpringPhysicalNamingStrategyIntegrationTest { } @Test - void givenPeopleAndDefaultNamingStrategyAndH2Database_whenQueryPersonQuotedUpperCase_thenResult() { + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + // Unexpected result List result = (List) query.getResultStream() .map(this::fromDatabase) .collect(Collectors.toList()); @@ -64,9 +66,10 @@ class SpringPhysicalNamingStrategyIntegrationTest { } @Test - void givenPeopleAndDefaultNamingStrategyAndH2Database_whenQueryPersonQuotedLowerCase_thenException() { + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { Query query = entityManager.createNativeQuery("select * from \"person\""); + // Unexpected result assertThrows(SQLGrammarException.class, query::getResultStream); } diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresIntegrationTest.java new file mode 100644 index 0000000000..97f2b601b0 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresIntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("spring-physical-naming-strategy-on-postgres.properties") +class SpringPhysicalNamingStrategyPostgresIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndSpringNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java similarity index 91% rename from persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyIntegrationTest.java rename to persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java index 2d84a17526..6311c42e93 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java @@ -24,7 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("unquoted-lower-case-naming-strategy.properties") -class UnquotedLowerCaseNamingStrategyIntegrationTest { +class UnquotedLowerCaseNamingStrategyH2IntegrationTest { @PersistenceContext private EntityManager entityManager; @@ -43,9 +43,10 @@ class UnquotedLowerCaseNamingStrategyIntegrationTest { @ParameterizedTest @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { Query query = entityManager.createNativeQuery("select * from " + tableName); + // Expected result List result = (List) query.getResultStream() .map(this::fromDatabase) .collect(Collectors.toList()); @@ -54,9 +55,10 @@ class UnquotedLowerCaseNamingStrategyIntegrationTest { } @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + // Unexpected result List result = (List) query.getResultStream() .map(this::fromDatabase) .collect(Collectors.toList()); @@ -65,9 +67,10 @@ class UnquotedLowerCaseNamingStrategyIntegrationTest { } @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { Query query = entityManager.createNativeQuery("select * from \"person\""); + // Unexpected result assertThrows(SQLGrammarException.class, query::getResultStream); } diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresIntegrationTest.java new file mode 100644 index 0000000000..4e1d69ccdb --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresIntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-lower-case-naming-strategy-on-postgres.properties") +class UnquotedLowerCaseNamingStrategyPostgresIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..7af8001854 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-upper-case-naming-strategy.properties") +class UnquotedUpperCaseNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresIntegrationTest.java new file mode 100644 index 0000000000..0fdb05b0ee --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresIntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-upper-case-naming-strategy-on-postgres.properties") +class UnquotedUpperCaseNamingStrategyPostgresIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Unexpected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..04b29de41f --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/quoted-lower-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties index dce43e2da5..6643c12c8a 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties @@ -1,8 +1,8 @@ -spring.datasource.url=jdbc:h2:mem:custom-lower-case-strategy +spring.datasource.url=jdbc:h2:mem:quoted-lower-case-strategy spring.datasource.username=sa spring.datasource.password= -spring.jpa.hibernate.ddl-auto=create +spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedLowerCaseNamingStrategy #spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata #spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..36898d5b4f --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/quoted-upper-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties new file mode 100644 index 0000000000..6d56d58749 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:quoted-upper-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..706b12b1b6 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/spring-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=default-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties index a8ba1a3e4d..c9a0c6f24c 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties @@ -2,7 +2,7 @@ spring.datasource.url=jdbc:h2:mem:spring-strategy spring.datasource.username=sa spring.datasource.password= -spring.jpa.hibernate.ddl-auto=create +spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy #spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata #spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..b22472bd8f --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/unquoted-lower-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties index 63f400db0b..8083515b4b 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties @@ -1,8 +1,8 @@ -spring.datasource.url=jdbc:h2:mem:custom-lower-case-strategy +spring.datasource.url=jdbc:h2:mem:unquoted-lower-case-strategy spring.datasource.username=sa spring.datasource.password= -spring.jpa.hibernate.ddl-auto=create +spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedLowerCaseNamingStrategy #spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata #spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..da03a0d7b5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/unquoted-upper-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties new file mode 100644 index 0000000000..d1b63e008c --- /dev/null +++ b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:unquoted-upper-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file From daab2b383ff6059a9a64af89300e3adc2ae1d743 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Wed, 1 Apr 2020 23:10:07 +0200 Subject: [PATCH 083/187] [BAEL-2808] Last fix --- .../spring-data-jpa-4/default-naming-strategy-ddl.sql | 1 - .../src/main/java/com/baeldung/namingstrategy/Person.java | 1 - .../spring-data-jpa-4/upper-case-naming-strategy-ddl.sql | 1 - 3 files changed, 3 deletions(-) delete mode 100644 persistence-modules/spring-data-jpa-4/default-naming-strategy-ddl.sql delete mode 100644 persistence-modules/spring-data-jpa-4/upper-case-naming-strategy-ddl.sql diff --git a/persistence-modules/spring-data-jpa-4/default-naming-strategy-ddl.sql b/persistence-modules/spring-data-jpa-4/default-naming-strategy-ddl.sql deleted file mode 100644 index 34d5bd1867..0000000000 --- a/persistence-modules/spring-data-jpa-4/default-naming-strategy-ddl.sql +++ /dev/null @@ -1 +0,0 @@ -create table person (id int8 not null, firstname varchar(255), last_name varchar(255), primary key (id)) diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java index c3e7f50403..cfb6e67c2c 100644 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java @@ -9,7 +9,6 @@ public class Person { @Id private Long id; - @Column(name = "FIRSTNAME") private String firstName; private String lastName; diff --git a/persistence-modules/spring-data-jpa-4/upper-case-naming-strategy-ddl.sql b/persistence-modules/spring-data-jpa-4/upper-case-naming-strategy-ddl.sql deleted file mode 100644 index b26697ac66..0000000000 --- a/persistence-modules/spring-data-jpa-4/upper-case-naming-strategy-ddl.sql +++ /dev/null @@ -1 +0,0 @@ -create table "PERSON" ("ID" int8 not null, "FIRSTNAME" varchar(255), "LAST_NAME" varchar(255), primary key ("ID")) From c73b8dbf724d4fe5bc2a3f4b5ffbb424b4747c22 Mon Sep 17 00:00:00 2001 From: dupirefr Date: Sun, 5 Apr 2020 16:16:27 +0200 Subject: [PATCH 084/187] [BAEL-2808] Migrated PostgreSQL tests to LiveTest --- ...ation.java => SpringDataJpaNamingConventionApplication.java} | 2 +- ....java => QuotedLowerCaseNamingStrategyPostgresLiveTest.java} | 2 +- ....java => QuotedUpperCaseNamingStrategyPostgresLiveTest.java} | 2 +- ...t.java => SpringPhysicalNamingStrategyPostgresLiveTest.java} | 2 +- ...ava => UnquotedLowerCaseNamingStrategyPostgresLiveTest.java} | 2 +- ...ava => UnquotedUpperCaseNamingStrategyPostgresLiveTest.java} | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) rename persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/{SpringDataJpaTableAndColumnNamesApplication.java => SpringDataJpaNamingConventionApplication.java} (69%) rename persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/{QuotedLowerCaseNamingStrategyPostgresIntegrationTest.java => QuotedLowerCaseNamingStrategyPostgresLiveTest.java} (97%) rename persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/{QuotedUpperCaseNamingStrategyPostgresIntegrationTest.java => QuotedUpperCaseNamingStrategyPostgresLiveTest.java} (97%) rename persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/{SpringPhysicalNamingStrategyPostgresIntegrationTest.java => SpringPhysicalNamingStrategyPostgresLiveTest.java} (97%) rename persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/{UnquotedLowerCaseNamingStrategyPostgresIntegrationTest.java => UnquotedLowerCaseNamingStrategyPostgresLiveTest.java} (97%) rename persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/{UnquotedUpperCaseNamingStrategyPostgresIntegrationTest.java => UnquotedUpperCaseNamingStrategyPostgresLiveTest.java} (97%) diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaTableAndColumnNamesApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java similarity index 69% rename from persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaTableAndColumnNamesApplication.java rename to persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java index 09aaf12b60..f223015db8 100644 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaTableAndColumnNamesApplication.java +++ b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java @@ -3,5 +3,5 @@ package com.baeldung.namingstrategy; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication -public class SpringDataJpaTableAndColumnNamesApplication { +public class SpringDataJpaNamingConventionApplication { } diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java similarity index 97% rename from persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresIntegrationTest.java rename to persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java index 79c47e86e0..6b1c984600 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("quoted-lower-case-naming-strategy-on-postgres.properties") -class QuotedLowerCaseNamingStrategyPostgresIntegrationTest { +class QuotedLowerCaseNamingStrategyPostgresLiveTest { @PersistenceContext private EntityManager entityManager; diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java similarity index 97% rename from persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresIntegrationTest.java rename to persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java index 20250a7ecb..bd23b81b4b 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("quoted-upper-case-naming-strategy-on-postgres.properties") -class QuotedUpperCaseNamingStrategyPostgresIntegrationTest { +class QuotedUpperCaseNamingStrategyPostgresLiveTest { @PersistenceContext private EntityManager entityManager; diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java similarity index 97% rename from persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresIntegrationTest.java rename to persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java index 97f2b601b0..e26ebb148d 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("spring-physical-naming-strategy-on-postgres.properties") -class SpringPhysicalNamingStrategyPostgresIntegrationTest { +class SpringPhysicalNamingStrategyPostgresLiveTest { @PersistenceContext private EntityManager entityManager; diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java similarity index 97% rename from persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresIntegrationTest.java rename to persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java index 4e1d69ccdb..033a213cf5 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("unquoted-lower-case-naming-strategy-on-postgres.properties") -class UnquotedLowerCaseNamingStrategyPostgresIntegrationTest { +class UnquotedLowerCaseNamingStrategyPostgresLiveTest { @PersistenceContext private EntityManager entityManager; diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java similarity index 97% rename from persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresIntegrationTest.java rename to persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java index 0fdb05b0ee..0151e7ece4 100644 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java @@ -23,7 +23,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("unquoted-upper-case-naming-strategy-on-postgres.properties") -class UnquotedUpperCaseNamingStrategyPostgresIntegrationTest { +class UnquotedUpperCaseNamingStrategyPostgresLiveTest { @PersistenceContext private EntityManager entityManager; From b30ee628059d55773e18420d9ed8df9f079678eb Mon Sep 17 00:00:00 2001 From: Belma Jakupovic Date: Mon, 6 Apr 2020 20:22:28 +0200 Subject: [PATCH 085/187] 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 086/187] 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 087/187] 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 088/187] 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 089/187] 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 222a1363756975e00c7580f40db6ab3190457fcd Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 15:02:49 +0800 Subject: [PATCH 090/187] Update README.md --- cas/cas-server/README.md | 145 --------------------------------------- 1 file changed, 145 deletions(-) diff --git a/cas/cas-server/README.md b/cas/cas-server/README.md index b224738732..8b13789179 100644 --- a/cas/cas-server/README.md +++ b/cas/cas-server/README.md @@ -1,146 +1 @@ -CAS Overlay Template [![Build Status](https://travis-ci.org/apereo/cas-overlay-template.svg?branch=master)](https://travis-ci.org/apereo/cas-overlay-template) -======================= -Generic CAS WAR overlay to exercise the latest versions of CAS. This overlay could be freely used as a starting template for local CAS war overlays. - -# Versions - -- CAS `6.1.x` -- JDK `11` - -# Overview - -To build the project, use: - -```bash -# Use --refresh-dependencies to force-update SNAPSHOT versions -./gradlew[.bat] clean build -``` - -To see what commands are available to the build script, run: - -```bash -./gradlew[.bat] tasks -``` - -To launch into the CAS command-line shell: - -```bash -./gradlew[.bat] downloadShell runShell -``` - -To fetch and overlay a CAS resource or view, use: - -```bash -./gradlew[.bat] getResource -PresourceName=[resource-name] -``` - -To list all available CAS views and templates: - -```bash -./gradlew[.bat] listTemplateViews -``` - -To unzip and explode the CAS web application file and the internal resources jar: - -```bash -./gradlew[.bat] explodeWar -``` - -# Configuration - -- The `etc` directory contains the configuration files and directories that need to be copied to `/etc/cas/config`. - -```bash -./gradlew[.bat] copyCasConfiguration -``` - -- The specifics of the build are controlled using the `gradle.properties` file. - -## Adding Modules - -CAS modules may be specified under the `dependencies` block of the [Gradle build script](build.gradle): - -```gradle -dependencies { - compile "org.apereo.cas:cas-server-some-module:${project.casVersion}" - ... -} -``` - -To collect the list of all project modules and dependencies: - -```bash -./gradlew[.bat] allDependencies -``` - -### Clear Gradle Cache - -If you need to, on Linux/Unix systems, you can delete all the existing artifacts (artifacts and metadata) Gradle has downloaded using: - -```bash -# Only do this when absolutely necessary -rm -rf $HOME/.gradle/caches/ -``` - -Same strategy applies to Windows too, provided you switch `$HOME` to its equivalent in the above command. - -# Deployment - -- Create a keystore file `thekeystore` under `/etc/cas`. Use the password `changeit` for both the keystore and the key/certificate entries. This can either be done using the JDK's `keytool` utility or via the following command: - -```bash -./gradlew[.bat] createKeystore -``` - -- Ensure the keystore is loaded up with keys and certificates of the server. - -On a successful deployment via the following methods, CAS will be available at: - -* `https://cas.server.name:8443/cas` - -## Executable WAR - -Run the CAS web application as an executable WAR: - -```bash -./gradlew[.bat] run -``` - -Debug the CAS web application as an executable WAR: - -```bash -./gradlew[.bat] debug -``` - -Run the CAS web application as a *standalone* executable WAR: - -```bash -./gradlew[.bat] clean executable -``` - -## External - -Deploy the binary web application file `cas.war` after a successful build to a servlet container of choice. - -## Docker - -The following strategies outline how to build and deploy CAS Docker images. - -### Jib - -The overlay embraces the [Jib Gradle Plugin](https://github.com/GoogleContainerTools/jib) to provide easy-to-use out-of-the-box tooling for building CAS docker images. Jib is an open-source Java containerizer from Google that lets Java developers build containers using the tools they know. It is a container image builder that handles all the steps of packaging your application into a container image. It does not require you to write a Dockerfile or have Docker installed, and it is directly integrated into the overlay. - -```bash -./gradlew build jibDockerBuild -``` - -### Dockerfile - -You can also use the native Docker tooling and the provided `Dockerfile` to build and run CAS. - -```bash -chmod +x *.sh -./docker-build.sh -./docker-run.sh -``` From 911c746f23022890bcc39b2a1e936f7109dbae11 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 15:02:57 +0800 Subject: [PATCH 091/187] Delete README.md --- cas/cas-server/README.md | 1 - 1 file changed, 1 deletion(-) delete mode 100644 cas/cas-server/README.md diff --git a/cas/cas-server/README.md b/cas/cas-server/README.md deleted file mode 100644 index 8b13789179..0000000000 --- a/cas/cas-server/README.md +++ /dev/null @@ -1 +0,0 @@ - From c76c811b1cb72b71c8c127c9e3da41a731e4adff Mon Sep 17 00:00:00 2001 From: patkorek Date: Tue, 7 Apr 2020 10:23:15 +0200 Subject: [PATCH 092/187] BAEL-2660 few examples to convert String to Int --- .../strings/ConvertStringToInt.groovy | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy diff --git a/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy b/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy new file mode 100644 index 0000000000..40c53965a5 --- /dev/null +++ b/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy @@ -0,0 +1,92 @@ +package com.baeldung.strings + +import org.junit.Test + +import java.text.DecimalFormat + +import static org.junit.Assert.assertEquals +import static org.junit.Assert.assertNull + +class ConvertStringToInt { + + @Test + void givenString_thenConvertToIntegerUsingAsInteger() { + def stringNum = "123" + def invalidString = "123a" + Integer expectedInteger = 123 + Integer integerNum = stringNum as Integer + def intNum = invalidString?.isInteger() ? invalidString as Integer : null + + assertNull(null, intNum) + assertEquals(integerNum, expectedInteger) + } + + @Test + void givenString_thenConvertToIntUsingAsInt() { + def stringNum = "123" + int expectedInt = 123 + int intNum = stringNum as int + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_thenConvertToIntegerUsingToInteger() { + def stringNum = "123" + int expectedInt = 123 + int intNum = stringNum.toInteger() + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_thenConvertToIntegerUsingParseInt() { + def stringNum = "123" + int expectedInt = 123 + int intNum = Integer.parseInt(stringNum) + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_thenConvertToIntegerUsingValueOf() { + def stringNum = "123" + int expectedInt = 123 + int intNum = Integer.valueOf(stringNum) + + assertEquals(intNum, expectedInt) + } + + @Test + void givenString_thenConvertToIntegerUsingIntValue() { + def stringNum = "123" + int expectedInt = 123 + int intNum = new Integer(stringNum).intValue() + int secondIntNum = new Integer(stringNum) + + assertEquals(intNum, expectedInt) + assertEquals(secondIntNum, expectedInt) + } + + @Test + void givenString_thenConvertToIntegerUsingDecimalFormat() { + def stringNum = "123" + int expectedInt = 123 + DecimalFormat decimalFormat = new DecimalFormat("#") + int intNum = decimalFormat.parse(stringNum).intValue() + + assertEquals(intNum, expectedInt) + } + + @Test(expected = NumberFormatException.class) + void givenInvalidString_whenUsingAs_thenThrowNumberFormatException() { + def invalidString = "123a" + invalidString as Integer + } + + @Test(expected = NullPointerException.class) + void givenNullString_whenUsingToInteger_thenThrowNullPointerException() { + def invalidString = null + invalidString.toInteger() + } +} From 5e90298049ebf59769a0397e2cfebf14eabd3a8b Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 16:24:27 +0800 Subject: [PATCH 093/187] Update README.md --- libraries-3/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries-3/README.md b/libraries-3/README.md index f3c3375098..62bd3b9f66 100644 --- a/libraries-3/README.md +++ b/libraries-3/README.md @@ -15,4 +15,4 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [Introduction to the jcabi-aspects AOP Annotations Library](https://www.baeldung.com/java-jcabi-aspects) - [Introduction to Takes](https://www.baeldung.com/java-takes) - [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway) - +- [Introduction to Alibaba Arthas](https://www.baeldung.com/java-alibaba-arthas-intro) From 2ecd4cb204e6856476f5cf2b24877a591612248a Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 16:27:04 +0800 Subject: [PATCH 094/187] Update README.md --- persistence-modules/spring-boot-persistence-h2/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/persistence-modules/spring-boot-persistence-h2/README.md b/persistence-modules/spring-boot-persistence-h2/README.md index a0f9c67a33..d11ec1f409 100644 --- a/persistence-modules/spring-boot-persistence-h2/README.md +++ b/persistence-modules/spring-boot-persistence-h2/README.md @@ -1,4 +1,5 @@ ### Relevant Articles: - [Access the Same In-Memory H2 Database in Multiple Spring Boot Applications](https://www.baeldung.com/spring-boot-access-h2-database-multiple-apps) - [Spring Boot With H2 Database](https://www.baeldung.com/spring-boot-h2-database) -- [Hibernate @NotNull vs @Column(nullable = false)](https://www.baeldung.com/hibernate-notnull-vs-nullable) \ No newline at end of file +- [Hibernate @NotNull vs @Column(nullable = false)](https://www.baeldung.com/hibernate-notnull-vs-nullable) +- [Quick Guide to Hibernate enable_lazy_load_no_trans Property](https://www.baeldung.com/hibernate-lazy-loading-workaround) From fb594d2b2734aa68bdffaf636729f52461b9439c Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 16:30:42 +0800 Subject: [PATCH 095/187] Update README.md --- core-java-modules/core-java-io-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-io-2/README.md b/core-java-modules/core-java-io-2/README.md index 62461be0ff..84cabc5992 100644 --- a/core-java-modules/core-java-io-2/README.md +++ b/core-java-modules/core-java-io-2/README.md @@ -12,4 +12,5 @@ This module contains articles about core Java input and output (IO) - [Java – Append Data to a File](https://www.baeldung.com/java-append-to-file) - [How to Copy a File with Java](https://www.baeldung.com/java-copy-file) - [Create a Directory in Java](https://www.baeldung.com/java-create-directory) +- [Java IO vs NIO](https://www.baeldung.com/java-io-vs-nio) - [[<-- Prev]](/core-java-modules/core-java-io) From a59aa144001d35a75c7014eb03f7e0457e67161f Mon Sep 17 00:00:00 2001 From: patkorek Date: Tue, 7 Apr 2020 10:34:38 +0200 Subject: [PATCH 096/187] Renamed methods --- .../com/baeldung/strings/ConvertStringToInt.groovy | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy b/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy index 40c53965a5..3b179ee193 100644 --- a/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy @@ -10,7 +10,7 @@ import static org.junit.Assert.assertNull class ConvertStringToInt { @Test - void givenString_thenConvertToIntegerUsingAsInteger() { + void givenString_whenUsingAsInteger_thenConvertToInteger() { def stringNum = "123" def invalidString = "123a" Integer expectedInteger = 123 @@ -22,7 +22,7 @@ class ConvertStringToInt { } @Test - void givenString_thenConvertToIntUsingAsInt() { + void givenString_whenUsingAsInt_thenConvertToInt() { def stringNum = "123" int expectedInt = 123 int intNum = stringNum as int @@ -31,7 +31,7 @@ class ConvertStringToInt { } @Test - void givenString_thenConvertToIntegerUsingToInteger() { + void givenString_whenUsingToInteger_thenConvertToInteger() { def stringNum = "123" int expectedInt = 123 int intNum = stringNum.toInteger() @@ -40,7 +40,7 @@ class ConvertStringToInt { } @Test - void givenString_thenConvertToIntegerUsingParseInt() { + void givenString_whenUsingParseInt_thenConvertToInteger() { def stringNum = "123" int expectedInt = 123 int intNum = Integer.parseInt(stringNum) @@ -49,7 +49,7 @@ class ConvertStringToInt { } @Test - void givenString_thenConvertToIntegerUsingValueOf() { + void givenString_whenUsingValueOf_thenConvertToInteger() { def stringNum = "123" int expectedInt = 123 int intNum = Integer.valueOf(stringNum) @@ -58,7 +58,7 @@ class ConvertStringToInt { } @Test - void givenString_thenConvertToIntegerUsingIntValue() { + void givenString_whenUsingIntValue_thenConvertToInteger() { def stringNum = "123" int expectedInt = 123 int intNum = new Integer(stringNum).intValue() @@ -69,7 +69,7 @@ class ConvertStringToInt { } @Test - void givenString_thenConvertToIntegerUsingDecimalFormat() { + void givenString_whenUsingDecimalFormat_thenConvertToInteger() { def stringNum = "123" int expectedInt = 123 DecimalFormat decimalFormat = new DecimalFormat("#") From c9847d5036664bd35d88332b33836e85e293249d Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 16:37:03 +0800 Subject: [PATCH 097/187] Create README.md --- linux-bash/functions/src/main/bash/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 linux-bash/functions/src/main/bash/README.md diff --git a/linux-bash/functions/src/main/bash/README.md b/linux-bash/functions/src/main/bash/README.md new file mode 100644 index 0000000000..5fb6958b9d --- /dev/null +++ b/linux-bash/functions/src/main/bash/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Bash Functions in Linux](https://www.baeldung.com/linux/bash-functions) From 23a7314302d4f9bb1f7949d1b009f965cb43d340 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 16:39:13 +0800 Subject: [PATCH 098/187] Create README.md --- lombok/src/main/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 lombok/src/main/README.md diff --git a/lombok/src/main/README.md b/lombok/src/main/README.md new file mode 100644 index 0000000000..4092d8ce99 --- /dev/null +++ b/lombok/src/main/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Guide to the Linux wc Command](https://www.baeldung.com/linux/wc-command) From 4d9ae47da774264f984f77203e20a9908bd42d40 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 16:44:15 +0800 Subject: [PATCH 099/187] Create README.md --- linux-bash/read/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 linux-bash/read/README.md diff --git a/linux-bash/read/README.md b/linux-bash/read/README.md new file mode 100644 index 0000000000..56c1dd5b24 --- /dev/null +++ b/linux-bash/read/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Guide to the Linux read Command](https://www.baeldung.com/linux/read-command) From 850b02f07e04b3adebc27384ba8aad13c05945c6 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 16:48:21 +0800 Subject: [PATCH 100/187] Create README.md --- linux-bash/command-line-arguments/src/main/bash/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 linux-bash/command-line-arguments/src/main/bash/README.md diff --git a/linux-bash/command-line-arguments/src/main/bash/README.md b/linux-bash/command-line-arguments/src/main/bash/README.md new file mode 100644 index 0000000000..27d89fff99 --- /dev/null +++ b/linux-bash/command-line-arguments/src/main/bash/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [How to Use Command Line Arguments in a Bash Script](https://www.baeldung.com/linux/use-command-line-arguments-in-bash-script) From 1f6163f45cb9a0bf94cca287e5bfc0e4a765b779 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 16:49:44 +0800 Subject: [PATCH 101/187] Update README.md --- linux-bash/text/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/linux-bash/text/README.md b/linux-bash/text/README.md index de99c1962a..20df2a33ec 100644 --- a/linux-bash/text/README.md +++ b/linux-bash/text/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Linux Commands – Remove All Text After X](https://www.baeldung.com/linux/tr-manipulate-strings) +- [Linux Commands for Appending Multiple Lines to a File](https://www.baeldung.com/linux/appending-multiple-lines-to-file2) From 83cf886628977eb17779e46eb2edcd3a13c367e4 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 16:56:28 +0800 Subject: [PATCH 102/187] Create README.md --- .../core-java-concurrency-collections-2/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-java-modules/core-java-concurrency-collections-2/README.md diff --git a/core-java-modules/core-java-concurrency-collections-2/README.md b/core-java-modules/core-java-concurrency-collections-2/README.md new file mode 100644 index 0000000000..91da6c623c --- /dev/null +++ b/core-java-modules/core-java-concurrency-collections-2/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to Lock Striping](https://www.baeldung.com/java-lock-stripping) From 073f9c9067e96c56fee2af7580174b56c9c95a8b Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 17:09:25 +0800 Subject: [PATCH 103/187] Create README.md --- core-scala/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-scala/README.md diff --git a/core-scala/README.md b/core-scala/README.md new file mode 100644 index 0000000000..72b583c22b --- /dev/null +++ b/core-scala/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Pattern Matching in Scala](https://www.baeldung.com/scala/pattern-matching) From 40825b6f1fd4896b868d08b95e86aed98109d3a7 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Tue, 7 Apr 2020 14:49:42 +0530 Subject: [PATCH 104/187] JAVA-1188: Moved modules to core-java-modules --- java-collections-maps-2/README.md | 16 - java-collections-maps-2/pom.xml | 79 ---- .../main/java/com/baeldung/map/Product.java | 133 ------- .../com/baeldung/map/convert/MapToString.java | 34 -- .../com/baeldung/map/convert/StringToMap.java | 21 -- .../baeldung/map/copyhashmap/CopyHashMap.java | 55 --- .../map/initialize/MapInitializer.java | 80 ----- .../baeldung/map/iteration/MapIteration.java | 74 ---- .../java/com/baeldung/map/mapmax/MapMax.java | 92 ----- .../com/baeldung/map/mergemaps/Employee.java | 60 ---- .../com/baeldung/map/mergemaps/MergeMaps.java | 105 ------ .../map/primitives/PrimitiveMaps.java | 69 ---- .../com/baeldung/map/sort/SortHashMap.java | 104 ------ .../com/baeldung/map/ProductUnitTest.java | 174 --------- .../map/convert/MapToStringUnitTest.java | 48 --- .../map/convert/StringToMapUnitTest.java | 23 -- .../map/copyhashmap/CopyHashMapUnitTest.java | 76 ---- .../baeldung/map/copyhashmap/Employee.java | 28 -- .../initialize/MapInitializerUnitTest.java | 27 -- .../baeldung/map/mapmax/MapMaxUnitTest.java | 58 --- .../map/weakhashmap/WeakHashMapUnitTest.java | 72 ---- java-collections-maps-3/README.md | 8 - java-collections-maps-3/pom.xml | 26 -- .../compare/HashMapComparisonUnitTest.java | 225 ------------ .../TreeMapVsHashMapUnitTest.java | 58 --- java-collections-maps/README.md | 16 - java-collections-maps/pom.xml | 35 -- .../main/java/com/baeldung/map/MapUtil.java | 44 --- .../src/main/java/com/baeldung/map/MyKey.java | 64 ---- .../com/baeldung/map/MyLinkedHashMap.java | 23 -- .../src/main/resources/logback.xml | 13 - .../baeldung/guava/GuavaBiMapUnitTest.java | 120 ------- .../baeldung/map/ImmutableMapUnitTest.java | 84 ----- .../com/baeldung/map/KeyCheckUnitTest.java | 27 -- .../map/MapMultipleValuesUnitTest.java | 119 ------- .../java/com/baeldung/map/MapUnitTest.java | 336 ------------------ .../com/baeldung/map/MapUtilUnitTest.java | 103 ------ .../baeldung/map/MultiValuedMapUnitTest.java | 227 ------------ 38 files changed, 2956 deletions(-) delete mode 100644 java-collections-maps-2/README.md delete mode 100644 java-collections-maps-2/pom.xml delete mode 100644 java-collections-maps-2/src/main/java/com/baeldung/map/Product.java delete mode 100644 java-collections-maps-2/src/main/java/com/baeldung/map/convert/MapToString.java delete mode 100644 java-collections-maps-2/src/main/java/com/baeldung/map/convert/StringToMap.java delete mode 100644 java-collections-maps-2/src/main/java/com/baeldung/map/copyhashmap/CopyHashMap.java delete mode 100644 java-collections-maps-2/src/main/java/com/baeldung/map/initialize/MapInitializer.java delete mode 100644 java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java delete mode 100644 java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java delete mode 100644 java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/Employee.java delete mode 100644 java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/MergeMaps.java delete mode 100644 java-collections-maps-2/src/main/java/com/baeldung/map/primitives/PrimitiveMaps.java delete mode 100644 java-collections-maps-2/src/main/java/com/baeldung/map/sort/SortHashMap.java delete mode 100644 java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java delete mode 100644 java-collections-maps-2/src/test/java/com/baeldung/map/convert/MapToStringUnitTest.java delete mode 100644 java-collections-maps-2/src/test/java/com/baeldung/map/convert/StringToMapUnitTest.java delete mode 100644 java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/CopyHashMapUnitTest.java delete mode 100644 java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/Employee.java delete mode 100644 java-collections-maps-2/src/test/java/com/baeldung/map/initialize/MapInitializerUnitTest.java delete mode 100644 java-collections-maps-2/src/test/java/com/baeldung/map/mapmax/MapMaxUnitTest.java delete mode 100644 java-collections-maps-2/src/test/java/com/baeldung/map/weakhashmap/WeakHashMapUnitTest.java delete mode 100644 java-collections-maps-3/README.md delete mode 100644 java-collections-maps-3/pom.xml delete mode 100644 java-collections-maps-3/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java delete mode 100644 java-collections-maps-3/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java delete mode 100644 java-collections-maps/README.md delete mode 100644 java-collections-maps/pom.xml delete mode 100644 java-collections-maps/src/main/java/com/baeldung/map/MapUtil.java delete mode 100644 java-collections-maps/src/main/java/com/baeldung/map/MyKey.java delete mode 100644 java-collections-maps/src/main/java/com/baeldung/map/MyLinkedHashMap.java delete mode 100644 java-collections-maps/src/main/resources/logback.xml delete mode 100644 java-collections-maps/src/test/java/com/baeldung/guava/GuavaBiMapUnitTest.java delete mode 100644 java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java delete mode 100644 java-collections-maps/src/test/java/com/baeldung/map/KeyCheckUnitTest.java delete mode 100644 java-collections-maps/src/test/java/com/baeldung/map/MapMultipleValuesUnitTest.java delete mode 100644 java-collections-maps/src/test/java/com/baeldung/map/MapUnitTest.java delete mode 100644 java-collections-maps/src/test/java/com/baeldung/map/MapUtilUnitTest.java delete mode 100644 java-collections-maps/src/test/java/com/baeldung/map/MultiValuedMapUnitTest.java diff --git a/java-collections-maps-2/README.md b/java-collections-maps-2/README.md deleted file mode 100644 index 2188960543..0000000000 --- a/java-collections-maps-2/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Java Collections Cookbooks and Examples - -This module contains articles about Map data structures in Java. - -### Relevant Articles: -- [Map of Primitives in Java](https://www.baeldung.com/java-map-primitives) -- [Copying a HashMap in Java](https://www.baeldung.com/java-copy-hashmap) -- [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap) -- [Guide to WeakHashMap in Java](https://www.baeldung.com/java-weakhashmap) -- [Map to String Conversion in Java](https://www.baeldung.com/java-map-to-string-conversion) -- [Iterate over a Map in Java](https://www.baeldung.com/java-iterate-map) -- [Merging Two Maps with Java 8](https://www.baeldung.com/java-merge-maps) -- [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) diff --git a/java-collections-maps-2/pom.xml b/java-collections-maps-2/pom.xml deleted file mode 100644 index a246559f61..0000000000 --- a/java-collections-maps-2/pom.xml +++ /dev/null @@ -1,79 +0,0 @@ - - - 4.0.0 - java-collections-maps-2 - 0.1.0-SNAPSHOT - java-collections-maps-2 - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - org.eclipse.collections - eclipse-collections - ${eclipse-collections.version} - - - net.sf.trove4j - trove4j - ${trove4j.version} - - - it.unimi.dsi - fastutil - ${fastutil.version} - - - colt - colt - ${colt.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - - - one.util - streamex - ${streamex.version} - - - com.jayway.awaitility - awaitility - ${avaitility.version} - test - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - 0.6.5 - 4.1 - 1.7.0 - 8.2.0 - 3.0.2 - 8.1.0 - 1.2.0 - 3.11.1 - - - \ No newline at end of file diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/Product.java b/java-collections-maps-2/src/main/java/com/baeldung/map/Product.java deleted file mode 100644 index 5559895730..0000000000 --- a/java-collections-maps-2/src/main/java/com/baeldung/map/Product.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.baeldung.map; - -import java.util.*; - -public class Product { - - private String name; - private String description; - private List tags; - - public Product(String name, String description) { - this.name = name; - this.description = description; - this.tags = new ArrayList<>(); - } - - public String getName() { - return name; - } - - public String getDescription() { - return description; - } - - public List getTags() { - return tags; - } - - public Product addTagsOfOtherProdcut(Product product) { - this.tags.addAll(product.getTags()); - return this; - } - - @Override - public boolean equals(Object o) { - - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - Product product = (Product) o; - return Objects.equals(name, product.name) && - Objects.equals(description, product.description); - } - - @Override - public int hashCode() { - return Objects.hash(name, description); - } - - public static void forEach() { - - HashMap productsByName = new HashMap<>(); - productsByName.forEach( (key, product) - -> System.out.println("Key: " + key + " Product:" + product.getDescription()) - //do something with the key and value - ); - - //Prior to Java 8: - for(Map.Entry entry : productsByName.entrySet()) { - Product product = entry.getValue(); - String key = entry.getKey(); - //do something with the key and value - } - } - - public static void getOrDefault() { - - HashMap productsByName = new HashMap<>(); - Product chocolate = new Product("chocolate", "something sweet"); - Product defaultProduct = productsByName.getOrDefault("horse carriage", chocolate); - Product bike = productsByName.getOrDefault("E-Bike", chocolate); - - //Prior to Java 8: - Product bike2 = productsByName.containsKey("E-Bike") - ? productsByName.get("E-Bike") - : chocolate; - Product defaultProduct2 = productsByName.containsKey("horse carriage") - ? productsByName.get("horse carriage") - : chocolate; - } - - public static void putIfAbsent() { - - HashMap productsByName = new HashMap<>(); - Product chocolate = new Product("chocolate", "something sweet"); - productsByName.putIfAbsent("E-Bike", chocolate); - - //Prior to Java 8: - if(productsByName.containsKey("E-Bike")) { - productsByName.put("E-Bike", chocolate); - } - } - - public static void merge() { - - HashMap productsByName = new HashMap<>(); - Product eBike2 = new Product("E-Bike", "A bike with a battery"); - eBike2.getTags().add("sport"); - productsByName.merge("E-Bike", eBike2, Product::addTagsOfOtherProdcut); - - //Prior to Java 8: - if(productsByName.containsKey("E-Bike")) { - productsByName.get("E-Bike").addTagsOfOtherProdcut(eBike2); - } else { - productsByName.put("E-Bike", eBike2); - } - } - - public static void compute() { - - HashMap productsByName = new HashMap<>(); - Product eBike2 = new Product("E-Bike", "A bike with a battery"); - - productsByName.compute("E-Bike", (k,v) -> { - if(v != null) { - return v.addTagsOfOtherProdcut(eBike2); - } else { - return eBike2; - } - }); - - //Prior to Java 8: - if(productsByName.containsKey("E-Bike")) { - productsByName.get("E-Bike").addTagsOfOtherProdcut(eBike2); - } else { - productsByName.put("E-Bike", eBike2); - } - } -} diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/convert/MapToString.java b/java-collections-maps-2/src/main/java/com/baeldung/map/convert/MapToString.java deleted file mode 100644 index d13be924ff..0000000000 --- a/java-collections-maps-2/src/main/java/com/baeldung/map/convert/MapToString.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.map.convert; - -import com.google.common.base.Joiner; -import org.apache.commons.lang3.StringUtils; - -import java.util.Map; -import java.util.stream.Collectors; - -public class MapToString { - - public static String convertWithIteration(Map map) { - StringBuilder mapAsString = new StringBuilder("{"); - for (Integer key : map.keySet()) { - mapAsString.append(key + "=" + map.get(key) + ", "); - } - mapAsString.delete(mapAsString.length()-2, mapAsString.length()).append("}"); - return mapAsString.toString(); - } - - public static String convertWithStream(Map map) { - String mapAsString = map.keySet().stream() - .map(key -> key + "=" + map.get(key)) - .collect(Collectors.joining(", ", "{", "}")); - return mapAsString; - } - - public static String convertWithGuava(Map map) { - return Joiner.on(",").withKeyValueSeparator("=").join(map); - } - - public static String convertWithApache(Map map) { - return StringUtils.join(map); - } -} diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/convert/StringToMap.java b/java-collections-maps-2/src/main/java/com/baeldung/map/convert/StringToMap.java deleted file mode 100644 index 416ba4dd9a..0000000000 --- a/java-collections-maps-2/src/main/java/com/baeldung/map/convert/StringToMap.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.map.convert; - -import com.google.common.base.Splitter; - -import java.util.Arrays; -import java.util.Map; -import java.util.stream.Collectors; - -public class StringToMap { - - public static Map convertWithStream(String mapAsString) { - Map map = Arrays.stream(mapAsString.split(",")) - .map(entry -> entry.split("=")) - .collect(Collectors.toMap(entry -> entry[0], entry -> entry[1])); - return map; - } - - public static Map convertWithGuava(String mapAsString) { - return Splitter.on(',').withKeyValueSeparator('=').split(mapAsString); - } -} diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/copyhashmap/CopyHashMap.java b/java-collections-maps-2/src/main/java/com/baeldung/map/copyhashmap/CopyHashMap.java deleted file mode 100644 index cb18f3aa11..0000000000 --- a/java-collections-maps-2/src/main/java/com/baeldung/map/copyhashmap/CopyHashMap.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.baeldung.map.copyhashmap; - -import org.apache.commons.lang3.SerializationUtils; - -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.stream.Collectors; - -public class CopyHashMap { - - public static HashMap copyUsingConstructor(HashMap originalMap) { - return new HashMap(originalMap); - } - - public static HashMap copyUsingClone(HashMap originalMap) { - return (HashMap) originalMap.clone(); - } - - public static HashMap copyUsingPut(HashMap originalMap) { - HashMap shallowCopy = new HashMap(); - Set> entries = originalMap.entrySet(); - for(Map.Entry mapEntry: entries) { - shallowCopy.put(mapEntry.getKey(), mapEntry.getValue()); - } - - return shallowCopy; - } - - public static HashMap copyUsingPutAll(HashMap originalMap) { - HashMap shallowCopy = new HashMap(); - shallowCopy.putAll(originalMap); - - return shallowCopy; - } - - public static HashMap copyUsingJava8Stream(HashMap originalMap) { - Set> entries = originalMap.entrySet(); - HashMap shallowCopy = (HashMap) entries - .stream() - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - - return shallowCopy; - } - - public static HashMap shallowCopy(HashMap originalMap) { - return (HashMap) originalMap.clone(); - } - - public static HashMap deepCopy(HashMap originalMap) { - return SerializationUtils.clone(originalMap); - } - -} diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/initialize/MapInitializer.java b/java-collections-maps-2/src/main/java/com/baeldung/map/initialize/MapInitializer.java deleted file mode 100644 index 4d63abcfd0..0000000000 --- a/java-collections-maps-2/src/main/java/com/baeldung/map/initialize/MapInitializer.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.baeldung.map.initialize; - -import java.util.AbstractMap; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -public class MapInitializer { - - public static Map articleMapOne; - static { - articleMapOne = new HashMap<>(); - articleMapOne.put("ar01", "Intro to Map"); - articleMapOne.put("ar02", "Some article"); - } - - public static Map createSingletonMap() { - Map passwordMap = Collections.singletonMap("username1", "password1"); - return passwordMap; - - } - - public Map createEmptyMap() { - Map emptyMap = Collections.emptyMap(); - return emptyMap; - } - - public Map createUsingDoubleBrace() { - Map doubleBraceMap = new HashMap() { - - /** - * - */ - private static final long serialVersionUID = 1L; - - { - put("key1", "value1"); - put("key2", "value2"); - } - }; - return doubleBraceMap; - } - - public Map createMapUsingStreamStringArray() { - Map map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, }) - .collect(Collectors.toMap(data -> data[0], data -> data[1])); - - return map; - } - - public Map createMapUsingStreamObjectArray() { - Map map = Stream.of(new Object[][] { { "data1", 1 }, { "data2", 2 }, }) - .collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1])); - - return map; - } - - public Map createMapUsingStreamSimpleEntry() { - Map map = Stream.of(new AbstractMap.SimpleEntry<>("idea", 1), new AbstractMap.SimpleEntry<>("mobile", 2)) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - - return map; - } - - public Map createMapUsingStreamSimpleImmutableEntry() { - Map map = Stream.of(new AbstractMap.SimpleImmutableEntry<>("idea", 1), new AbstractMap.SimpleImmutableEntry<>("mobile", 2)) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - - return map; - } - - public Map createImmutableMapWithStreams() { - Map map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, }) - .collect(Collectors.collectingAndThen(Collectors.toMap(data -> data[0], data -> data[1]), Collections:: unmodifiableMap)); - return map; - - } -} diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java b/java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java deleted file mode 100644 index b0c32e1487..0000000000 --- a/java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.map.iteration; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -public class MapIteration { - - public static void main(String[] args) { - MapIteration mapIteration = new MapIteration(); - Map map = new HashMap<>(); - - map.put("One", 1); - map.put("Three", 3); - map.put("Two", 2); - - System.out.println("Iterating Keys of Map Using KeySet"); - mapIteration.iterateKeys(map); - - System.out.println("Iterating Map Using Entry Set"); - mapIteration.iterateUsingEntrySet(map); - - System.out.println("Iterating Using Iterator and Map Entry"); - mapIteration.iterateUsingIteratorAndEntry(map); - - System.out.println("Iterating Using KeySet and For Each"); - mapIteration.iterateUsingKeySetAndForeach(map); - - System.out.println("Iterating Map Using Lambda Expression"); - mapIteration.iterateUsingLambda(map); - - System.out.println("Iterating Using Stream API"); - mapIteration.iterateUsingStreamAPI(map); - } - - public void iterateUsingEntrySet(Map map) { - for (Map.Entry entry : map.entrySet()) { - System.out.println(entry.getKey() + ":" + entry.getValue()); - } - } - - public void iterateUsingLambda(Map map) { - map.forEach((k, v) -> System.out.println((k + ":" + v))); - } - - public void iterateUsingIteratorAndEntry(Map map) { - Iterator> iterator = map.entrySet() - .iterator(); - while (iterator.hasNext()) { - Map.Entry pair = iterator.next(); - System.out.println(pair.getKey() + ":" + pair.getValue()); - } - } - - public void iterateUsingKeySetAndForeach(Map map) { - for (String key : map.keySet()) { - System.out.println(key + ":" + map.get(key)); - } - } - - public void iterateUsingStreamAPI(Map map) { - map.entrySet() - .stream() - .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue())); - } - - public void iterateKeys(Map map) { - for (String key : map.keySet()) { - System.out.println(key); - } - - } - -} \ No newline at end of file diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java b/java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java deleted file mode 100644 index 8c33c857ee..0000000000 --- a/java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.baeldung.map.mapmax; - -import java.util.*; -import java.util.Map.Entry; - -public class MapMax { - - public > V maxUsingIteration(Map map) { - - Map.Entry maxEntry = null; - - for (Map.Entry entry : map.entrySet()) { - - if (maxEntry == null || entry.getValue() - .compareTo(maxEntry.getValue()) > 0) { - maxEntry = entry; - } - } - - return maxEntry.getValue(); - } - - public > V maxUsingCollectionsMax(Map map) { - - Entry maxEntry = Collections.max(map.entrySet(), new Comparator>() { - public int compare(Entry e1, Entry e2) { - return e1.getValue() - .compareTo(e2.getValue()); - } - }); - - return maxEntry.getValue(); - } - - public > V maxUsingCollectionsMaxAndLambda(Map map) { - - Entry maxEntry = Collections.max(map.entrySet(), (Entry e1, Entry e2) -> e1.getValue() - .compareTo(e2.getValue())); - - return maxEntry.getValue(); - } - - public > V maxUsingCollectionsMaxAndMethodReference(Map map) { - - Entry maxEntry = Collections.max(map.entrySet(), Comparator.comparing(Map.Entry::getValue)); - - return maxEntry.getValue(); - } - - public > V maxUsingStreamAndLambda(Map map) { - - Optional> maxEntry = map.entrySet() - .stream() - .max((Entry e1, Entry e2) -> e1.getValue() - .compareTo(e2.getValue())); - - return maxEntry.get() - .getValue(); - } - - public > V maxUsingStreamAndMethodReference(Map map) { - - Optional> maxEntry = map.entrySet() - .stream() - .max(Comparator.comparing(Map.Entry::getValue)); - - return maxEntry.get() - .getValue(); - } - - public static void main(String[] args) { - - Map map = new HashMap(); - - map.put(1, 3); - map.put(2, 4); - map.put(3, 5); - map.put(4, 6); - map.put(5, 7); - - MapMax mapMax = new MapMax(); - - System.out.println(mapMax.maxUsingIteration(map)); - System.out.println(mapMax.maxUsingCollectionsMax(map)); - System.out.println(mapMax.maxUsingCollectionsMaxAndLambda(map)); - System.out.println(mapMax.maxUsingCollectionsMaxAndMethodReference(map)); - System.out.println(mapMax.maxUsingStreamAndLambda(map)); - System.out.println(mapMax.maxUsingStreamAndMethodReference(map)); - - } - -} diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/Employee.java b/java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/Employee.java deleted file mode 100644 index d7fb0d1a1d..0000000000 --- a/java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/Employee.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.map.mergemaps; - -public class Employee implements Comparable { - - private Long id; - private String name; - - public Employee(Long id, String name) { - this.name = name; - this.id = id; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Employee employee = (Employee) o; - - if (!id.equals(employee.id)) return false; - return name.equals(employee.name); - - } - - @Override - public int hashCode() { - int result = id.hashCode(); - result = 31 * result + name.hashCode(); - return result; - } - - @Override - public String toString() { - return "Employee{" + - "id=" + id + - ", name='" + name + '\'' + - '}'; - } - - @Override - public int compareTo(Employee employee) { - return (int)(this.id - employee.getId()); - } -} diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/MergeMaps.java b/java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/MergeMaps.java deleted file mode 100644 index 4f187bad90..0000000000 --- a/java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/MergeMaps.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.baeldung.map.mergemaps; - -import one.util.streamex.EntryStream; - -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -public class MergeMaps { - - private static Map map1 = new HashMap<>(); - private static Map map2 = new HashMap<>(); - - public static void main(String[] args) { - - initialize(); - - mergeFunction(); - - streamConcat(); - - streamOf(); - - streamEx(); - - streamMerge(); - } - - private static void streamMerge() { - - Map map3 = map2.entrySet() - .stream() - .collect( - Collectors.toMap( - Map.Entry::getKey, - Map.Entry::getValue, - (v1, v2) -> new Employee(v1.getId(), v2.getName()), - () -> new HashMap<>(map1) - ) - ); - - System.out.println(map3); - } - - private static void streamEx() { - Map map3 = EntryStream.of(map1) - .append(EntryStream.of(map2)) - .toMap((e1, e2) -> e1); - - System.out.println(map3); - - } - - private static void streamOf() { - Map map3 = Stream.of(map1, map2) - .flatMap(map -> map.entrySet().stream()) - .collect( - Collectors.toMap( - Map.Entry::getKey, - Map.Entry::getValue, - (v1, v2) -> new Employee(v1.getId(), v2.getName()) - ) - ); - - map3.entrySet().forEach(System.out::println); - } - - private static void streamConcat() { - Map result = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream()).collect(Collectors.toMap( - Map.Entry::getKey, - Map.Entry::getValue, - (value1, value2) -> new Employee(value2.getId(), value1.getName()) - )); - - result.entrySet().forEach(System.out::println); - } - - private static void mergeFunction() { - Map map3 = new HashMap<>(map1); - - map2.forEach( - (key, value) -> map3.merge(key, value, (v1, v2) -> - new Employee(v1.getId(), v2.getName())) - ); - - map3.entrySet().forEach(System.out::println); - } - - - private static void initialize() { - Employee employee1 = new Employee(1L, "Henry"); - map1.put(employee1.getName(), employee1); - Employee employee2 = new Employee(22L, "Annie"); - map1.put(employee2.getName(), employee2); - Employee employee3 = new Employee(8L, "John"); - map1.put(employee3.getName(), employee3); - - Employee employee4 = new Employee(2L, "George"); - map2.put(employee4.getName(), employee4); - Employee employee5 = new Employee(3L, "Henry"); - map2.put(employee5.getName(), employee5); - } - -} diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/primitives/PrimitiveMaps.java b/java-collections-maps-2/src/main/java/com/baeldung/map/primitives/PrimitiveMaps.java deleted file mode 100644 index 30bec12ccc..0000000000 --- a/java-collections-maps-2/src/main/java/com/baeldung/map/primitives/PrimitiveMaps.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.map.primitives; - -import cern.colt.map.AbstractIntDoubleMap; -import cern.colt.map.OpenIntDoubleHashMap; -import gnu.trove.map.TDoubleIntMap; -import gnu.trove.map.hash.TDoubleIntHashMap; -import it.unimi.dsi.fastutil.ints.Int2BooleanMap; -import it.unimi.dsi.fastutil.ints.Int2BooleanOpenHashMap; -import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMap; -import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMaps; -import org.eclipse.collections.api.map.primitive.ImmutableIntIntMap; -import org.eclipse.collections.api.map.primitive.MutableIntIntMap; -import org.eclipse.collections.api.map.primitive.MutableObjectDoubleMap; -import org.eclipse.collections.impl.factory.primitive.IntIntMaps; -import org.eclipse.collections.impl.factory.primitive.ObjectDoubleMaps; - -public class PrimitiveMaps { - - public static void main(String[] args) { - - eclipseCollectionsMap(); - troveMap(); - coltMap(); - fastutilMap(); - } - - private static void fastutilMap() { - Int2BooleanMap int2BooleanMap = new Int2BooleanOpenHashMap(); - int2BooleanMap.put(1, true); - int2BooleanMap.put(7, false); - int2BooleanMap.put(4, true); - - boolean value = int2BooleanMap.get(1); - - Int2BooleanSortedMap int2BooleanSorted = Int2BooleanSortedMaps.EMPTY_MAP; - } - - private static void coltMap() { - AbstractIntDoubleMap map = new OpenIntDoubleHashMap(); - map.put(1, 4.5); - double value = map.get(1); - } - - private static void eclipseCollectionsMap() { - MutableIntIntMap mutableIntIntMap = IntIntMaps.mutable.empty(); - mutableIntIntMap.addToValue(1, 1); - - ImmutableIntIntMap immutableIntIntMap = IntIntMaps.immutable.empty(); - - MutableObjectDoubleMap dObject = ObjectDoubleMaps.mutable.empty(); - dObject.addToValue("price", 150.5); - dObject.addToValue("quality", 4.4); - dObject.addToValue("stability", 0.8); - } - - private static void troveMap() { - double[] doubles = new double[] {1.2, 4.5, 0.3}; - int[] ints = new int[] {1, 4, 0}; - - TDoubleIntMap doubleIntMap = new TDoubleIntHashMap(doubles, ints); - - doubleIntMap.put(1.2, 22); - doubleIntMap.put(4.5, 16); - - doubleIntMap.adjustValue(1.2, 1); - doubleIntMap.adjustValue(4.5, 4); - doubleIntMap.adjustValue(0.3, 7); - } -} diff --git a/java-collections-maps-2/src/main/java/com/baeldung/map/sort/SortHashMap.java b/java-collections-maps-2/src/main/java/com/baeldung/map/sort/SortHashMap.java deleted file mode 100644 index 14610ffb00..0000000000 --- a/java-collections-maps-2/src/main/java/com/baeldung/map/sort/SortHashMap.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.baeldung.map.sort; - -import com.baeldung.map.mergemaps.Employee; -import com.google.common.base.Functions; -import com.google.common.collect.ImmutableSortedMap; -import com.google.common.collect.Ordering; - -import java.util.*; -import java.util.stream.Collectors; - -public class SortHashMap { - - private static Map map = new HashMap<>(); - - public static void main(String[] args) { - - initialize(); - - treeMapSortByKey(); - - arrayListSortByValue(); - arrayListSortByKey(); - - sortStream(); - - sortGuava(); - - addDuplicates(); - - treeSetByKey(); - treeSetByValue(); - - } - - private static void sortGuava() { - final Ordering naturalOrdering = - Ordering.natural().onResultOf(Functions.forMap(map, null)); - - System.out.println(ImmutableSortedMap.copyOf(map, naturalOrdering)); - } - - private static void sortStream() { - map.entrySet().stream() - .sorted(Map.Entry.comparingByKey().reversed()) - .forEach(System.out::println); - - Map result = map.entrySet().stream() - .sorted(Map.Entry.comparingByValue()) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, - (oldValue, newValue) -> oldValue, LinkedHashMap::new)); - - result.entrySet().forEach(System.out::println); - } - - private static void treeSetByValue() { - SortedSet values = new TreeSet<>(map.values()); - System.out.println(values); - } - - private static void treeSetByKey() { - SortedSet keysSet = new TreeSet<>(map.keySet()); - System.out.println(keysSet); - } - - private static void treeMapSortByKey() { - TreeMap sorted = new TreeMap<>(map); - sorted.putAll(map); - - sorted.entrySet().forEach(System.out::println); - - } - - private static void arrayListSortByValue() { - List employeeById = new ArrayList<>(map.values()); - - Collections.sort(employeeById); - - System.out.println(employeeById); - } - - private static void arrayListSortByKey() { - List employeeByKey = new ArrayList<>(map.keySet()); - Collections.sort(employeeByKey); - System.out.println(employeeByKey); - } - - private static void initialize() { - Employee employee1 = new Employee(1L, "Mher"); - map.put(employee1.getName(), employee1); - Employee employee2 = new Employee(22L, "Annie"); - map.put(employee2.getName(), employee2); - Employee employee3 = new Employee(8L, "John"); - map.put(employee3.getName(), employee3); - Employee employee4 = new Employee(2L, "George"); - map.put(employee4.getName(), employee4); - } - - private static void addDuplicates() { - Employee employee5 = new Employee(1L, "Mher"); - map.put(employee5.getName(), employee5); - Employee employee6 = new Employee(22L, "Annie"); - map.put(employee6.getName(), employee6); - } -} diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java b/java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java deleted file mode 100644 index ba29d5c454..0000000000 --- a/java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java +++ /dev/null @@ -1,174 +0,0 @@ -package com.baeldung.map; - -import org.junit.jupiter.api.Test; - -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - -import static org.junit.jupiter.api.Assertions.*; - -class ProductUnitTest { - - - @Test - public void getExistingValue() { - HashMap productsByName = new HashMap<>(); - - Product eBike = new Product("E-Bike", "A bike with a battery"); - Product roadBike = new Product("Road bike", "A bike for competition"); - - productsByName.put(eBike.getName(), eBike); - productsByName.put(roadBike.getName(), roadBike); - - Product nextPurchase = productsByName.get("E-Bike"); - - assertEquals("A bike with a battery", nextPurchase.getDescription()); - } - - @Test - public void getNonExistingValue() { - HashMap productsByName = new HashMap<>(); - - Product eBike = new Product("E-Bike", "A bike with a battery"); - Product roadBike = new Product("Road bike", "A bike for competition"); - - productsByName.put(eBike.getName(), eBike); - productsByName.put(roadBike.getName(), roadBike); - - Product nextPurchase = productsByName.get("Car"); - - assertNull(nextPurchase); - } - - @Test - public void getExistingValueAfterSameKeyInsertedTwice() { - HashMap productsByName = new HashMap<>(); - - Product eBike = new Product("E-Bike", "A bike with a battery"); - Product roadBike = new Product("Road bike", "A bike for competition"); - Product newEBike = new Product("E-Bike", "A bike with a better battery"); - - productsByName.put(eBike.getName(), eBike); - productsByName.put(roadBike.getName(), roadBike); - productsByName.put(newEBike.getName(), newEBike); - - Product nextPurchase = productsByName.get("E-Bike"); - - assertEquals("A bike with a better battery", nextPurchase.getDescription()); - } - - @Test - public void getExistingValueWithNullKey() { - HashMap productsByName = new HashMap<>(); - - Product defaultProduct = new Product("Chocolate", "At least buy chocolate"); - - productsByName.put(null, defaultProduct); - productsByName.put(defaultProduct.getName(), defaultProduct); - - Product nextPurchase = productsByName.get(null); - assertEquals("At least buy chocolate", nextPurchase.getDescription()); - - nextPurchase = productsByName.get("Chocolate"); - assertEquals("At least buy chocolate", nextPurchase.getDescription()); - } - - @Test - public void insertSameObjectWithDifferentKey() { - HashMap productsByName = new HashMap<>(); - - Product defaultProduct = new Product("Chocolate", "At least buy chocolate"); - - productsByName.put(null, defaultProduct); - productsByName.put(defaultProduct.getName(), defaultProduct); - - assertSame(productsByName.get(null), productsByName.get("Chocolate")); - } - - @Test - public void checkIfKeyExists() { - HashMap productsByName = new HashMap<>(); - - Product eBike = new Product("E-Bike", "A bike with a battery"); - - productsByName.put(eBike.getName(), eBike); - - assertTrue(productsByName.containsKey("E-Bike")); - } - - @Test - public void checkIfValueExists() { - HashMap productsByName = new HashMap<>(); - - Product eBike = new Product("E-Bike", "A bike with a battery"); - - productsByName.put(eBike.getName(), eBike); - - assertTrue(productsByName.containsValue(eBike)); - } - - @Test - public void removeExistingKey() { - HashMap productsByName = new HashMap<>(); - - Product eBike = new Product("E-Bike", "A bike with a battery"); - Product roadBike = new Product("Road bike", "A bike for competition"); - - productsByName.put(eBike.getName(), eBike); - productsByName.put(roadBike.getName(), roadBike); - - productsByName.remove("E-Bike"); - - assertNull(productsByName.get("E-Bike")); - } - - @Test - public void givenMutableKeyWhenKeyChangeThenValueNotFound() { - // Given - MutableKey key = new MutableKey("initial"); - - Map items = new HashMap<>(); - items.put(key, "success"); - - // When - key.setName("changed"); - - // Then - assertNull(items.get(key)); - } - - static class MutableKey { - private String name; - - public MutableKey(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - MutableKey that = (MutableKey) o; - return Objects.equals(name, that.name); - } - - @Override - public int hashCode() { - return Objects.hash(name); - } - } - -} diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/convert/MapToStringUnitTest.java b/java-collections-maps-2/src/test/java/com/baeldung/map/convert/MapToStringUnitTest.java deleted file mode 100644 index 4517dea328..0000000000 --- a/java-collections-maps-2/src/test/java/com/baeldung/map/convert/MapToStringUnitTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.map.convert; - -import org.apache.commons.collections4.MapUtils; -import org.junit.Assert; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.HashMap; -import java.util.Map; - -public class MapToStringUnitTest { - - private Map wordsByKey = new HashMap<>(); - - @BeforeEach - public void setup() { - wordsByKey.clear(); - wordsByKey.put(1, "one"); - wordsByKey.put(2, "two"); - wordsByKey.put(3, "three"); - wordsByKey.put(4, "four"); - } - - @Test - public void givenMap_WhenUsingIteration_ThenResultingMapIsCorrect() { - String mapAsString = MapToString.convertWithIteration(wordsByKey); - Assert.assertEquals("{1=one, 2=two, 3=three, 4=four}", mapAsString); - } - - @Test - public void givenMap_WhenUsingStream_ThenResultingMapIsCorrect() { - String mapAsString = MapToString.convertWithStream(wordsByKey); - Assert.assertEquals("{1=one, 2=two, 3=three, 4=four}", mapAsString); - } - - @Test - public void givenMap_WhenUsingGuava_ThenResultingMapIsCorrect() { - String mapAsString = MapToString.convertWithGuava(wordsByKey); - Assert.assertEquals("1=one,2=two,3=three,4=four", mapAsString); - } - - @Test - public void givenMap_WhenUsingApache_ThenResultingMapIsCorrect() { - String mapAsString = MapToString.convertWithApache(wordsByKey); - Assert.assertEquals("{1=one, 2=two, 3=three, 4=four}", mapAsString); - MapUtils.debugPrint(System.out, "Map as String", wordsByKey); - } -} \ No newline at end of file diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/convert/StringToMapUnitTest.java b/java-collections-maps-2/src/test/java/com/baeldung/map/convert/StringToMapUnitTest.java deleted file mode 100644 index 2f80b30871..0000000000 --- a/java-collections-maps-2/src/test/java/com/baeldung/map/convert/StringToMapUnitTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.map.convert; - -import org.junit.Assert; -import org.junit.jupiter.api.Test; - -import java.util.Map; - -public class StringToMapUnitTest { - - @Test - public void givenString_WhenUsingStream_ThenResultingStringIsCorrect() { - Map wordsByKey = StringToMap.convertWithStream("1=one,2=two,3=three,4=four"); - Assert.assertEquals(4, wordsByKey.size()); - Assert.assertEquals("one", wordsByKey.get("1")); - } - - @Test - void givenString_WhenUsingGuava_ThenResultingStringIsCorrect() { - Map wordsByKey = StringToMap.convertWithGuava("1=one,2=two,3=three,4=four"); - Assert.assertEquals(4, wordsByKey.size()); - Assert.assertEquals("one", wordsByKey.get("1")); - } -} \ No newline at end of file diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/CopyHashMapUnitTest.java b/java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/CopyHashMapUnitTest.java deleted file mode 100644 index e2d5e327e1..0000000000 --- a/java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/CopyHashMapUnitTest.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.baeldung.map.copyhashmap; - -import com.google.common.collect.ImmutableMap; -import org.junit.Test; - -import java.util.HashMap; -import java.util.Map; - -import static org.assertj.core.api.Assertions.assertThat; - -public class CopyHashMapUnitTest { - - @Test - public void givenHashMap_whenShallowCopy_thenCopyisNotSameAsOriginal() { - - HashMap map = new HashMap<>(); - Employee emp1 = new Employee("John"); - Employee emp2 = new Employee("Norman"); - map.put("emp1",emp1); - map.put("emp2",emp2); - - HashMap shallowCopy = CopyHashMap.shallowCopy(map); - - assertThat(shallowCopy).isNotSameAs(map); - - } - - @Test - public void givenHashMap_whenShallowCopyModifyingOriginalObject_thenCopyShouldChange() { - - HashMap map = new HashMap<>(); - Employee emp1 = new Employee("John"); - Employee emp2 = new Employee("Norman"); - map.put("emp1",emp1); - map.put("emp2",emp2); - - HashMap shallowCopy = CopyHashMap.shallowCopy(map); - - emp1.setName("Johny"); - - assertThat(shallowCopy.get("emp1")).isEqualTo(map.get("emp1")); - - } - - @Test - public void givenHashMap_whenDeepCopyModifyingOriginalObject_thenCopyShouldNotChange() { - - HashMap map = new HashMap<>(); - Employee emp1 = new Employee("John"); - Employee emp2 = new Employee("Norman"); - map.put("emp1",emp1); - map.put("emp2",emp2); - HashMap deepCopy = CopyHashMap.deepCopy(map); - - emp1.setName("Johny"); - - assertThat(deepCopy.get("emp1")).isNotEqualTo(map.get("emp1")); - - } - - @Test - public void givenImmutableMap_whenCopyUsingGuava_thenCopyShouldNotChange() { - Employee emp1 = new Employee("John"); - Employee emp2 = new Employee("Norman"); - - Map map = ImmutableMap. builder() - .put("emp1",emp1) - .put("emp2",emp2) - .build(); - Map shallowCopy = ImmutableMap.copyOf(map); - - assertThat(shallowCopy).isSameAs(map); - - } - -} diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/Employee.java b/java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/Employee.java deleted file mode 100644 index 5db55c26ea..0000000000 --- a/java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/Employee.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.map.copyhashmap; - -import java.io.Serializable; - -public class Employee implements Serializable{ - - private String name; - - public Employee(String name) { - super(); - this.name = name; - } - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public String toString() { - return this.name; - } - -} - - diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/initialize/MapInitializerUnitTest.java b/java-collections-maps-2/src/test/java/com/baeldung/map/initialize/MapInitializerUnitTest.java deleted file mode 100644 index 7c6dffe787..0000000000 --- a/java-collections-maps-2/src/test/java/com/baeldung/map/initialize/MapInitializerUnitTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.map.initialize; - -import org.junit.Test; - -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -public class MapInitializerUnitTest { - - @Test - public void givenStaticMap_whenUpdated_thenCorrect() { - - MapInitializer.articleMapOne.put("NewArticle1", "Convert array to List"); - - assertEquals(MapInitializer.articleMapOne.get("NewArticle1"), "Convert array to List"); - - } - - @Test(expected=UnsupportedOperationException.class) - public void givenSingleTonMap_whenEntriesAdded_throwsException() { - - Map map = MapInitializer.createSingletonMap(); - map.put("username2", "password2"); - } - -} diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/mapmax/MapMaxUnitTest.java b/java-collections-maps-2/src/test/java/com/baeldung/map/mapmax/MapMaxUnitTest.java deleted file mode 100644 index 30b945bfc8..0000000000 --- a/java-collections-maps-2/src/test/java/com/baeldung/map/mapmax/MapMaxUnitTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.map.mapmax; - - -import org.junit.Before; -import org.junit.Test; - -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -public class MapMaxUnitTest { - - Map map = null; - MapMax mapMax = null; - - - @Before - public void setupTestData() { - map = new HashMap(); - map.put(23, 12); - map.put(46, 24); - map.put(27, 38); - mapMax = new MapMax(); - } - - @Test - public void givenMap_whenIterated_thenReturnMaxValue() { - assertEquals(new Integer(38), mapMax.maxUsingIteration(map)); - } - - @Test - public void givenMap_whenUsingCollectionsMax_thenReturnMaxValue() { - assertEquals(new Integer(38), mapMax.maxUsingCollectionsMax(map)); - } - - @Test - public void givenMap_whenUsingCollectionsMaxAndLambda_thenReturnMaxValue() { - assertEquals(new Integer(38), mapMax.maxUsingCollectionsMaxAndLambda(map)); - } - - @Test - public void givenMap_whenUsingCollectionsMaxAndMethodReference_thenReturnMaxValue() { - assertEquals(new Integer(38), mapMax.maxUsingCollectionsMaxAndMethodReference(map)); - } - - @Test - public void givenMap_whenUsingStreamAndLambda_thenReturnMaxValue() { - assertEquals(new Integer(38), mapMax.maxUsingStreamAndLambda(map)); - } - - @Test - public void givenMap_whenUsingStreamAndMethodReference_thenReturnMaxValue() { - assertEquals(new Integer(38), mapMax.maxUsingStreamAndMethodReference (map)); - } - - -} diff --git a/java-collections-maps-2/src/test/java/com/baeldung/map/weakhashmap/WeakHashMapUnitTest.java b/java-collections-maps-2/src/test/java/com/baeldung/map/weakhashmap/WeakHashMapUnitTest.java deleted file mode 100644 index 293f24c378..0000000000 --- a/java-collections-maps-2/src/test/java/com/baeldung/map/weakhashmap/WeakHashMapUnitTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.baeldung.map.weakhashmap; - - -import org.junit.Test; - -import java.util.WeakHashMap; -import java.util.concurrent.TimeUnit; - -import static com.jayway.awaitility.Awaitility.await; -import static org.junit.Assert.assertTrue; - -public class WeakHashMapUnitTest { - - @Test - public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObject() { - //given - WeakHashMap map = new WeakHashMap<>(); - BigImage bigImage = new BigImage("image_id"); - UniqueImageName imageName = new UniqueImageName("name_of_big_image"); - - map.put(imageName, bigImage); - assertTrue(map.containsKey(imageName)); - - //when big image key is not reference anywhere - imageName = null; - System.gc(); - - //then GC will finally reclaim that object - await().atMost(10, TimeUnit.SECONDS).until(map::isEmpty); - } - - @Test - public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObjectButLeaveReferencedObject() { - //given - WeakHashMap map = new WeakHashMap<>(); - BigImage bigImageFirst = new BigImage("foo"); - UniqueImageName imageNameFirst = new UniqueImageName("name_of_big_image"); - - BigImage bigImageSecond = new BigImage("foo_2"); - UniqueImageName imageNameSecond = new UniqueImageName("name_of_big_image_2"); - - map.put(imageNameFirst, bigImageFirst); - map.put(imageNameSecond, bigImageSecond); - assertTrue(map.containsKey(imageNameFirst)); - assertTrue(map.containsKey(imageNameSecond)); - - //when - imageNameFirst = null; - System.gc(); - - //then - await().atMost(10, TimeUnit.SECONDS).until(() -> map.size() == 1); - await().atMost(10, TimeUnit.SECONDS).until(() -> map.containsKey(imageNameSecond)); - } - - - class BigImage { - public final String imageId; - - BigImage(String imageId) { - this.imageId = imageId; - } - } - - class UniqueImageName { - public final String imageName; - - UniqueImageName(String imageName) { - this.imageName = imageName; - } - } -} diff --git a/java-collections-maps-3/README.md b/java-collections-maps-3/README.md deleted file mode 100644 index 886461a35c..0000000000 --- a/java-collections-maps-3/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## 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 deleted file mode 100644 index 30b0d01528..0000000000 --- a/java-collections-maps-3/pom.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - 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-3/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java deleted file mode 100644 index 0edd0cd87b..0000000000 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java +++ /dev/null @@ -1,225 +0,0 @@ -package com.baeldung.map.compare; - -import com.google.common.base.Equivalence; -import com.google.common.collect.MapDifference; -import com.google.common.collect.MapDifference.ValueDifference; -import com.google.common.collect.Maps; -import org.junit.Before; -import org.junit.Test; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.collection.IsMapContaining.hasEntry; -import static org.hamcrest.collection.IsMapContaining.hasKey; -import static org.junit.Assert.*; - -public class HashMapComparisonUnitTest { - - Map asiaCapital1; - Map asiaCapital2; - Map asiaCapital3; - - Map asiaCity1; - Map asiaCity2; - Map asiaCity3; - - @Before - public void setup(){ - asiaCapital1 = new HashMap(); - asiaCapital1.put("Japan", "Tokyo"); - asiaCapital1.put("South Korea", "Seoul"); - - asiaCapital2 = new HashMap(); - asiaCapital2.put("South Korea", "Seoul"); - asiaCapital2.put("Japan", "Tokyo"); - - asiaCapital3 = new HashMap(); - asiaCapital3.put("Japan", "Tokyo"); - asiaCapital3.put("China", "Beijing"); - - asiaCity1 = new HashMap(); - asiaCity1.put("Japan", new String[] { "Tokyo", "Osaka" }); - asiaCity1.put("South Korea", new String[] { "Seoul", "Busan" }); - - asiaCity2 = new HashMap(); - asiaCity2.put("South Korea", new String[] { "Seoul", "Busan" }); - asiaCity2.put("Japan", new String[] { "Tokyo", "Osaka" }); - - asiaCity3 = new HashMap(); - asiaCity3.put("Japan", new String[] { "Tokyo", "Osaka" }); - asiaCity3.put("China", new String[] { "Beijing", "Hong Kong" }); - } - - @Test - public void whenCompareTwoHashMapsUsingEquals_thenSuccess() { - assertTrue(asiaCapital1.equals(asiaCapital2)); - assertFalse(asiaCapital1.equals(asiaCapital3)); - } - - @Test - public void whenCompareTwoHashMapsWithArrayValuesUsingEquals_thenFail() { - assertFalse(asiaCity1.equals(asiaCity2)); - } - - @Test - public void whenCompareTwoHashMapsUsingStreamAPI_thenSuccess() { - assertTrue(areEqual(asiaCapital1, asiaCapital2)); - assertFalse(areEqual(asiaCapital1, asiaCapital3)); - } - - @Test - public void whenCompareTwoHashMapsWithArrayValuesUsingStreamAPI_thenSuccess() { - assertTrue(areEqualWithArrayValue(asiaCity1, asiaCity2)); - assertFalse(areEqualWithArrayValue(asiaCity1, asiaCity3)); - } - - @Test - public void whenCompareTwoHashMapKeys_thenSuccess() { - assertTrue(asiaCapital1.keySet().equals(asiaCapital2.keySet())); - assertFalse(asiaCapital1.keySet().equals(asiaCapital3.keySet())); - } - - @Test - public void whenCompareTwoHashMapKeyValuesUsingStreamAPI_thenSuccess() { - Map asiaCapital3 = new HashMap(); - asiaCapital3.put("Japan", "Tokyo"); - asiaCapital3.put("South Korea", "Seoul"); - asiaCapital3.put("China", "Beijing"); - - Map asiaCapital4 = new HashMap(); - asiaCapital4.put("South Korea", "Seoul"); - asiaCapital4.put("Japan", "Osaka"); - asiaCapital4.put("China", "Beijing"); - - Map result = areEqualKeyValues(asiaCapital3, asiaCapital4); - - assertEquals(3, result.size()); - assertThat(result, hasEntry("Japan", false)); - assertThat(result, hasEntry("South Korea", true)); - assertThat(result, hasEntry("China", true)); - } - - @Test - public void givenDifferentMaps_whenGetDiffUsingGuava_thenSuccess() { - Map asia1 = new HashMap(); - asia1.put("Japan", "Tokyo"); - asia1.put("South Korea", "Seoul"); - asia1.put("India", "New Delhi"); - - Map asia2 = new HashMap(); - asia2.put("Japan", "Tokyo"); - asia2.put("China", "Beijing"); - asia2.put("India", "Delhi"); - - MapDifference diff = Maps.difference(asia1, asia2); - Map> entriesDiffering = diff.entriesDiffering(); - - assertFalse(diff.areEqual()); - assertEquals(1, entriesDiffering.size()); - assertThat(entriesDiffering, hasKey("India")); - assertEquals("New Delhi", entriesDiffering.get("India").leftValue()); - assertEquals("Delhi", entriesDiffering.get("India").rightValue()); - } - - @Test - public void givenDifferentMaps_whenGetEntriesOnOneSideUsingGuava_thenSuccess() { - Map asia1 = new HashMap(); - asia1.put("Japan", "Tokyo"); - asia1.put("South Korea", "Seoul"); - asia1.put("India", "New Delhi"); - - Map asia2 = new HashMap(); - asia2.put("Japan", "Tokyo"); - asia2.put("China", "Beijing"); - asia2.put("India", "Delhi"); - - MapDifference diff = Maps.difference(asia1, asia2); - Map entriesOnlyOnRight = diff.entriesOnlyOnRight(); - Map entriesOnlyOnLeft = diff.entriesOnlyOnLeft(); - - assertEquals(1, entriesOnlyOnRight.size()); - assertThat(entriesOnlyOnRight, hasEntry("China", "Beijing")); - assertEquals(1, entriesOnlyOnLeft.size()); - assertThat(entriesOnlyOnLeft, hasEntry("South Korea", "Seoul")); - } - - @Test - public void givenDifferentMaps_whenGetCommonEntriesUsingGuava_thenSuccess() { - Map asia1 = new HashMap(); - asia1.put("Japan", "Tokyo"); - asia1.put("South Korea", "Seoul"); - asia1.put("India", "New Delhi"); - - Map asia2 = new HashMap(); - asia2.put("Japan", "Tokyo"); - asia2.put("China", "Beijing"); - asia2.put("India", "Delhi"); - - MapDifference diff = Maps.difference(asia1, asia2); - Map entriesInCommon = diff.entriesInCommon(); - - assertEquals(1, entriesInCommon.size()); - assertThat(entriesInCommon, hasEntry("Japan", "Tokyo")); - } - - @Test - public void givenSimilarMapsWithArrayValue_whenCompareUsingGuava_thenFail() { - MapDifference diff = Maps.difference(asiaCity1, asiaCity2); - assertFalse(diff.areEqual()); - } - - @Test - public void givenSimilarMapsWithArrayValue_whenCompareUsingGuavaEquivalence_thenSuccess() { - Equivalence eq = new Equivalence() { - @Override - protected boolean doEquivalent(String[] a, String[] b) { - return Arrays.equals(a, b); - } - - @Override - protected int doHash(String[] value) { - return value.hashCode(); - } - }; - - MapDifference diff = Maps.difference(asiaCity1, asiaCity2, eq); - assertTrue(diff.areEqual()); - - diff = Maps.difference(asiaCity1, asiaCity3, eq); - assertFalse(diff.areEqual()); - } - - // =========================================================================== - - private boolean areEqual(Map first, Map second) { - if (first.size() != second.size()) { - return false; - } - - return first.entrySet() - .stream() - .allMatch(e -> e.getValue() - .equals(second.get(e.getKey()))); - } - - private boolean areEqualWithArrayValue(Map first, Map second) { - if (first.size() != second.size()) { - return false; - } - - return first.entrySet() - .stream() - .allMatch(e -> Arrays.equals(e.getValue(), second.get(e.getKey()))); - } - - private Map areEqualKeyValues(Map first, Map second) { - return first.entrySet() - .stream() - .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().equals(second.get(e.getKey())))); - } - -} diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java deleted file mode 100644 index 1057e3b9f0..0000000000 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.map.treemaphashmap; - -import org.hamcrest.Matchers; -import org.junit.Assert; -import org.junit.Test; - -import java.util.HashMap; -import java.util.Map; -import java.util.TreeMap; - -public class TreeMapVsHashMapUnitTest { - - @Test - public void whenInsertObjectsTreeMap_thenNaturalOrder() { - Map treemap = new TreeMap<>(); - treemap.put(3, "TreeMap"); - treemap.put(2, "vs"); - treemap.put(1, "HashMap"); - Assert.assertThat(treemap.keySet(), Matchers.contains(1, 2, 3)); - } - - @Test(expected = NullPointerException.class) - public void whenInsertNullInTreeMap_thenException() { - Map treemap = new TreeMap<>(); - treemap.put(null, "NullPointerException"); - } - - @Test - public void whenInsertObjectsHashMap_thenRandomOrder() { - Map hashmap = new HashMap<>(); - hashmap.put(3, "TreeMap"); - hashmap.put(2, "vs"); - hashmap.put(1, "HashMap"); - Assert.assertThat(hashmap.keySet(), Matchers.containsInAnyOrder(1, 2, 3)); - } - - @Test - public void whenInsertNullInHashMap_thenInsertsNull() { - Map hashmap = new HashMap<>(); - hashmap.put(null, null); - Assert.assertNull(hashmap.get(null)); - } - - @Test - public void givenHashMapAndTreeMap_whenputDuplicates_thenOnlyUnique() { - Map treeMap = new HashMap<>(); - treeMap.put(1, "Baeldung"); - treeMap.put(1, "Baeldung"); - - Assert.assertTrue(treeMap.size() == 1); - - Map treeMap2 = new TreeMap<>(); - treeMap2.put(1, "Baeldung"); - treeMap2.put(1, "Baeldung"); - - Assert.assertTrue(treeMap2.size() == 1); - } -} \ No newline at end of file diff --git a/java-collections-maps/README.md b/java-collections-maps/README.md deleted file mode 100644 index 8fa6fa32fa..0000000000 --- a/java-collections-maps/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Java Collections Cookbooks and Examples - -This module contains articles about Map data structures in Java. - -### Relevant Articles: -- [Guide to the Guava BiMap](https://www.baeldung.com/guava-bimap) -- [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap) -- [A Guide to LinkedHashMap in Java](https://www.baeldung.com/java-linked-hashmap) -- [A Guide to TreeMap in Java](https://www.baeldung.com/java-treemap) -- [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) -- [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) diff --git a/java-collections-maps/pom.xml b/java-collections-maps/pom.xml deleted file mode 100644 index 38cf1c38ad..0000000000 --- a/java-collections-maps/pom.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - 4.0.0 - java-collections-maps - 0.1.0-SNAPSHOT - java-collections-maps - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - 4.1 - 3.6.1 - - diff --git a/java-collections-maps/src/main/java/com/baeldung/map/MapUtil.java b/java-collections-maps/src/main/java/com/baeldung/map/MapUtil.java deleted file mode 100644 index 91b7197a92..0000000000 --- a/java-collections-maps/src/main/java/com/baeldung/map/MapUtil.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * - */ -package com.baeldung.map; - -import java.util.HashSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.stream.Stream; - -/** - * @author swpraman - * - */ -public class MapUtil { - - public static Stream keys(Map map, V value) { - return map.entrySet() - .stream() - .filter(entry -> value.equals(entry.getValue())) - .map(Map.Entry::getKey); - } - - public static Set getKeys(Map map, V value) { - Set keys = new HashSet<>(); - for (Entry entry : map.entrySet()) { - if (entry.getValue().equals(value)) { - keys.add(entry.getKey()); - } - } - return keys; - } - - public static K getKey(Map map, V value) { - for (Entry entry : map.entrySet()) { - if (entry.getValue().equals(value)) { - return entry.getKey(); - } - } - return null; - } - -} diff --git a/java-collections-maps/src/main/java/com/baeldung/map/MyKey.java b/java-collections-maps/src/main/java/com/baeldung/map/MyKey.java deleted file mode 100644 index 9993d7862c..0000000000 --- a/java-collections-maps/src/main/java/com/baeldung/map/MyKey.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MyKey { - private static final Logger LOG = LoggerFactory.getLogger(MyKey.class); - - private String name; - private int id; - - public MyKey(int id, String name) { - this.id = id; - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - @Override - public int hashCode() { - LOG.debug("Calling hashCode()"); - return id; - } - - @Override - public String toString() { - return "MyKey [name=" + name + ", id=" + id + "]"; - } - - @Override - public boolean equals(Object obj) { - LOG.debug("Calling equals() for key: " + obj); - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - MyKey other = (MyKey) obj; - if (id != other.id) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - -} diff --git a/java-collections-maps/src/main/java/com/baeldung/map/MyLinkedHashMap.java b/java-collections-maps/src/main/java/com/baeldung/map/MyLinkedHashMap.java deleted file mode 100644 index b687e57d85..0000000000 --- a/java-collections-maps/src/main/java/com/baeldung/map/MyLinkedHashMap.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.map; - -import java.util.LinkedHashMap; -import java.util.Map; - -public class MyLinkedHashMap extends LinkedHashMap { - - /** - * - */ - private static final long serialVersionUID = 1L; - private static final int MAX_ENTRIES = 5; - - public MyLinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) { - super(initialCapacity, loadFactor, accessOrder); - } - - @Override - protected boolean removeEldestEntry(Map.Entry eldest) { - return size() > MAX_ENTRIES; - } - -} diff --git a/java-collections-maps/src/main/resources/logback.xml b/java-collections-maps/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/java-collections-maps/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/java-collections-maps/src/test/java/com/baeldung/guava/GuavaBiMapUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/guava/GuavaBiMapUnitTest.java deleted file mode 100644 index b44d2db1aa..0000000000 --- a/java-collections-maps/src/test/java/com/baeldung/guava/GuavaBiMapUnitTest.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.baeldung.guava; - -import static org.junit.Assert.*; -import java.util.HashMap; -import java.util.Map; -import org.junit.Test; -import com.google.common.collect.BiMap; -import com.google.common.collect.EnumHashBiMap; -import com.google.common.collect.HashBiMap; -import com.google.common.collect.ImmutableBiMap; - -public class GuavaBiMapUnitTest { - @Test - public void whenQueryByValue_returnsKey() { - final BiMap capitalCountryBiMap = HashBiMap.create(); - capitalCountryBiMap.put("New Delhi", "India"); - capitalCountryBiMap.put("Washingon, D.C.", "USA"); - capitalCountryBiMap.put("Moscow", "Russia"); - - final String countryCapitalName = capitalCountryBiMap.inverse().get("India"); - - assertEquals("New Delhi", countryCapitalName); - } - - @Test - public void whenCreateBiMapFromExistingMap_returnsKey() { - final Map capitalCountryMap = new HashMap<>(); - capitalCountryMap.put("New Delhi", "India"); - capitalCountryMap.put("Washingon, D.C.", "USA"); - capitalCountryMap.put("Moscow", "Russia"); - final BiMap capitalCountryBiMap = HashBiMap.create(capitalCountryMap); - - final String countryCapitalName = capitalCountryBiMap.inverse().get("India"); - - assertEquals("New Delhi", countryCapitalName); - } - - @Test - public void whenQueryByKey_returnsValue() { - final BiMap capitalCountryBiMap = HashBiMap.create(); - - capitalCountryBiMap.put("New Delhi", "India"); - capitalCountryBiMap.put("Washingon, D.C.", "USA"); - capitalCountryBiMap.put("Moscow", "Russia"); - - assertEquals("USA", capitalCountryBiMap.get("Washingon, D.C.")); - } - - @Test(expected = IllegalArgumentException.class) - public void whenSameValueIsPresent_throwsException() { - final BiMap capitalCountryBiMap = HashBiMap.create(); - - capitalCountryBiMap.put("New Delhi", "India"); - capitalCountryBiMap.put("Washingon, D.C.", "USA"); - capitalCountryBiMap.put("Moscow", "Russia"); - capitalCountryBiMap.put("Trump", "USA"); - } - - @Test - public void givenSameValueIsPresent_whenForcePut_completesSuccessfully() { - final BiMap capitalCountryBiMap = HashBiMap.create(); - - capitalCountryBiMap.put("New Delhi", "India"); - capitalCountryBiMap.put("Washingon, D.C.", "USA"); - capitalCountryBiMap.put("Moscow", "Russia"); - capitalCountryBiMap.forcePut("Trump", "USA"); - - assertEquals("USA", capitalCountryBiMap.get("Trump")); - assertEquals("Trump", capitalCountryBiMap.inverse().get("USA")); - } - - @Test - public void whenSameKeyIsPresent_replacesAlreadyPresent() { - final BiMap capitalCountryBiMap = HashBiMap.create(); - - capitalCountryBiMap.put("New Delhi", "India"); - capitalCountryBiMap.put("Washingon, D.C.", "USA"); - capitalCountryBiMap.put("Moscow", "Russia"); - capitalCountryBiMap.put("Washingon, D.C.", "HongKong"); - - assertEquals("HongKong", capitalCountryBiMap.get("Washingon, D.C.")); - } - - @Test - public void whenUsingImmutableBiMap_allowsPutSuccessfully() { - final BiMap capitalCountryBiMap = new ImmutableBiMap.Builder().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build(); - - assertEquals("USA", capitalCountryBiMap.get("Washingon, D.C.")); - } - - @Test(expected = UnsupportedOperationException.class) - public void whenUsingImmutableBiMap_doesntAllowRemove() { - final BiMap capitalCountryBiMap = new ImmutableBiMap.Builder().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build(); - - capitalCountryBiMap.remove("New Delhi"); - } - - @Test(expected = UnsupportedOperationException.class) - public void whenUsingImmutableBiMap_doesntAllowPut() { - final BiMap capitalCountryBiMap = new ImmutableBiMap.Builder().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build(); - - capitalCountryBiMap.put("New York", "USA"); - } - - private enum Operation { - ADD, SUBTRACT, MULTIPLY, DIVIDE - } - - @Test - public void whenUsingEnumAsKeyInMap_replacesAlreadyPresent() { - final BiMap operationStringBiMap = EnumHashBiMap.create(Operation.class); - - operationStringBiMap.put(Operation.ADD, "Add"); - operationStringBiMap.put(Operation.SUBTRACT, "Subtract"); - operationStringBiMap.put(Operation.MULTIPLY, "Multiply"); - operationStringBiMap.put(Operation.DIVIDE, "Divide"); - - assertEquals("Divide", operationStringBiMap.get(Operation.DIVIDE)); - } -} \ No newline at end of file diff --git a/java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java deleted file mode 100644 index d308aac7eb..0000000000 --- a/java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.baeldung.map; - -import com.google.common.collect.ImmutableMap; -import org.junit.jupiter.api.Test; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.*; - - -public class ImmutableMapUnitTest { - - @Test - public void whenCollectionsUnModifiableMapMethod_thenOriginalCollectionChangesReflectInUnmodifiableMap() { - - Map mutableMap = new HashMap<>(); - mutableMap.put("USA", "North America"); - - Map unmodifiableMap = Collections.unmodifiableMap(mutableMap); - assertThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put("Canada", "North America")); - - mutableMap.remove("USA"); - assertFalse(unmodifiableMap.containsKey("USA")); - - mutableMap.put("Mexico", "North America"); - assertTrue(unmodifiableMap.containsKey("Mexico")); - } - - @Test - @SuppressWarnings("deprecation") - public void whenGuavaImmutableMapFromCopyOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() { - - Map mutableMap = new HashMap<>(); - mutableMap.put("USA", "North America"); - - ImmutableMap immutableMap = ImmutableMap.copyOf(mutableMap); - assertTrue(immutableMap.containsKey("USA")); - - assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America")); - - mutableMap.remove("USA"); - assertTrue(immutableMap.containsKey("USA")); - - mutableMap.put("Mexico", "North America"); - assertFalse(immutableMap.containsKey("Mexico")); - } - - @Test - @SuppressWarnings("deprecation") - public void whenGuavaImmutableMapFromBuilderMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() { - - Map mutableMap = new HashMap<>(); - mutableMap.put("USA", "North America"); - - ImmutableMap immutableMap = ImmutableMap.builder() - .putAll(mutableMap) - .put("Costa Rica", "North America") - .build(); - assertTrue(immutableMap.containsKey("USA")); - assertTrue(immutableMap.containsKey("Costa Rica")); - - assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America")); - - mutableMap.remove("USA"); - assertTrue(immutableMap.containsKey("USA")); - - mutableMap.put("Mexico", "North America"); - assertFalse(immutableMap.containsKey("Mexico")); - } - - @Test - @SuppressWarnings("deprecation") - public void whenGuavaImmutableMapFromOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() { - - ImmutableMap immutableMap = ImmutableMap.of("USA", "North America", "Costa Rica", "North America"); - assertTrue(immutableMap.containsKey("USA")); - assertTrue(immutableMap.containsKey("Costa Rica")); - - assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America")); - } - -} diff --git a/java-collections-maps/src/test/java/com/baeldung/map/KeyCheckUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/map/KeyCheckUnitTest.java deleted file mode 100644 index dbad2e5b5e..0000000000 --- a/java-collections-maps/src/test/java/com/baeldung/map/KeyCheckUnitTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.map; - -import org.junit.Test; - -import java.util.Collections; -import java.util.Map; - -import static org.junit.Assert.*; - -public class KeyCheckUnitTest { - - @Test - public void whenKeyIsPresent_thenContainsKeyReturnsTrue() { - Map map = Collections.singletonMap("key", "value"); - - assertTrue(map.containsKey("key")); - assertFalse(map.containsKey("missing")); - } - - @Test - public void whenKeyHasNullValue_thenGetStillWorks() { - Map map = Collections.singletonMap("nothing", null); - - assertTrue(map.containsKey("nothing")); - assertNull(map.get("nothing")); - } -} \ No newline at end of file diff --git a/java-collections-maps/src/test/java/com/baeldung/map/MapMultipleValuesUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/map/MapMultipleValuesUnitTest.java deleted file mode 100644 index 721b48ea7b..0000000000 --- a/java-collections-maps/src/test/java/com/baeldung/map/MapMultipleValuesUnitTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.baeldung.map; - -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.LinkedHashMultimap; -import com.google.common.collect.Multimap; -import com.google.common.collect.TreeMultimap; -import org.apache.commons.collections4.MultiMap; -import org.apache.commons.collections4.MultiMapUtils; -import org.apache.commons.collections4.MultiValuedMap; -import org.apache.commons.collections4.map.MultiValueMap; -import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; -import org.apache.commons.collections4.multimap.HashSetValuedHashMap; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.*; - -import static org.assertj.core.api.Assertions.assertThat; - -public class MapMultipleValuesUnitTest { - private static final Logger LOG = LoggerFactory.getLogger(MapMultipleValuesUnitTest.class); - - @Test - public void givenHashMap_whenPuttingTwice_thenReturningFirstValue() { - Map map = new HashMap<>(); - assertThat(map.put("key1", "value1")).isEqualTo(null); - assertThat(map.put("key1", "value2")).isEqualTo("value1"); - assertThat(map.get("key1")).isEqualTo("value2"); - } - - @Test - public void givenCollectionAsValue_whenPuttingTwice_thenReturningCollection() { - Map> map = new HashMap<>(); - List list = new ArrayList<>(); - map.put("key1", list); - map.get("key1").add("value1"); - map.get("key1").add("value2"); - assertThat(map.get("key1").get(0)).isEqualTo("value1"); - assertThat(map.get("key1").get(1)).isEqualTo("value2"); - } - - @Test - public void givenCollectionAsValueAndJava8_whenPuttingTwice_thenReturningCollection() { - Map> map = new HashMap<>(); - map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value1"); - map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value2"); - assertThat(map.get("key1").get(0)).isEqualTo("value1"); - assertThat(map.get("key1").get(1)).isEqualTo("value2"); - } - - @Test - public void givenMultiValueMap_whenPuttingTwice_thenReturningValues() { - MultiMap map = new MultiValueMap<>(); - map.put("key1", "value1"); - map.put("key1", "value2"); - assertThat((Collection) map.get("key1")) - .contains("value1", "value2"); - } - - @Test - public void givenArrayListValuedHashMap_whenPuttingDoubleValues_thenReturningAllValues() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key1", "value1"); - map.put("key1", "value2"); - map.put("key1", "value2"); - assertThat((Collection) map.get("key1")) - .containsExactly("value1", "value2", "value2"); - } - - @Test - public void givenHashSetValuedHashMap_whenPuttingTwiceTheSame_thenReturningOneValue() { - MultiValuedMap map = new HashSetValuedHashMap<>(); - map.put("key1", "value1"); - map.put("key1", "value1"); - assertThat((Collection) map.get("key1")) - .containsExactly("value1"); - } - - @Test(expected = UnsupportedOperationException.class) - public void givenUnmodifiableMultiValuedMap_whenInserting_thenThrowingException() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("key1", "value1"); - map.put("key1", "value2"); - MultiValuedMap immutableMap = - MultiMapUtils.unmodifiableMultiValuedMap(map); - immutableMap.put("key1", "value3"); - } - - @Test - public void givenArrayListMultiMap_whenInserting_thenCorrectOutput() { - Multimap map = ArrayListMultimap.create(); - map.put("key1", "value2"); - map.put("key1", "value1"); - assertThat((Collection) map.get("key1")) - .containsExactly("value2", "value1"); - } - - @Test - public void givenLinkedHashMultiMap_whenInserting_thenReturningValuesInInsertionOrder() { - Multimap map = LinkedHashMultimap.create(); - map.put("key1", "value3"); - map.put("key1", "value1"); - map.put("key1", "value2"); - assertThat((Collection) map.get("key1")) - .containsExactly("value3", "value1", "value2"); - } - - @Test - public void givenTreeMultimap_whenInserting_thenReturningValuesInNaturalOrder() { - Multimap map = TreeMultimap.create(); - map.put("key1", "value3"); - map.put("key1", "value1"); - map.put("key1", "value2"); - assertThat((Collection) map.get("key1")) - .containsExactly("value1", "value2", "value3"); - } - -} \ No newline at end of file diff --git a/java-collections-maps/src/test/java/com/baeldung/map/MapUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/map/MapUnitTest.java deleted file mode 100644 index eaf68ccba5..0000000000 --- a/java-collections-maps/src/test/java/com/baeldung/map/MapUnitTest.java +++ /dev/null @@ -1,336 +0,0 @@ -package com.baeldung.map; - -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.*; -import java.util.Map.Entry; - -import static org.junit.Assert.*; - -public class MapUnitTest { - private static final Logger LOG = LoggerFactory.getLogger(MapUnitTest.class); - - - @Test - public void givenHashMap_whenRetrievesKeyset_thenCorrect() { - Map map = new HashMap<>(); - map.put("name", "baeldung"); - map.put("type", "blog"); - - Set keys = map.keySet(); - - assertEquals(2, keys.size()); - assertTrue(keys.contains("name")); - assertTrue(keys.contains("type")); - } - - @Test - public void givenHashMap_whenRetrievesValues_thenCorrect() { - Map map = new HashMap<>(); - map.put("name", "baeldung"); - map.put("type", "blog"); - - Collection values = map.values(); - - assertEquals(2, values.size()); - assertTrue(values.contains("baeldung")); - assertTrue(values.contains("blog")); - } - - @Test - public void givenHashMap_whenRetrievesEntries_thenCorrect() { - Map map = new HashMap<>(); - map.put("name", "baeldung"); - map.put("type", "blog"); - - Set> entries = map.entrySet(); - - assertEquals(2, entries.size()); - for (Entry e : entries) { - String key = e.getKey(); - String val = e.getValue(); - assertTrue(key.equals("name") || key.equals("type")); - assertTrue(val.equals("baeldung") || val.equals("blog")); - } - } - - @Test - public void givenKeySet_whenChangeReflectsInMap_thenCorrect() { - Map map = new HashMap<>(); - map.put("name", "baeldung"); - map.put("type", "blog"); - - assertEquals(2, map.size()); - - Set keys = map.keySet(); - - keys.remove("name"); - assertEquals(1, map.size()); - } - - @Test(expected = ConcurrentModificationException.class) - public void givenIterator_whenFailsFastOnModification_thenCorrect() { - Map map = new HashMap<>(); - map.put("name", "baeldung"); - map.put("type", "blog"); - - Set keys = map.keySet(); - Iterator it = keys.iterator(); - map.remove("type"); - while (it.hasNext()) { - String key = it.next(); - } - } - - public void givenIterator_whenRemoveWorks_thenCorrect() { - Map map = new HashMap<>(); - map.put("name", "baeldung"); - map.put("type", "blog"); - - Set keys = map.keySet(); - Iterator it = keys.iterator(); - while (it.hasNext()) { - it.next(); - it.remove(); - } - assertEquals(0, map.size()); - } - - @Test - public void whenHashCodeIsCalledOnPut_thenCorrect() { - MyKey key = new MyKey(1, "name"); - Map map = new HashMap<>(); - map.put(key, "val"); - } - - @Test - public void whenHashCodeIsCalledOnGet_thenCorrect() { - MyKey key = new MyKey(1, "name"); - Map map = new HashMap<>(); - map.put(key, "val"); - map.get(key); - } - - @Test - public void whenGetWorks_thenCorrect() { - Map map = new HashMap<>(); - map.put("key", "val"); - - String val = map.get("key"); - - assertEquals("val", val); - } - - @Test - public void givenNewKey_whenPutReturnsNull_thenCorrect() { - Map map = new HashMap<>(); - - String rtnVal = map.put("key1", "val1"); - - assertNull(rtnVal); - } - - @Test - public void givenUnmappedKey_whenGetReturnsNull_thenCorrect() { - Map map = new HashMap<>(); - - String rtnVal = map.get("key1"); - - assertNull(rtnVal); - } - - @Test - public void givenNullVal_whenPutReturnsNull_thenCorrect() { - Map map = new HashMap<>(); - - String rtnVal = map.put("key1", null); - - assertNull(rtnVal); - } - - @Test - public void givenNullKeyAndVal_whenAccepts_thenCorrect() { - Map map = new HashMap<>(); - - map.put(null, null); - } - - @Test - public void givenNullVal_whenRetrieves_thenCorrect() { - Map map = new HashMap<>(); - map.put("key", null); - - String val = map.get("key"); - - assertNull(val); - } - - @Test - public void whenContainsDistinguishesNullValues_thenCorrect() { - Map map = new HashMap<>(); - - String val1 = map.get("key"); - boolean valPresent = map.containsKey("key"); - - assertNull(val1); - assertFalse(valPresent); - - map.put("key", null); - String val = map.get("key"); - valPresent = map.containsKey("key"); - - assertNull(val); - assertTrue(valPresent); - - } - - @Test - public void whenPutReturnsPrevValue_thenCorrect() { - Map map = new HashMap<>(); - map.put("key1", "val1"); - String rtnVal = map.put("key1", "val2"); - - assertEquals("val1", rtnVal); - } - - @Test - public void whenCallsEqualsOnCollision_thenCorrect() { - HashMap map = new HashMap<>(); - MyKey k1 = new MyKey(1, "firstKey"); - MyKey k2 = new MyKey(2, "secondKey"); - MyKey k3 = new MyKey(2, "thirdKey"); - - LOG.debug("storing value for k1"); - map.put(k1, "firstValue"); - - LOG.debug("storing value for k2"); - map.put(k2, "secondValue"); - - LOG.debug("storing value for k3"); - map.put(k3, "thirdValue"); - - LOG.debug("retrieving value for k1"); - String v1 = map.get(k1); - - LOG.debug("retrieving value for k2"); - String v2 = map.get(k2); - - LOG.debug("retrieving value for k3"); - String v3 = map.get(k3); - - assertEquals("firstValue", v1); - assertEquals("secondValue", v2); - assertEquals("thirdValue", v3); - - } - - @Test - public void givenLinkedHashMap_whenGetsOrderedKeyset_thenCorrect() { - LinkedHashMap map = new LinkedHashMap<>(); - map.put(1, null); - map.put(2, null); - map.put(3, null); - map.put(4, null); - map.put(5, null); - Set keys = map.keySet(); - Integer[] arr = keys.toArray(new Integer[0]); - for (int i = 0; i < arr.length; i++) { - assertEquals(new Integer(i + 1), arr[i]); - - } - } - - @Test - public void givenLinkedHashMap_whenAccessOrderWorks_thenCorrect() { - LinkedHashMap map = new LinkedHashMap<>(16, .75f, true); - map.put(1, null); - map.put(2, null); - map.put(3, null); - map.put(4, null); - map.put(5, null); - Set keys = map.keySet(); - assertEquals("[1, 2, 3, 4, 5]", keys.toString()); - map.get(4); - assertEquals("[1, 2, 3, 5, 4]", keys.toString()); - map.get(1); - assertEquals("[2, 3, 5, 4, 1]", keys.toString()); - map.get(3); - assertEquals("[2, 5, 4, 1, 3]", keys.toString()); - } - - @Test - public void givenLinkedHashMap_whenRemovesEldestEntry_thenCorrect() { - LinkedHashMap map = new MyLinkedHashMap<>(16, .75f, true); - map.put(1, null); - map.put(2, null); - map.put(3, null); - map.put(4, null); - map.put(5, null); - Set keys = map.keySet(); - assertEquals("[1, 2, 3, 4, 5]", keys.toString()); - map.put(6, null); - assertEquals("[2, 3, 4, 5, 6]", keys.toString()); - map.put(7, null); - assertEquals("[3, 4, 5, 6, 7]", keys.toString()); - map.put(8, null); - assertEquals("[4, 5, 6, 7, 8]", keys.toString()); - } - - @Test - public void givenTreeMap_whenOrdersEntriesNaturally_thenCorrect() { - TreeMap map = new TreeMap<>(); - map.put(3, "val"); - map.put(2, "val"); - map.put(1, "val"); - map.put(5, "val"); - map.put(4, "val"); - assertEquals("[1, 2, 3, 4, 5]", map.keySet().toString()); - } - - @Test - public void givenTreeMap_whenOrdersEntriesNaturally_thenCorrect2() { - TreeMap map = new TreeMap<>(); - map.put("c", "val"); - map.put("b", "val"); - map.put("a", "val"); - map.put("e", "val"); - map.put("d", "val"); - - assertEquals("[a, b, c, d, e]", map.keySet().toString()); - } - - @Test - public void givenTreeMap_whenOrdersEntriesByComparator_thenCorrect() { - TreeMap map = new TreeMap<>(Comparator.reverseOrder()); - map.put(3, "val"); - map.put(2, "val"); - map.put(1, "val"); - map.put(5, "val"); - map.put(4, "val"); - - assertEquals("[5, 4, 3, 2, 1]", map.keySet().toString()); - } - - @Test - public void givenTreeMap_whenPerformsQueries_thenCorrect() { - TreeMap map = new TreeMap<>(); - map.put(3, "val"); - map.put(2, "val"); - map.put(1, "val"); - map.put(5, "val"); - map.put(4, "val"); - - Integer highestKey = map.lastKey(); - Integer lowestKey = map.firstKey(); - Set keysLessThan3 = map.headMap(3).keySet(); - Set keysGreaterThanEqTo3 = map.tailMap(3).keySet(); - - assertEquals(new Integer(5), highestKey); - assertEquals(new Integer(1), lowestKey); - assertEquals("[1, 2]", keysLessThan3.toString()); - assertEquals("[3, 4, 5]", keysGreaterThanEqTo3.toString()); - } - -} diff --git a/java-collections-maps/src/test/java/com/baeldung/map/MapUtilUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/map/MapUtilUnitTest.java deleted file mode 100644 index f8e4c8fd8a..0000000000 --- a/java-collections-maps/src/test/java/com/baeldung/map/MapUtilUnitTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * - */ -package com.baeldung.map; - -import com.google.common.collect.HashBiMap; -import org.apache.commons.collections4.BidiMap; -import org.apache.commons.collections4.bidimap.DualHashBidiMap; -import org.junit.Test; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.stream.Collectors; - -import static org.junit.Assert.assertEquals; - -/** - * @author swpraman - * - */ -public class MapUtilUnitTest { - - - @Test - public void whenUsingImperativeWayForSingleKey_shouldReturnSingleKey() { - Map capitalCountryMap = new HashMap<>(); - capitalCountryMap.put("Tokyo", "Japan"); - capitalCountryMap.put("New Delhi", "India"); - assertEquals("New Delhi", MapUtil.getKey(capitalCountryMap, "India")); - } - - @Test - public void whenUsingImperativeWayForAllKeys_shouldReturnAllKeys() { - Map capitalCountryMap = new HashMap<>(); - capitalCountryMap.put("Tokyo", "Japan"); - capitalCountryMap.put("Berlin", "Germany"); - capitalCountryMap.put("Cape Town", "South Africa"); - capitalCountryMap.put("Pretoria", "South Africa"); - capitalCountryMap.put("Bloemfontein", "South Africa"); - - assertEquals(new HashSet(Arrays.asList( - new String[] {"Cape Town", "Pretoria", "Bloemfontein"})), - MapUtil.getKeys(capitalCountryMap, "South Africa")); - } - - @Test - public void whenUsingFunctionalWayForSingleKey_shouldReturnSingleKey() { - Map capitalCountryMap = new HashMap<>(); - capitalCountryMap.put("Tokyo", "Japan"); - capitalCountryMap.put("Berlin", "Germany"); - assertEquals("Berlin", MapUtil.keys(capitalCountryMap, "Germany").findFirst().get()); - } - - @Test - public void whenUsingFunctionalWayForAllKeys_shouldReturnAllKeys() { - Map capitalCountryMap = new HashMap<>(); - capitalCountryMap.put("Tokyo", "Japan"); - capitalCountryMap.put("Berlin", "Germany"); - capitalCountryMap.put("Cape Town", "South Africa"); - capitalCountryMap.put("Pretoria", "South Africa"); - capitalCountryMap.put("Bloemfontein", "South Africa"); - assertEquals(new HashSet(Arrays.asList( - new String[] {"Cape Town", "Pretoria", "Bloemfontein"})), - MapUtil.keys(capitalCountryMap, "South Africa").collect(Collectors.toSet())); - } - - @Test - public void whenUsingBidiMap_shouldReturnKey() { - BidiMap capitalCountryMap = new DualHashBidiMap(); - capitalCountryMap.put("Berlin", "Germany"); - capitalCountryMap.put("Cape Town", "South Africa"); - assertEquals("Berlin", capitalCountryMap.getKey("Germany")); - } - - @Test - public void whenUsingBidiMapAddDuplicateValue_shouldRemoveOldEntry() { - BidiMap capitalCountryMap = new DualHashBidiMap(); - capitalCountryMap.put("Berlin", "Germany"); - capitalCountryMap.put("Cape Town", "South Africa"); - capitalCountryMap.put("Pretoria", "South Africa"); - assertEquals("Pretoria", capitalCountryMap.getKey("South Africa")); - } - - @Test - public void whenUsingBiMap_shouldReturnKey() { - HashBiMap capitalCountryMap = HashBiMap.create(); - capitalCountryMap.put("Berlin", "Germany"); - capitalCountryMap.put("Cape Town", "South Africa"); - assertEquals("Berlin", capitalCountryMap.inverse().get("Germany")); - } - - @Test(expected=IllegalArgumentException.class) - public void whenUsingBiMapAddDuplicateValue_shouldThrowException() { - HashBiMap capitalCountryMap = HashBiMap.create(); - capitalCountryMap.put("Berlin", "Germany"); - capitalCountryMap.put("Cape Town", "South Africa"); - capitalCountryMap.put("Pretoria", "South Africa"); - assertEquals("Berlin", capitalCountryMap.inverse().get("Germany")); - } - -} diff --git a/java-collections-maps/src/test/java/com/baeldung/map/MultiValuedMapUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/map/MultiValuedMapUnitTest.java deleted file mode 100644 index 686c1cef87..0000000000 --- a/java-collections-maps/src/test/java/com/baeldung/map/MultiValuedMapUnitTest.java +++ /dev/null @@ -1,227 +0,0 @@ -package com.baeldung.map; - -import org.apache.commons.collections4.MultiMapUtils; -import org.apache.commons.collections4.MultiSet; -import org.apache.commons.collections4.MultiValuedMap; -import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; -import org.apache.commons.collections4.multimap.HashSetValuedHashMap; -import org.junit.Test; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - -public class MultiValuedMapUnitTest { - - @Test - public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutMethod_thenReturningAllValues() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - - map.put("fruits", "apple"); - map.put("fruits", "orange"); - - assertThat((Collection) map.get("fruits")).containsExactly("apple", "orange"); - - } - - @Test - public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutAllMethod_thenReturningAllValues() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - - map.putAll("vehicles", Arrays.asList("car", "bike")); - - assertThat((Collection) map.get("vehicles")).containsExactly("car", "bike"); - - } - - @Test - public void givenMultiValuesMap_whenGettingValueUsingGetMethod_thenReturningValue() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - - map.put("fruits", "apple"); - - assertThat((Collection) map.get("fruits")).containsExactly("apple"); - } - - @Test - public void givenMultiValuesMap_whenUsingEntriesMethod_thenReturningMappings() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("fruits", "apple"); - map.put("fruits", "orange"); - - Collection> entries = (Collection>) map.entries(); - - for(Map.Entry entry : entries) { - assertThat(entry.getKey()).contains("fruits"); - assertTrue(entry.getValue().equals("apple") || entry.getValue().equals("orange") ); - } - } - - @Test - public void givenMultiValuesMap_whenUsingKeysMethod_thenReturningAllKeys() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("fruits", "apple"); - map.put("fruits", "orange"); - map.put("vehicles", "car"); - map.put("vehicles", "bike"); - - MultiSet keys = map.keys(); - - assertThat((keys)).contains("fruits", "vehicles"); - - } - - @Test - public void givenMultiValuesMap_whenUsingKeySetMethod_thenReturningAllKeys() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("fruits", "apple"); - map.put("fruits", "orange"); - map.put("vehicles", "car"); - map.put("vehicles", "bike"); - - Set keys = map.keySet(); - - assertThat(keys).contains("fruits", "vehicles"); - - } - - @Test - public void givenMultiValuesMap_whenUsingValuesMethod_thenReturningAllValues() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - - map.put("fruits", "apple"); - map.put("fruits", "orange"); - map.put("vehicles", "car"); - map.put("vehicles", "bike"); - - assertThat(((Collection) map.values())).contains("apple", "orange", "car", "bike"); - } - - @Test - public void givenMultiValuesMap_whenUsingRemoveMethod_thenReturningUpdatedMap() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - - map.put("fruits", "apple"); - map.put("fruits", "orange"); - map.put("vehicles", "car"); - map.put("vehicles", "bike"); - assertThat(((Collection) map.values())).contains("apple", "orange", "car", "bike"); - - map.remove("fruits"); - - assertThat(((Collection) map.values())).contains("car", "bike"); - - } - - @Test - public void givenMultiValuesMap_whenUsingRemoveMappingMethod_thenReturningUpdatedMapAfterMappingRemoved() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - - map.put("fruits", "apple"); - map.put("fruits", "orange"); - map.put("vehicles", "car"); - map.put("vehicles", "bike"); - assertThat(((Collection) map.values())).contains("apple", "orange", "car", "bike"); - - map.removeMapping("fruits", "apple"); - - assertThat(((Collection) map.values())).contains("orange", "car", "bike"); - } - - @Test - public void givenMultiValuesMap_whenUsingClearMethod_thenReturningEmptyMap() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("fruits", "apple"); - map.put("fruits", "orange"); - map.put("vehicles", "car"); - map.put("vehicles", "bike"); - assertThat(((Collection) map.values())).contains("apple", "orange", "car", "bike"); - - map.clear(); - - assertTrue(map.isEmpty()); - } - - @Test - public void givenMultiValuesMap_whenUsingContainsKeyMethod_thenReturningTrue() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("fruits", "apple"); - map.put("fruits", "orange"); - map.put("vehicles", "car"); - map.put("vehicles", "bike"); - - assertTrue(map.containsKey("fruits")); - } - - @Test - public void givenMultiValuesMap_whenUsingContainsValueMethod_thenReturningTrue() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("fruits", "apple"); - map.put("fruits", "orange"); - map.put("vehicles", "car"); - map.put("vehicles", "bike"); - - assertTrue(map.containsValue("orange")); - } - - @Test - public void givenMultiValuesMap_whenUsingIsEmptyMethod_thenReturningFalse() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("fruits", "apple"); - map.put("fruits", "orange"); - map.put("vehicles", "car"); - map.put("vehicles", "bike"); - - assertFalse(map.isEmpty()); - } - - @Test - public void givenMultiValuesMap_whenUsingSizeMethod_thenReturningElementCount() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("fruits", "apple"); - map.put("fruits", "orange"); - map.put("vehicles", "car"); - map.put("vehicles", "bike"); - - assertEquals(4, map.size()); - } - - @Test - public void givenArrayListValuedHashMap_whenPuttingDoubleValues_thenReturningAllValues() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("fruits", "apple"); - map.put("fruits", "orange"); - map.put("fruits", "orange"); - - assertThat((Collection) map.get("fruits")).containsExactly("apple", "orange", "orange"); - } - - @Test - public void givenHashSetValuedHashMap_whenPuttingTwiceTheSame_thenReturningOneValue() { - MultiValuedMap map = new HashSetValuedHashMap<>(); - map.put("fruits", "apple"); - map.put("fruits", "apple"); - - assertThat((Collection) map.get("fruits")).containsExactly("apple"); - } - - @Test(expected = UnsupportedOperationException.class) - public void givenUnmodifiableMultiValuedMap_whenInserting_thenThrowingException() { - MultiValuedMap map = new ArrayListValuedHashMap<>(); - map.put("fruits", "apple"); - map.put("fruits", "orange"); - MultiValuedMap immutableMap = MultiMapUtils.unmodifiableMultiValuedMap(map); - - immutableMap.put("fruits", "banana"); - - } - - -} From cb7bd8d2f2d6e94ad5d8846886c041edbd8bbdcb Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Tue, 7 Apr 2020 14:50:03 +0530 Subject: [PATCH 105/187] JAVA-1188: Moved modules to core-java-modules --- .../core-java-collections-maps-2/README.md | 16 + .../core-java-collections-maps-2/pom.xml | 79 ++++ .../main/java/com/baeldung/map/Product.java | 133 +++++++ .../com/baeldung/map/convert/MapToString.java | 34 ++ .../com/baeldung/map/convert/StringToMap.java | 21 ++ .../baeldung/map/copyhashmap/CopyHashMap.java | 55 +++ .../map/initialize/MapInitializer.java | 80 +++++ .../baeldung/map/iteration/MapIteration.java | 74 ++++ .../java/com/baeldung/map/mapmax/MapMax.java | 92 +++++ .../com/baeldung/map/mergemaps/Employee.java | 60 ++++ .../com/baeldung/map/mergemaps/MergeMaps.java | 105 ++++++ .../map/primitives/PrimitiveMaps.java | 69 ++++ .../com/baeldung/map/sort/SortHashMap.java | 104 ++++++ .../com/baeldung/map/ProductUnitTest.java | 174 +++++++++ .../map/convert/MapToStringUnitTest.java | 48 +++ .../map/convert/StringToMapUnitTest.java | 23 ++ .../map/copyhashmap/CopyHashMapUnitTest.java | 76 ++++ .../baeldung/map/copyhashmap/Employee.java | 28 ++ .../initialize/MapInitializerUnitTest.java | 27 ++ .../baeldung/map/mapmax/MapMaxUnitTest.java | 58 +++ .../map/weakhashmap/WeakHashMapUnitTest.java | 72 ++++ .../core-java-collections-maps-3/README.md | 8 + .../core-java-collections-maps-3/pom.xml | 26 ++ .../compare/HashMapComparisonUnitTest.java | 225 ++++++++++++ .../TreeMapVsHashMapUnitTest.java | 58 +++ .../core-java-collections-maps/README.md | 16 + .../core-java-collections-maps/pom.xml | 35 ++ .../main/java/com/baeldung/map/MapUtil.java | 44 +++ .../src/main/java/com/baeldung/map/MyKey.java | 64 ++++ .../com/baeldung/map/MyLinkedHashMap.java | 23 ++ .../src/main/resources/logback.xml | 13 + .../baeldung/guava/GuavaBiMapUnitTest.java | 120 +++++++ .../baeldung/map/ImmutableMapUnitTest.java | 84 +++++ .../com/baeldung/map/KeyCheckUnitTest.java | 27 ++ .../map/MapMultipleValuesUnitTest.java | 119 +++++++ .../java/com/baeldung/map/MapUnitTest.java | 336 ++++++++++++++++++ .../com/baeldung/map/MapUtilUnitTest.java | 103 ++++++ .../baeldung/map/MultiValuedMapUnitTest.java | 227 ++++++++++++ core-java-modules/pom.xml | 3 + 39 files changed, 2959 insertions(+) create mode 100644 core-java-modules/core-java-collections-maps-2/README.md create mode 100644 core-java-modules/core-java-collections-maps-2/pom.xml create mode 100644 core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/Product.java create mode 100644 core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/convert/MapToString.java create mode 100644 core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/convert/StringToMap.java create mode 100644 core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/copyhashmap/CopyHashMap.java create mode 100644 core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/MapInitializer.java create mode 100644 core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java create mode 100644 core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java create mode 100644 core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/Employee.java create mode 100644 core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/MergeMaps.java create mode 100644 core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/primitives/PrimitiveMaps.java create mode 100644 core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/sort/SortHashMap.java create mode 100644 core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java create mode 100644 core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/convert/MapToStringUnitTest.java create mode 100644 core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/convert/StringToMapUnitTest.java create mode 100644 core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/CopyHashMapUnitTest.java create mode 100644 core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/Employee.java create mode 100644 core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/MapInitializerUnitTest.java create mode 100644 core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/mapmax/MapMaxUnitTest.java create mode 100644 core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/weakhashmap/WeakHashMapUnitTest.java create mode 100644 core-java-modules/core-java-collections-maps-3/README.md create mode 100644 core-java-modules/core-java-collections-maps-3/pom.xml create mode 100644 core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java create mode 100644 core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java create mode 100644 core-java-modules/core-java-collections-maps/README.md create mode 100644 core-java-modules/core-java-collections-maps/pom.xml create mode 100644 core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MapUtil.java create mode 100644 core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MyKey.java create mode 100644 core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MyLinkedHashMap.java create mode 100644 core-java-modules/core-java-collections-maps/src/main/resources/logback.xml create mode 100644 core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/guava/GuavaBiMapUnitTest.java create mode 100644 core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java create mode 100644 core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/KeyCheckUnitTest.java create mode 100644 core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapMultipleValuesUnitTest.java create mode 100644 core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapUnitTest.java create mode 100644 core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapUtilUnitTest.java create mode 100644 core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MultiValuedMapUnitTest.java diff --git a/core-java-modules/core-java-collections-maps-2/README.md b/core-java-modules/core-java-collections-maps-2/README.md new file mode 100644 index 0000000000..da9279b191 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/README.md @@ -0,0 +1,16 @@ +## Java Collections Cookbooks and Examples + +This module contains articles about Map data structures in Java. + +### Relevant Articles: +- [Map of Primitives in Java](https://www.baeldung.com/java-map-primitives) +- [Copying a HashMap in Java](https://www.baeldung.com/java-copy-hashmap) +- [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap) +- [Guide to WeakHashMap in Java](https://www.baeldung.com/java-weakhashmap) +- [Map to String Conversion in Java](https://www.baeldung.com/java-map-to-string-conversion) +- [Iterate over a Map in Java](https://www.baeldung.com/java-iterate-map) +- [Merging Two Maps with Java 8](https://www.baeldung.com/java-merge-maps) +- [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]](/core-java-collections-maps) [[next -->]](/core-java-collections-maps-3) diff --git a/core-java-modules/core-java-collections-maps-2/pom.xml b/core-java-modules/core-java-collections-maps-2/pom.xml new file mode 100644 index 0000000000..a08a4ac072 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/pom.xml @@ -0,0 +1,79 @@ + + + 4.0.0 + core-java-collections-maps-2 + 0.1.0-SNAPSHOT + core-java-collections-maps-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.eclipse.collections + eclipse-collections + ${eclipse-collections.version} + + + net.sf.trove4j + trove4j + ${trove4j.version} + + + it.unimi.dsi + fastutil + ${fastutil.version} + + + colt + colt + ${colt.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + one.util + streamex + ${streamex.version} + + + com.jayway.awaitility + awaitility + ${avaitility.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + 0.6.5 + 4.1 + 1.7.0 + 8.2.0 + 3.0.2 + 8.1.0 + 1.2.0 + 3.11.1 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/Product.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/Product.java new file mode 100644 index 0000000000..5559895730 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/Product.java @@ -0,0 +1,133 @@ +package com.baeldung.map; + +import java.util.*; + +public class Product { + + private String name; + private String description; + private List tags; + + public Product(String name, String description) { + this.name = name; + this.description = description; + this.tags = new ArrayList<>(); + } + + public String getName() { + return name; + } + + public String getDescription() { + return description; + } + + public List getTags() { + return tags; + } + + public Product addTagsOfOtherProdcut(Product product) { + this.tags.addAll(product.getTags()); + return this; + } + + @Override + public boolean equals(Object o) { + + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + Product product = (Product) o; + return Objects.equals(name, product.name) && + Objects.equals(description, product.description); + } + + @Override + public int hashCode() { + return Objects.hash(name, description); + } + + public static void forEach() { + + HashMap productsByName = new HashMap<>(); + productsByName.forEach( (key, product) + -> System.out.println("Key: " + key + " Product:" + product.getDescription()) + //do something with the key and value + ); + + //Prior to Java 8: + for(Map.Entry entry : productsByName.entrySet()) { + Product product = entry.getValue(); + String key = entry.getKey(); + //do something with the key and value + } + } + + public static void getOrDefault() { + + HashMap productsByName = new HashMap<>(); + Product chocolate = new Product("chocolate", "something sweet"); + Product defaultProduct = productsByName.getOrDefault("horse carriage", chocolate); + Product bike = productsByName.getOrDefault("E-Bike", chocolate); + + //Prior to Java 8: + Product bike2 = productsByName.containsKey("E-Bike") + ? productsByName.get("E-Bike") + : chocolate; + Product defaultProduct2 = productsByName.containsKey("horse carriage") + ? productsByName.get("horse carriage") + : chocolate; + } + + public static void putIfAbsent() { + + HashMap productsByName = new HashMap<>(); + Product chocolate = new Product("chocolate", "something sweet"); + productsByName.putIfAbsent("E-Bike", chocolate); + + //Prior to Java 8: + if(productsByName.containsKey("E-Bike")) { + productsByName.put("E-Bike", chocolate); + } + } + + public static void merge() { + + HashMap productsByName = new HashMap<>(); + Product eBike2 = new Product("E-Bike", "A bike with a battery"); + eBike2.getTags().add("sport"); + productsByName.merge("E-Bike", eBike2, Product::addTagsOfOtherProdcut); + + //Prior to Java 8: + if(productsByName.containsKey("E-Bike")) { + productsByName.get("E-Bike").addTagsOfOtherProdcut(eBike2); + } else { + productsByName.put("E-Bike", eBike2); + } + } + + public static void compute() { + + HashMap productsByName = new HashMap<>(); + Product eBike2 = new Product("E-Bike", "A bike with a battery"); + + productsByName.compute("E-Bike", (k,v) -> { + if(v != null) { + return v.addTagsOfOtherProdcut(eBike2); + } else { + return eBike2; + } + }); + + //Prior to Java 8: + if(productsByName.containsKey("E-Bike")) { + productsByName.get("E-Bike").addTagsOfOtherProdcut(eBike2); + } else { + productsByName.put("E-Bike", eBike2); + } + } +} diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/convert/MapToString.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/convert/MapToString.java new file mode 100644 index 0000000000..d13be924ff --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/convert/MapToString.java @@ -0,0 +1,34 @@ +package com.baeldung.map.convert; + +import com.google.common.base.Joiner; +import org.apache.commons.lang3.StringUtils; + +import java.util.Map; +import java.util.stream.Collectors; + +public class MapToString { + + public static String convertWithIteration(Map map) { + StringBuilder mapAsString = new StringBuilder("{"); + for (Integer key : map.keySet()) { + mapAsString.append(key + "=" + map.get(key) + ", "); + } + mapAsString.delete(mapAsString.length()-2, mapAsString.length()).append("}"); + return mapAsString.toString(); + } + + public static String convertWithStream(Map map) { + String mapAsString = map.keySet().stream() + .map(key -> key + "=" + map.get(key)) + .collect(Collectors.joining(", ", "{", "}")); + return mapAsString; + } + + public static String convertWithGuava(Map map) { + return Joiner.on(",").withKeyValueSeparator("=").join(map); + } + + public static String convertWithApache(Map map) { + return StringUtils.join(map); + } +} diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/convert/StringToMap.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/convert/StringToMap.java new file mode 100644 index 0000000000..416ba4dd9a --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/convert/StringToMap.java @@ -0,0 +1,21 @@ +package com.baeldung.map.convert; + +import com.google.common.base.Splitter; + +import java.util.Arrays; +import java.util.Map; +import java.util.stream.Collectors; + +public class StringToMap { + + public static Map convertWithStream(String mapAsString) { + Map map = Arrays.stream(mapAsString.split(",")) + .map(entry -> entry.split("=")) + .collect(Collectors.toMap(entry -> entry[0], entry -> entry[1])); + return map; + } + + public static Map convertWithGuava(String mapAsString) { + return Splitter.on(',').withKeyValueSeparator('=').split(mapAsString); + } +} diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/copyhashmap/CopyHashMap.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/copyhashmap/CopyHashMap.java new file mode 100644 index 0000000000..cb18f3aa11 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/copyhashmap/CopyHashMap.java @@ -0,0 +1,55 @@ +package com.baeldung.map.copyhashmap; + +import org.apache.commons.lang3.SerializationUtils; + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.stream.Collectors; + +public class CopyHashMap { + + public static HashMap copyUsingConstructor(HashMap originalMap) { + return new HashMap(originalMap); + } + + public static HashMap copyUsingClone(HashMap originalMap) { + return (HashMap) originalMap.clone(); + } + + public static HashMap copyUsingPut(HashMap originalMap) { + HashMap shallowCopy = new HashMap(); + Set> entries = originalMap.entrySet(); + for(Map.Entry mapEntry: entries) { + shallowCopy.put(mapEntry.getKey(), mapEntry.getValue()); + } + + return shallowCopy; + } + + public static HashMap copyUsingPutAll(HashMap originalMap) { + HashMap shallowCopy = new HashMap(); + shallowCopy.putAll(originalMap); + + return shallowCopy; + } + + public static HashMap copyUsingJava8Stream(HashMap originalMap) { + Set> entries = originalMap.entrySet(); + HashMap shallowCopy = (HashMap) entries + .stream() + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + + return shallowCopy; + } + + public static HashMap shallowCopy(HashMap originalMap) { + return (HashMap) originalMap.clone(); + } + + public static HashMap deepCopy(HashMap originalMap) { + return SerializationUtils.clone(originalMap); + } + +} diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/MapInitializer.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/MapInitializer.java new file mode 100644 index 0000000000..4d63abcfd0 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/initialize/MapInitializer.java @@ -0,0 +1,80 @@ +package com.baeldung.map.initialize; + +import java.util.AbstractMap; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class MapInitializer { + + public static Map articleMapOne; + static { + articleMapOne = new HashMap<>(); + articleMapOne.put("ar01", "Intro to Map"); + articleMapOne.put("ar02", "Some article"); + } + + public static Map createSingletonMap() { + Map passwordMap = Collections.singletonMap("username1", "password1"); + return passwordMap; + + } + + public Map createEmptyMap() { + Map emptyMap = Collections.emptyMap(); + return emptyMap; + } + + public Map createUsingDoubleBrace() { + Map doubleBraceMap = new HashMap() { + + /** + * + */ + private static final long serialVersionUID = 1L; + + { + put("key1", "value1"); + put("key2", "value2"); + } + }; + return doubleBraceMap; + } + + public Map createMapUsingStreamStringArray() { + Map map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, }) + .collect(Collectors.toMap(data -> data[0], data -> data[1])); + + return map; + } + + public Map createMapUsingStreamObjectArray() { + Map map = Stream.of(new Object[][] { { "data1", 1 }, { "data2", 2 }, }) + .collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1])); + + return map; + } + + public Map createMapUsingStreamSimpleEntry() { + Map map = Stream.of(new AbstractMap.SimpleEntry<>("idea", 1), new AbstractMap.SimpleEntry<>("mobile", 2)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + + return map; + } + + public Map createMapUsingStreamSimpleImmutableEntry() { + Map map = Stream.of(new AbstractMap.SimpleImmutableEntry<>("idea", 1), new AbstractMap.SimpleImmutableEntry<>("mobile", 2)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + + return map; + } + + public Map createImmutableMapWithStreams() { + Map map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, }) + .collect(Collectors.collectingAndThen(Collectors.toMap(data -> data[0], data -> data[1]), Collections:: unmodifiableMap)); + return map; + + } +} diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java new file mode 100644 index 0000000000..b0c32e1487 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/iteration/MapIteration.java @@ -0,0 +1,74 @@ +package com.baeldung.map.iteration; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +public class MapIteration { + + public static void main(String[] args) { + MapIteration mapIteration = new MapIteration(); + Map map = new HashMap<>(); + + map.put("One", 1); + map.put("Three", 3); + map.put("Two", 2); + + System.out.println("Iterating Keys of Map Using KeySet"); + mapIteration.iterateKeys(map); + + System.out.println("Iterating Map Using Entry Set"); + mapIteration.iterateUsingEntrySet(map); + + System.out.println("Iterating Using Iterator and Map Entry"); + mapIteration.iterateUsingIteratorAndEntry(map); + + System.out.println("Iterating Using KeySet and For Each"); + mapIteration.iterateUsingKeySetAndForeach(map); + + System.out.println("Iterating Map Using Lambda Expression"); + mapIteration.iterateUsingLambda(map); + + System.out.println("Iterating Using Stream API"); + mapIteration.iterateUsingStreamAPI(map); + } + + public void iterateUsingEntrySet(Map map) { + for (Map.Entry entry : map.entrySet()) { + System.out.println(entry.getKey() + ":" + entry.getValue()); + } + } + + public void iterateUsingLambda(Map map) { + map.forEach((k, v) -> System.out.println((k + ":" + v))); + } + + public void iterateUsingIteratorAndEntry(Map map) { + Iterator> iterator = map.entrySet() + .iterator(); + while (iterator.hasNext()) { + Map.Entry pair = iterator.next(); + System.out.println(pair.getKey() + ":" + pair.getValue()); + } + } + + public void iterateUsingKeySetAndForeach(Map map) { + for (String key : map.keySet()) { + System.out.println(key + ":" + map.get(key)); + } + } + + public void iterateUsingStreamAPI(Map map) { + map.entrySet() + .stream() + .forEach(e -> System.out.println(e.getKey() + ":" + e.getValue())); + } + + public void iterateKeys(Map map) { + for (String key : map.keySet()) { + System.out.println(key); + } + + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java new file mode 100644 index 0000000000..8c33c857ee --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mapmax/MapMax.java @@ -0,0 +1,92 @@ +package com.baeldung.map.mapmax; + +import java.util.*; +import java.util.Map.Entry; + +public class MapMax { + + public > V maxUsingIteration(Map map) { + + Map.Entry maxEntry = null; + + for (Map.Entry entry : map.entrySet()) { + + if (maxEntry == null || entry.getValue() + .compareTo(maxEntry.getValue()) > 0) { + maxEntry = entry; + } + } + + return maxEntry.getValue(); + } + + public > V maxUsingCollectionsMax(Map map) { + + Entry maxEntry = Collections.max(map.entrySet(), new Comparator>() { + public int compare(Entry e1, Entry e2) { + return e1.getValue() + .compareTo(e2.getValue()); + } + }); + + return maxEntry.getValue(); + } + + public > V maxUsingCollectionsMaxAndLambda(Map map) { + + Entry maxEntry = Collections.max(map.entrySet(), (Entry e1, Entry e2) -> e1.getValue() + .compareTo(e2.getValue())); + + return maxEntry.getValue(); + } + + public > V maxUsingCollectionsMaxAndMethodReference(Map map) { + + Entry maxEntry = Collections.max(map.entrySet(), Comparator.comparing(Map.Entry::getValue)); + + return maxEntry.getValue(); + } + + public > V maxUsingStreamAndLambda(Map map) { + + Optional> maxEntry = map.entrySet() + .stream() + .max((Entry e1, Entry e2) -> e1.getValue() + .compareTo(e2.getValue())); + + return maxEntry.get() + .getValue(); + } + + public > V maxUsingStreamAndMethodReference(Map map) { + + Optional> maxEntry = map.entrySet() + .stream() + .max(Comparator.comparing(Map.Entry::getValue)); + + return maxEntry.get() + .getValue(); + } + + public static void main(String[] args) { + + Map map = new HashMap(); + + map.put(1, 3); + map.put(2, 4); + map.put(3, 5); + map.put(4, 6); + map.put(5, 7); + + MapMax mapMax = new MapMax(); + + System.out.println(mapMax.maxUsingIteration(map)); + System.out.println(mapMax.maxUsingCollectionsMax(map)); + System.out.println(mapMax.maxUsingCollectionsMaxAndLambda(map)); + System.out.println(mapMax.maxUsingCollectionsMaxAndMethodReference(map)); + System.out.println(mapMax.maxUsingStreamAndLambda(map)); + System.out.println(mapMax.maxUsingStreamAndMethodReference(map)); + + } + +} diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/Employee.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/Employee.java new file mode 100644 index 0000000000..d7fb0d1a1d --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/Employee.java @@ -0,0 +1,60 @@ +package com.baeldung.map.mergemaps; + +public class Employee implements Comparable { + + private Long id; + private String name; + + public Employee(Long id, String name) { + this.name = name; + this.id = id; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Employee employee = (Employee) o; + + if (!id.equals(employee.id)) return false; + return name.equals(employee.name); + + } + + @Override + public int hashCode() { + int result = id.hashCode(); + result = 31 * result + name.hashCode(); + return result; + } + + @Override + public String toString() { + return "Employee{" + + "id=" + id + + ", name='" + name + '\'' + + '}'; + } + + @Override + public int compareTo(Employee employee) { + return (int)(this.id - employee.getId()); + } +} diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/MergeMaps.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/MergeMaps.java new file mode 100644 index 0000000000..4f187bad90 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/mergemaps/MergeMaps.java @@ -0,0 +1,105 @@ +package com.baeldung.map.mergemaps; + +import one.util.streamex.EntryStream; + +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class MergeMaps { + + private static Map map1 = new HashMap<>(); + private static Map map2 = new HashMap<>(); + + public static void main(String[] args) { + + initialize(); + + mergeFunction(); + + streamConcat(); + + streamOf(); + + streamEx(); + + streamMerge(); + } + + private static void streamMerge() { + + Map map3 = map2.entrySet() + .stream() + .collect( + Collectors.toMap( + Map.Entry::getKey, + Map.Entry::getValue, + (v1, v2) -> new Employee(v1.getId(), v2.getName()), + () -> new HashMap<>(map1) + ) + ); + + System.out.println(map3); + } + + private static void streamEx() { + Map map3 = EntryStream.of(map1) + .append(EntryStream.of(map2)) + .toMap((e1, e2) -> e1); + + System.out.println(map3); + + } + + private static void streamOf() { + Map map3 = Stream.of(map1, map2) + .flatMap(map -> map.entrySet().stream()) + .collect( + Collectors.toMap( + Map.Entry::getKey, + Map.Entry::getValue, + (v1, v2) -> new Employee(v1.getId(), v2.getName()) + ) + ); + + map3.entrySet().forEach(System.out::println); + } + + private static void streamConcat() { + Map result = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream()).collect(Collectors.toMap( + Map.Entry::getKey, + Map.Entry::getValue, + (value1, value2) -> new Employee(value2.getId(), value1.getName()) + )); + + result.entrySet().forEach(System.out::println); + } + + private static void mergeFunction() { + Map map3 = new HashMap<>(map1); + + map2.forEach( + (key, value) -> map3.merge(key, value, (v1, v2) -> + new Employee(v1.getId(), v2.getName())) + ); + + map3.entrySet().forEach(System.out::println); + } + + + private static void initialize() { + Employee employee1 = new Employee(1L, "Henry"); + map1.put(employee1.getName(), employee1); + Employee employee2 = new Employee(22L, "Annie"); + map1.put(employee2.getName(), employee2); + Employee employee3 = new Employee(8L, "John"); + map1.put(employee3.getName(), employee3); + + Employee employee4 = new Employee(2L, "George"); + map2.put(employee4.getName(), employee4); + Employee employee5 = new Employee(3L, "Henry"); + map2.put(employee5.getName(), employee5); + } + +} diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/primitives/PrimitiveMaps.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/primitives/PrimitiveMaps.java new file mode 100644 index 0000000000..30bec12ccc --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/primitives/PrimitiveMaps.java @@ -0,0 +1,69 @@ +package com.baeldung.map.primitives; + +import cern.colt.map.AbstractIntDoubleMap; +import cern.colt.map.OpenIntDoubleHashMap; +import gnu.trove.map.TDoubleIntMap; +import gnu.trove.map.hash.TDoubleIntHashMap; +import it.unimi.dsi.fastutil.ints.Int2BooleanMap; +import it.unimi.dsi.fastutil.ints.Int2BooleanOpenHashMap; +import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMap; +import it.unimi.dsi.fastutil.ints.Int2BooleanSortedMaps; +import org.eclipse.collections.api.map.primitive.ImmutableIntIntMap; +import org.eclipse.collections.api.map.primitive.MutableIntIntMap; +import org.eclipse.collections.api.map.primitive.MutableObjectDoubleMap; +import org.eclipse.collections.impl.factory.primitive.IntIntMaps; +import org.eclipse.collections.impl.factory.primitive.ObjectDoubleMaps; + +public class PrimitiveMaps { + + public static void main(String[] args) { + + eclipseCollectionsMap(); + troveMap(); + coltMap(); + fastutilMap(); + } + + private static void fastutilMap() { + Int2BooleanMap int2BooleanMap = new Int2BooleanOpenHashMap(); + int2BooleanMap.put(1, true); + int2BooleanMap.put(7, false); + int2BooleanMap.put(4, true); + + boolean value = int2BooleanMap.get(1); + + Int2BooleanSortedMap int2BooleanSorted = Int2BooleanSortedMaps.EMPTY_MAP; + } + + private static void coltMap() { + AbstractIntDoubleMap map = new OpenIntDoubleHashMap(); + map.put(1, 4.5); + double value = map.get(1); + } + + private static void eclipseCollectionsMap() { + MutableIntIntMap mutableIntIntMap = IntIntMaps.mutable.empty(); + mutableIntIntMap.addToValue(1, 1); + + ImmutableIntIntMap immutableIntIntMap = IntIntMaps.immutable.empty(); + + MutableObjectDoubleMap dObject = ObjectDoubleMaps.mutable.empty(); + dObject.addToValue("price", 150.5); + dObject.addToValue("quality", 4.4); + dObject.addToValue("stability", 0.8); + } + + private static void troveMap() { + double[] doubles = new double[] {1.2, 4.5, 0.3}; + int[] ints = new int[] {1, 4, 0}; + + TDoubleIntMap doubleIntMap = new TDoubleIntHashMap(doubles, ints); + + doubleIntMap.put(1.2, 22); + doubleIntMap.put(4.5, 16); + + doubleIntMap.adjustValue(1.2, 1); + doubleIntMap.adjustValue(4.5, 4); + doubleIntMap.adjustValue(0.3, 7); + } +} diff --git a/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/sort/SortHashMap.java b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/sort/SortHashMap.java new file mode 100644 index 0000000000..14610ffb00 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/main/java/com/baeldung/map/sort/SortHashMap.java @@ -0,0 +1,104 @@ +package com.baeldung.map.sort; + +import com.baeldung.map.mergemaps.Employee; +import com.google.common.base.Functions; +import com.google.common.collect.ImmutableSortedMap; +import com.google.common.collect.Ordering; + +import java.util.*; +import java.util.stream.Collectors; + +public class SortHashMap { + + private static Map map = new HashMap<>(); + + public static void main(String[] args) { + + initialize(); + + treeMapSortByKey(); + + arrayListSortByValue(); + arrayListSortByKey(); + + sortStream(); + + sortGuava(); + + addDuplicates(); + + treeSetByKey(); + treeSetByValue(); + + } + + private static void sortGuava() { + final Ordering naturalOrdering = + Ordering.natural().onResultOf(Functions.forMap(map, null)); + + System.out.println(ImmutableSortedMap.copyOf(map, naturalOrdering)); + } + + private static void sortStream() { + map.entrySet().stream() + .sorted(Map.Entry.comparingByKey().reversed()) + .forEach(System.out::println); + + Map result = map.entrySet().stream() + .sorted(Map.Entry.comparingByValue()) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, + (oldValue, newValue) -> oldValue, LinkedHashMap::new)); + + result.entrySet().forEach(System.out::println); + } + + private static void treeSetByValue() { + SortedSet values = new TreeSet<>(map.values()); + System.out.println(values); + } + + private static void treeSetByKey() { + SortedSet keysSet = new TreeSet<>(map.keySet()); + System.out.println(keysSet); + } + + private static void treeMapSortByKey() { + TreeMap sorted = new TreeMap<>(map); + sorted.putAll(map); + + sorted.entrySet().forEach(System.out::println); + + } + + private static void arrayListSortByValue() { + List employeeById = new ArrayList<>(map.values()); + + Collections.sort(employeeById); + + System.out.println(employeeById); + } + + private static void arrayListSortByKey() { + List employeeByKey = new ArrayList<>(map.keySet()); + Collections.sort(employeeByKey); + System.out.println(employeeByKey); + } + + private static void initialize() { + Employee employee1 = new Employee(1L, "Mher"); + map.put(employee1.getName(), employee1); + Employee employee2 = new Employee(22L, "Annie"); + map.put(employee2.getName(), employee2); + Employee employee3 = new Employee(8L, "John"); + map.put(employee3.getName(), employee3); + Employee employee4 = new Employee(2L, "George"); + map.put(employee4.getName(), employee4); + } + + private static void addDuplicates() { + Employee employee5 = new Employee(1L, "Mher"); + map.put(employee5.getName(), employee5); + Employee employee6 = new Employee(22L, "Annie"); + map.put(employee6.getName(), employee6); + } +} diff --git a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java new file mode 100644 index 0000000000..ba29d5c454 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/ProductUnitTest.java @@ -0,0 +1,174 @@ +package com.baeldung.map; + +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +import static org.junit.jupiter.api.Assertions.*; + +class ProductUnitTest { + + + @Test + public void getExistingValue() { + HashMap productsByName = new HashMap<>(); + + Product eBike = new Product("E-Bike", "A bike with a battery"); + Product roadBike = new Product("Road bike", "A bike for competition"); + + productsByName.put(eBike.getName(), eBike); + productsByName.put(roadBike.getName(), roadBike); + + Product nextPurchase = productsByName.get("E-Bike"); + + assertEquals("A bike with a battery", nextPurchase.getDescription()); + } + + @Test + public void getNonExistingValue() { + HashMap productsByName = new HashMap<>(); + + Product eBike = new Product("E-Bike", "A bike with a battery"); + Product roadBike = new Product("Road bike", "A bike for competition"); + + productsByName.put(eBike.getName(), eBike); + productsByName.put(roadBike.getName(), roadBike); + + Product nextPurchase = productsByName.get("Car"); + + assertNull(nextPurchase); + } + + @Test + public void getExistingValueAfterSameKeyInsertedTwice() { + HashMap productsByName = new HashMap<>(); + + Product eBike = new Product("E-Bike", "A bike with a battery"); + Product roadBike = new Product("Road bike", "A bike for competition"); + Product newEBike = new Product("E-Bike", "A bike with a better battery"); + + productsByName.put(eBike.getName(), eBike); + productsByName.put(roadBike.getName(), roadBike); + productsByName.put(newEBike.getName(), newEBike); + + Product nextPurchase = productsByName.get("E-Bike"); + + assertEquals("A bike with a better battery", nextPurchase.getDescription()); + } + + @Test + public void getExistingValueWithNullKey() { + HashMap productsByName = new HashMap<>(); + + Product defaultProduct = new Product("Chocolate", "At least buy chocolate"); + + productsByName.put(null, defaultProduct); + productsByName.put(defaultProduct.getName(), defaultProduct); + + Product nextPurchase = productsByName.get(null); + assertEquals("At least buy chocolate", nextPurchase.getDescription()); + + nextPurchase = productsByName.get("Chocolate"); + assertEquals("At least buy chocolate", nextPurchase.getDescription()); + } + + @Test + public void insertSameObjectWithDifferentKey() { + HashMap productsByName = new HashMap<>(); + + Product defaultProduct = new Product("Chocolate", "At least buy chocolate"); + + productsByName.put(null, defaultProduct); + productsByName.put(defaultProduct.getName(), defaultProduct); + + assertSame(productsByName.get(null), productsByName.get("Chocolate")); + } + + @Test + public void checkIfKeyExists() { + HashMap productsByName = new HashMap<>(); + + Product eBike = new Product("E-Bike", "A bike with a battery"); + + productsByName.put(eBike.getName(), eBike); + + assertTrue(productsByName.containsKey("E-Bike")); + } + + @Test + public void checkIfValueExists() { + HashMap productsByName = new HashMap<>(); + + Product eBike = new Product("E-Bike", "A bike with a battery"); + + productsByName.put(eBike.getName(), eBike); + + assertTrue(productsByName.containsValue(eBike)); + } + + @Test + public void removeExistingKey() { + HashMap productsByName = new HashMap<>(); + + Product eBike = new Product("E-Bike", "A bike with a battery"); + Product roadBike = new Product("Road bike", "A bike for competition"); + + productsByName.put(eBike.getName(), eBike); + productsByName.put(roadBike.getName(), roadBike); + + productsByName.remove("E-Bike"); + + assertNull(productsByName.get("E-Bike")); + } + + @Test + public void givenMutableKeyWhenKeyChangeThenValueNotFound() { + // Given + MutableKey key = new MutableKey("initial"); + + Map items = new HashMap<>(); + items.put(key, "success"); + + // When + key.setName("changed"); + + // Then + assertNull(items.get(key)); + } + + static class MutableKey { + private String name; + + public MutableKey(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MutableKey that = (MutableKey) o; + return Objects.equals(name, that.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + } + +} diff --git a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/convert/MapToStringUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/convert/MapToStringUnitTest.java new file mode 100644 index 0000000000..4517dea328 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/convert/MapToStringUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.map.convert; + +import org.apache.commons.collections4.MapUtils; +import org.junit.Assert; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; + +public class MapToStringUnitTest { + + private Map wordsByKey = new HashMap<>(); + + @BeforeEach + public void setup() { + wordsByKey.clear(); + wordsByKey.put(1, "one"); + wordsByKey.put(2, "two"); + wordsByKey.put(3, "three"); + wordsByKey.put(4, "four"); + } + + @Test + public void givenMap_WhenUsingIteration_ThenResultingMapIsCorrect() { + String mapAsString = MapToString.convertWithIteration(wordsByKey); + Assert.assertEquals("{1=one, 2=two, 3=three, 4=four}", mapAsString); + } + + @Test + public void givenMap_WhenUsingStream_ThenResultingMapIsCorrect() { + String mapAsString = MapToString.convertWithStream(wordsByKey); + Assert.assertEquals("{1=one, 2=two, 3=three, 4=four}", mapAsString); + } + + @Test + public void givenMap_WhenUsingGuava_ThenResultingMapIsCorrect() { + String mapAsString = MapToString.convertWithGuava(wordsByKey); + Assert.assertEquals("1=one,2=two,3=three,4=four", mapAsString); + } + + @Test + public void givenMap_WhenUsingApache_ThenResultingMapIsCorrect() { + String mapAsString = MapToString.convertWithApache(wordsByKey); + Assert.assertEquals("{1=one, 2=two, 3=three, 4=four}", mapAsString); + MapUtils.debugPrint(System.out, "Map as String", wordsByKey); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/convert/StringToMapUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/convert/StringToMapUnitTest.java new file mode 100644 index 0000000000..2f80b30871 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/convert/StringToMapUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.map.convert; + +import org.junit.Assert; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +public class StringToMapUnitTest { + + @Test + public void givenString_WhenUsingStream_ThenResultingStringIsCorrect() { + Map wordsByKey = StringToMap.convertWithStream("1=one,2=two,3=three,4=four"); + Assert.assertEquals(4, wordsByKey.size()); + Assert.assertEquals("one", wordsByKey.get("1")); + } + + @Test + void givenString_WhenUsingGuava_ThenResultingStringIsCorrect() { + Map wordsByKey = StringToMap.convertWithGuava("1=one,2=two,3=three,4=four"); + Assert.assertEquals(4, wordsByKey.size()); + Assert.assertEquals("one", wordsByKey.get("1")); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/CopyHashMapUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/CopyHashMapUnitTest.java new file mode 100644 index 0000000000..e2d5e327e1 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/CopyHashMapUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.map.copyhashmap; + +import com.google.common.collect.ImmutableMap; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CopyHashMapUnitTest { + + @Test + public void givenHashMap_whenShallowCopy_thenCopyisNotSameAsOriginal() { + + HashMap map = new HashMap<>(); + Employee emp1 = new Employee("John"); + Employee emp2 = new Employee("Norman"); + map.put("emp1",emp1); + map.put("emp2",emp2); + + HashMap shallowCopy = CopyHashMap.shallowCopy(map); + + assertThat(shallowCopy).isNotSameAs(map); + + } + + @Test + public void givenHashMap_whenShallowCopyModifyingOriginalObject_thenCopyShouldChange() { + + HashMap map = new HashMap<>(); + Employee emp1 = new Employee("John"); + Employee emp2 = new Employee("Norman"); + map.put("emp1",emp1); + map.put("emp2",emp2); + + HashMap shallowCopy = CopyHashMap.shallowCopy(map); + + emp1.setName("Johny"); + + assertThat(shallowCopy.get("emp1")).isEqualTo(map.get("emp1")); + + } + + @Test + public void givenHashMap_whenDeepCopyModifyingOriginalObject_thenCopyShouldNotChange() { + + HashMap map = new HashMap<>(); + Employee emp1 = new Employee("John"); + Employee emp2 = new Employee("Norman"); + map.put("emp1",emp1); + map.put("emp2",emp2); + HashMap deepCopy = CopyHashMap.deepCopy(map); + + emp1.setName("Johny"); + + assertThat(deepCopy.get("emp1")).isNotEqualTo(map.get("emp1")); + + } + + @Test + public void givenImmutableMap_whenCopyUsingGuava_thenCopyShouldNotChange() { + Employee emp1 = new Employee("John"); + Employee emp2 = new Employee("Norman"); + + Map map = ImmutableMap. builder() + .put("emp1",emp1) + .put("emp2",emp2) + .build(); + Map shallowCopy = ImmutableMap.copyOf(map); + + assertThat(shallowCopy).isSameAs(map); + + } + +} diff --git a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/Employee.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/Employee.java new file mode 100644 index 0000000000..5db55c26ea --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/copyhashmap/Employee.java @@ -0,0 +1,28 @@ +package com.baeldung.map.copyhashmap; + +import java.io.Serializable; + +public class Employee implements Serializable{ + + private String name; + + public Employee(String name) { + super(); + this.name = name; + } + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return this.name; + } + +} + + diff --git a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/MapInitializerUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/MapInitializerUnitTest.java new file mode 100644 index 0000000000..7c6dffe787 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/initialize/MapInitializerUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.map.initialize; + +import org.junit.Test; + +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +public class MapInitializerUnitTest { + + @Test + public void givenStaticMap_whenUpdated_thenCorrect() { + + MapInitializer.articleMapOne.put("NewArticle1", "Convert array to List"); + + assertEquals(MapInitializer.articleMapOne.get("NewArticle1"), "Convert array to List"); + + } + + @Test(expected=UnsupportedOperationException.class) + public void givenSingleTonMap_whenEntriesAdded_throwsException() { + + Map map = MapInitializer.createSingletonMap(); + map.put("username2", "password2"); + } + +} diff --git a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/mapmax/MapMaxUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/mapmax/MapMaxUnitTest.java new file mode 100644 index 0000000000..30b945bfc8 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/mapmax/MapMaxUnitTest.java @@ -0,0 +1,58 @@ +package com.baeldung.map.mapmax; + + +import org.junit.Before; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +public class MapMaxUnitTest { + + Map map = null; + MapMax mapMax = null; + + + @Before + public void setupTestData() { + map = new HashMap(); + map.put(23, 12); + map.put(46, 24); + map.put(27, 38); + mapMax = new MapMax(); + } + + @Test + public void givenMap_whenIterated_thenReturnMaxValue() { + assertEquals(new Integer(38), mapMax.maxUsingIteration(map)); + } + + @Test + public void givenMap_whenUsingCollectionsMax_thenReturnMaxValue() { + assertEquals(new Integer(38), mapMax.maxUsingCollectionsMax(map)); + } + + @Test + public void givenMap_whenUsingCollectionsMaxAndLambda_thenReturnMaxValue() { + assertEquals(new Integer(38), mapMax.maxUsingCollectionsMaxAndLambda(map)); + } + + @Test + public void givenMap_whenUsingCollectionsMaxAndMethodReference_thenReturnMaxValue() { + assertEquals(new Integer(38), mapMax.maxUsingCollectionsMaxAndMethodReference(map)); + } + + @Test + public void givenMap_whenUsingStreamAndLambda_thenReturnMaxValue() { + assertEquals(new Integer(38), mapMax.maxUsingStreamAndLambda(map)); + } + + @Test + public void givenMap_whenUsingStreamAndMethodReference_thenReturnMaxValue() { + assertEquals(new Integer(38), mapMax.maxUsingStreamAndMethodReference (map)); + } + + +} diff --git a/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/weakhashmap/WeakHashMapUnitTest.java b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/weakhashmap/WeakHashMapUnitTest.java new file mode 100644 index 0000000000..293f24c378 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-2/src/test/java/com/baeldung/map/weakhashmap/WeakHashMapUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.map.weakhashmap; + + +import org.junit.Test; + +import java.util.WeakHashMap; +import java.util.concurrent.TimeUnit; + +import static com.jayway.awaitility.Awaitility.await; +import static org.junit.Assert.assertTrue; + +public class WeakHashMapUnitTest { + + @Test + public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObject() { + //given + WeakHashMap map = new WeakHashMap<>(); + BigImage bigImage = new BigImage("image_id"); + UniqueImageName imageName = new UniqueImageName("name_of_big_image"); + + map.put(imageName, bigImage); + assertTrue(map.containsKey(imageName)); + + //when big image key is not reference anywhere + imageName = null; + System.gc(); + + //then GC will finally reclaim that object + await().atMost(10, TimeUnit.SECONDS).until(map::isEmpty); + } + + @Test + public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObjectButLeaveReferencedObject() { + //given + WeakHashMap map = new WeakHashMap<>(); + BigImage bigImageFirst = new BigImage("foo"); + UniqueImageName imageNameFirst = new UniqueImageName("name_of_big_image"); + + BigImage bigImageSecond = new BigImage("foo_2"); + UniqueImageName imageNameSecond = new UniqueImageName("name_of_big_image_2"); + + map.put(imageNameFirst, bigImageFirst); + map.put(imageNameSecond, bigImageSecond); + assertTrue(map.containsKey(imageNameFirst)); + assertTrue(map.containsKey(imageNameSecond)); + + //when + imageNameFirst = null; + System.gc(); + + //then + await().atMost(10, TimeUnit.SECONDS).until(() -> map.size() == 1); + await().atMost(10, TimeUnit.SECONDS).until(() -> map.containsKey(imageNameSecond)); + } + + + class BigImage { + public final String imageId; + + BigImage(String imageId) { + this.imageId = imageId; + } + } + + class UniqueImageName { + public final String imageName; + + UniqueImageName(String imageName) { + this.imageName = imageName; + } + } +} diff --git a/core-java-modules/core-java-collections-maps-3/README.md b/core-java-modules/core-java-collections-maps-3/README.md new file mode 100644 index 0000000000..142aa34800 --- /dev/null +++ b/core-java-modules/core-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]](/core-java-collections-maps-2) diff --git a/core-java-modules/core-java-collections-maps-3/pom.xml b/core-java-modules/core-java-collections-maps-3/pom.xml new file mode 100644 index 0000000000..95414c12c2 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-3/pom.xml @@ -0,0 +1,26 @@ + + + 4.0.0 + core-java-collections-maps-3 + 0.1.0-SNAPSHOT + core-java-collections-maps-3 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + + + + + + + \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java b/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java new file mode 100644 index 0000000000..0edd0cd87b --- /dev/null +++ b/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/compare/HashMapComparisonUnitTest.java @@ -0,0 +1,225 @@ +package com.baeldung.map.compare; + +import com.google.common.base.Equivalence; +import com.google.common.collect.MapDifference; +import com.google.common.collect.MapDifference.ValueDifference; +import com.google.common.collect.Maps; +import org.junit.Before; +import org.junit.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.collection.IsMapContaining.hasEntry; +import static org.hamcrest.collection.IsMapContaining.hasKey; +import static org.junit.Assert.*; + +public class HashMapComparisonUnitTest { + + Map asiaCapital1; + Map asiaCapital2; + Map asiaCapital3; + + Map asiaCity1; + Map asiaCity2; + Map asiaCity3; + + @Before + public void setup(){ + asiaCapital1 = new HashMap(); + asiaCapital1.put("Japan", "Tokyo"); + asiaCapital1.put("South Korea", "Seoul"); + + asiaCapital2 = new HashMap(); + asiaCapital2.put("South Korea", "Seoul"); + asiaCapital2.put("Japan", "Tokyo"); + + asiaCapital3 = new HashMap(); + asiaCapital3.put("Japan", "Tokyo"); + asiaCapital3.put("China", "Beijing"); + + asiaCity1 = new HashMap(); + asiaCity1.put("Japan", new String[] { "Tokyo", "Osaka" }); + asiaCity1.put("South Korea", new String[] { "Seoul", "Busan" }); + + asiaCity2 = new HashMap(); + asiaCity2.put("South Korea", new String[] { "Seoul", "Busan" }); + asiaCity2.put("Japan", new String[] { "Tokyo", "Osaka" }); + + asiaCity3 = new HashMap(); + asiaCity3.put("Japan", new String[] { "Tokyo", "Osaka" }); + asiaCity3.put("China", new String[] { "Beijing", "Hong Kong" }); + } + + @Test + public void whenCompareTwoHashMapsUsingEquals_thenSuccess() { + assertTrue(asiaCapital1.equals(asiaCapital2)); + assertFalse(asiaCapital1.equals(asiaCapital3)); + } + + @Test + public void whenCompareTwoHashMapsWithArrayValuesUsingEquals_thenFail() { + assertFalse(asiaCity1.equals(asiaCity2)); + } + + @Test + public void whenCompareTwoHashMapsUsingStreamAPI_thenSuccess() { + assertTrue(areEqual(asiaCapital1, asiaCapital2)); + assertFalse(areEqual(asiaCapital1, asiaCapital3)); + } + + @Test + public void whenCompareTwoHashMapsWithArrayValuesUsingStreamAPI_thenSuccess() { + assertTrue(areEqualWithArrayValue(asiaCity1, asiaCity2)); + assertFalse(areEqualWithArrayValue(asiaCity1, asiaCity3)); + } + + @Test + public void whenCompareTwoHashMapKeys_thenSuccess() { + assertTrue(asiaCapital1.keySet().equals(asiaCapital2.keySet())); + assertFalse(asiaCapital1.keySet().equals(asiaCapital3.keySet())); + } + + @Test + public void whenCompareTwoHashMapKeyValuesUsingStreamAPI_thenSuccess() { + Map asiaCapital3 = new HashMap(); + asiaCapital3.put("Japan", "Tokyo"); + asiaCapital3.put("South Korea", "Seoul"); + asiaCapital3.put("China", "Beijing"); + + Map asiaCapital4 = new HashMap(); + asiaCapital4.put("South Korea", "Seoul"); + asiaCapital4.put("Japan", "Osaka"); + asiaCapital4.put("China", "Beijing"); + + Map result = areEqualKeyValues(asiaCapital3, asiaCapital4); + + assertEquals(3, result.size()); + assertThat(result, hasEntry("Japan", false)); + assertThat(result, hasEntry("South Korea", true)); + assertThat(result, hasEntry("China", true)); + } + + @Test + public void givenDifferentMaps_whenGetDiffUsingGuava_thenSuccess() { + Map asia1 = new HashMap(); + asia1.put("Japan", "Tokyo"); + asia1.put("South Korea", "Seoul"); + asia1.put("India", "New Delhi"); + + Map asia2 = new HashMap(); + asia2.put("Japan", "Tokyo"); + asia2.put("China", "Beijing"); + asia2.put("India", "Delhi"); + + MapDifference diff = Maps.difference(asia1, asia2); + Map> entriesDiffering = diff.entriesDiffering(); + + assertFalse(diff.areEqual()); + assertEquals(1, entriesDiffering.size()); + assertThat(entriesDiffering, hasKey("India")); + assertEquals("New Delhi", entriesDiffering.get("India").leftValue()); + assertEquals("Delhi", entriesDiffering.get("India").rightValue()); + } + + @Test + public void givenDifferentMaps_whenGetEntriesOnOneSideUsingGuava_thenSuccess() { + Map asia1 = new HashMap(); + asia1.put("Japan", "Tokyo"); + asia1.put("South Korea", "Seoul"); + asia1.put("India", "New Delhi"); + + Map asia2 = new HashMap(); + asia2.put("Japan", "Tokyo"); + asia2.put("China", "Beijing"); + asia2.put("India", "Delhi"); + + MapDifference diff = Maps.difference(asia1, asia2); + Map entriesOnlyOnRight = diff.entriesOnlyOnRight(); + Map entriesOnlyOnLeft = diff.entriesOnlyOnLeft(); + + assertEquals(1, entriesOnlyOnRight.size()); + assertThat(entriesOnlyOnRight, hasEntry("China", "Beijing")); + assertEquals(1, entriesOnlyOnLeft.size()); + assertThat(entriesOnlyOnLeft, hasEntry("South Korea", "Seoul")); + } + + @Test + public void givenDifferentMaps_whenGetCommonEntriesUsingGuava_thenSuccess() { + Map asia1 = new HashMap(); + asia1.put("Japan", "Tokyo"); + asia1.put("South Korea", "Seoul"); + asia1.put("India", "New Delhi"); + + Map asia2 = new HashMap(); + asia2.put("Japan", "Tokyo"); + asia2.put("China", "Beijing"); + asia2.put("India", "Delhi"); + + MapDifference diff = Maps.difference(asia1, asia2); + Map entriesInCommon = diff.entriesInCommon(); + + assertEquals(1, entriesInCommon.size()); + assertThat(entriesInCommon, hasEntry("Japan", "Tokyo")); + } + + @Test + public void givenSimilarMapsWithArrayValue_whenCompareUsingGuava_thenFail() { + MapDifference diff = Maps.difference(asiaCity1, asiaCity2); + assertFalse(diff.areEqual()); + } + + @Test + public void givenSimilarMapsWithArrayValue_whenCompareUsingGuavaEquivalence_thenSuccess() { + Equivalence eq = new Equivalence() { + @Override + protected boolean doEquivalent(String[] a, String[] b) { + return Arrays.equals(a, b); + } + + @Override + protected int doHash(String[] value) { + return value.hashCode(); + } + }; + + MapDifference diff = Maps.difference(asiaCity1, asiaCity2, eq); + assertTrue(diff.areEqual()); + + diff = Maps.difference(asiaCity1, asiaCity3, eq); + assertFalse(diff.areEqual()); + } + + // =========================================================================== + + private boolean areEqual(Map first, Map second) { + if (first.size() != second.size()) { + return false; + } + + return first.entrySet() + .stream() + .allMatch(e -> e.getValue() + .equals(second.get(e.getKey()))); + } + + private boolean areEqualWithArrayValue(Map first, Map second) { + if (first.size() != second.size()) { + return false; + } + + return first.entrySet() + .stream() + .allMatch(e -> Arrays.equals(e.getValue(), second.get(e.getKey()))); + } + + private Map areEqualKeyValues(Map first, Map second) { + return first.entrySet() + .stream() + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().equals(second.get(e.getKey())))); + } + +} diff --git a/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java b/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java new file mode 100644 index 0000000000..1057e3b9f0 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/treemaphashmap/TreeMapVsHashMapUnitTest.java @@ -0,0 +1,58 @@ +package com.baeldung.map.treemaphashmap; + +import org.hamcrest.Matchers; +import org.junit.Assert; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; + +public class TreeMapVsHashMapUnitTest { + + @Test + public void whenInsertObjectsTreeMap_thenNaturalOrder() { + Map treemap = new TreeMap<>(); + treemap.put(3, "TreeMap"); + treemap.put(2, "vs"); + treemap.put(1, "HashMap"); + Assert.assertThat(treemap.keySet(), Matchers.contains(1, 2, 3)); + } + + @Test(expected = NullPointerException.class) + public void whenInsertNullInTreeMap_thenException() { + Map treemap = new TreeMap<>(); + treemap.put(null, "NullPointerException"); + } + + @Test + public void whenInsertObjectsHashMap_thenRandomOrder() { + Map hashmap = new HashMap<>(); + hashmap.put(3, "TreeMap"); + hashmap.put(2, "vs"); + hashmap.put(1, "HashMap"); + Assert.assertThat(hashmap.keySet(), Matchers.containsInAnyOrder(1, 2, 3)); + } + + @Test + public void whenInsertNullInHashMap_thenInsertsNull() { + Map hashmap = new HashMap<>(); + hashmap.put(null, null); + Assert.assertNull(hashmap.get(null)); + } + + @Test + public void givenHashMapAndTreeMap_whenputDuplicates_thenOnlyUnique() { + Map treeMap = new HashMap<>(); + treeMap.put(1, "Baeldung"); + treeMap.put(1, "Baeldung"); + + Assert.assertTrue(treeMap.size() == 1); + + Map treeMap2 = new TreeMap<>(); + treeMap2.put(1, "Baeldung"); + treeMap2.put(1, "Baeldung"); + + Assert.assertTrue(treeMap2.size() == 1); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps/README.md b/core-java-modules/core-java-collections-maps/README.md new file mode 100644 index 0000000000..1323fb97cd --- /dev/null +++ b/core-java-modules/core-java-collections-maps/README.md @@ -0,0 +1,16 @@ +## Java Collections Cookbooks and Examples + +This module contains articles about Map data structures in Java. + +### Relevant Articles: +- [Guide to the Guava BiMap](https://www.baeldung.com/guava-bimap) +- [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap) +- [A Guide to LinkedHashMap in Java](https://www.baeldung.com/java-linked-hashmap) +- [A Guide to TreeMap in Java](https://www.baeldung.com/java-treemap) +- [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) +- [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 -->]](/core-java-collections-maps-2) diff --git a/core-java-modules/core-java-collections-maps/pom.xml b/core-java-modules/core-java-collections-maps/pom.xml new file mode 100644 index 0000000000..c0dd705c1c --- /dev/null +++ b/core-java-modules/core-java-collections-maps/pom.xml @@ -0,0 +1,35 @@ + + + 4.0.0 + core-java-collections-maps + 0.1.0-SNAPSHOT + core-java-collections-maps + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + 4.1 + 3.6.1 + + diff --git a/core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MapUtil.java b/core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MapUtil.java new file mode 100644 index 0000000000..91b7197a92 --- /dev/null +++ b/core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MapUtil.java @@ -0,0 +1,44 @@ +/** + * + */ +package com.baeldung.map; + +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.stream.Stream; + +/** + * @author swpraman + * + */ +public class MapUtil { + + public static Stream keys(Map map, V value) { + return map.entrySet() + .stream() + .filter(entry -> value.equals(entry.getValue())) + .map(Map.Entry::getKey); + } + + public static Set getKeys(Map map, V value) { + Set keys = new HashSet<>(); + for (Entry entry : map.entrySet()) { + if (entry.getValue().equals(value)) { + keys.add(entry.getKey()); + } + } + return keys; + } + + public static K getKey(Map map, V value) { + for (Entry entry : map.entrySet()) { + if (entry.getValue().equals(value)) { + return entry.getKey(); + } + } + return null; + } + +} diff --git a/core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MyKey.java b/core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MyKey.java new file mode 100644 index 0000000000..9993d7862c --- /dev/null +++ b/core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MyKey.java @@ -0,0 +1,64 @@ +package com.baeldung.map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MyKey { + private static final Logger LOG = LoggerFactory.getLogger(MyKey.class); + + private String name; + private int id; + + public MyKey(int id, String name) { + this.id = id; + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + @Override + public int hashCode() { + LOG.debug("Calling hashCode()"); + return id; + } + + @Override + public String toString() { + return "MyKey [name=" + name + ", id=" + id + "]"; + } + + @Override + public boolean equals(Object obj) { + LOG.debug("Calling equals() for key: " + obj); + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + MyKey other = (MyKey) obj; + if (id != other.id) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + +} diff --git a/core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MyLinkedHashMap.java b/core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MyLinkedHashMap.java new file mode 100644 index 0000000000..b687e57d85 --- /dev/null +++ b/core-java-modules/core-java-collections-maps/src/main/java/com/baeldung/map/MyLinkedHashMap.java @@ -0,0 +1,23 @@ +package com.baeldung.map; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class MyLinkedHashMap extends LinkedHashMap { + + /** + * + */ + private static final long serialVersionUID = 1L; + private static final int MAX_ENTRIES = 5; + + public MyLinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) { + super(initialCapacity, loadFactor, accessOrder); + } + + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > MAX_ENTRIES; + } + +} diff --git a/core-java-modules/core-java-collections-maps/src/main/resources/logback.xml b/core-java-modules/core-java-collections-maps/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/core-java-modules/core-java-collections-maps/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/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/guava/GuavaBiMapUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/guava/GuavaBiMapUnitTest.java new file mode 100644 index 0000000000..b44d2db1aa --- /dev/null +++ b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/guava/GuavaBiMapUnitTest.java @@ -0,0 +1,120 @@ +package com.baeldung.guava; + +import static org.junit.Assert.*; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; +import com.google.common.collect.BiMap; +import com.google.common.collect.EnumHashBiMap; +import com.google.common.collect.HashBiMap; +import com.google.common.collect.ImmutableBiMap; + +public class GuavaBiMapUnitTest { + @Test + public void whenQueryByValue_returnsKey() { + final BiMap capitalCountryBiMap = HashBiMap.create(); + capitalCountryBiMap.put("New Delhi", "India"); + capitalCountryBiMap.put("Washingon, D.C.", "USA"); + capitalCountryBiMap.put("Moscow", "Russia"); + + final String countryCapitalName = capitalCountryBiMap.inverse().get("India"); + + assertEquals("New Delhi", countryCapitalName); + } + + @Test + public void whenCreateBiMapFromExistingMap_returnsKey() { + final Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("New Delhi", "India"); + capitalCountryMap.put("Washingon, D.C.", "USA"); + capitalCountryMap.put("Moscow", "Russia"); + final BiMap capitalCountryBiMap = HashBiMap.create(capitalCountryMap); + + final String countryCapitalName = capitalCountryBiMap.inverse().get("India"); + + assertEquals("New Delhi", countryCapitalName); + } + + @Test + public void whenQueryByKey_returnsValue() { + final BiMap capitalCountryBiMap = HashBiMap.create(); + + capitalCountryBiMap.put("New Delhi", "India"); + capitalCountryBiMap.put("Washingon, D.C.", "USA"); + capitalCountryBiMap.put("Moscow", "Russia"); + + assertEquals("USA", capitalCountryBiMap.get("Washingon, D.C.")); + } + + @Test(expected = IllegalArgumentException.class) + public void whenSameValueIsPresent_throwsException() { + final BiMap capitalCountryBiMap = HashBiMap.create(); + + capitalCountryBiMap.put("New Delhi", "India"); + capitalCountryBiMap.put("Washingon, D.C.", "USA"); + capitalCountryBiMap.put("Moscow", "Russia"); + capitalCountryBiMap.put("Trump", "USA"); + } + + @Test + public void givenSameValueIsPresent_whenForcePut_completesSuccessfully() { + final BiMap capitalCountryBiMap = HashBiMap.create(); + + capitalCountryBiMap.put("New Delhi", "India"); + capitalCountryBiMap.put("Washingon, D.C.", "USA"); + capitalCountryBiMap.put("Moscow", "Russia"); + capitalCountryBiMap.forcePut("Trump", "USA"); + + assertEquals("USA", capitalCountryBiMap.get("Trump")); + assertEquals("Trump", capitalCountryBiMap.inverse().get("USA")); + } + + @Test + public void whenSameKeyIsPresent_replacesAlreadyPresent() { + final BiMap capitalCountryBiMap = HashBiMap.create(); + + capitalCountryBiMap.put("New Delhi", "India"); + capitalCountryBiMap.put("Washingon, D.C.", "USA"); + capitalCountryBiMap.put("Moscow", "Russia"); + capitalCountryBiMap.put("Washingon, D.C.", "HongKong"); + + assertEquals("HongKong", capitalCountryBiMap.get("Washingon, D.C.")); + } + + @Test + public void whenUsingImmutableBiMap_allowsPutSuccessfully() { + final BiMap capitalCountryBiMap = new ImmutableBiMap.Builder().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build(); + + assertEquals("USA", capitalCountryBiMap.get("Washingon, D.C.")); + } + + @Test(expected = UnsupportedOperationException.class) + public void whenUsingImmutableBiMap_doesntAllowRemove() { + final BiMap capitalCountryBiMap = new ImmutableBiMap.Builder().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build(); + + capitalCountryBiMap.remove("New Delhi"); + } + + @Test(expected = UnsupportedOperationException.class) + public void whenUsingImmutableBiMap_doesntAllowPut() { + final BiMap capitalCountryBiMap = new ImmutableBiMap.Builder().put("New Delhi", "India").put("Washingon, D.C.", "USA").put("Moscow", "Russia").build(); + + capitalCountryBiMap.put("New York", "USA"); + } + + private enum Operation { + ADD, SUBTRACT, MULTIPLY, DIVIDE + } + + @Test + public void whenUsingEnumAsKeyInMap_replacesAlreadyPresent() { + final BiMap operationStringBiMap = EnumHashBiMap.create(Operation.class); + + operationStringBiMap.put(Operation.ADD, "Add"); + operationStringBiMap.put(Operation.SUBTRACT, "Subtract"); + operationStringBiMap.put(Operation.MULTIPLY, "Multiply"); + operationStringBiMap.put(Operation.DIVIDE, "Divide"); + + assertEquals("Divide", operationStringBiMap.get(Operation.DIVIDE)); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java new file mode 100644 index 0000000000..d308aac7eb --- /dev/null +++ b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java @@ -0,0 +1,84 @@ +package com.baeldung.map; + +import com.google.common.collect.ImmutableMap; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + + +public class ImmutableMapUnitTest { + + @Test + public void whenCollectionsUnModifiableMapMethod_thenOriginalCollectionChangesReflectInUnmodifiableMap() { + + Map mutableMap = new HashMap<>(); + mutableMap.put("USA", "North America"); + + Map unmodifiableMap = Collections.unmodifiableMap(mutableMap); + assertThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put("Canada", "North America")); + + mutableMap.remove("USA"); + assertFalse(unmodifiableMap.containsKey("USA")); + + mutableMap.put("Mexico", "North America"); + assertTrue(unmodifiableMap.containsKey("Mexico")); + } + + @Test + @SuppressWarnings("deprecation") + public void whenGuavaImmutableMapFromCopyOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() { + + Map mutableMap = new HashMap<>(); + mutableMap.put("USA", "North America"); + + ImmutableMap immutableMap = ImmutableMap.copyOf(mutableMap); + assertTrue(immutableMap.containsKey("USA")); + + assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America")); + + mutableMap.remove("USA"); + assertTrue(immutableMap.containsKey("USA")); + + mutableMap.put("Mexico", "North America"); + assertFalse(immutableMap.containsKey("Mexico")); + } + + @Test + @SuppressWarnings("deprecation") + public void whenGuavaImmutableMapFromBuilderMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() { + + Map mutableMap = new HashMap<>(); + mutableMap.put("USA", "North America"); + + ImmutableMap immutableMap = ImmutableMap.builder() + .putAll(mutableMap) + .put("Costa Rica", "North America") + .build(); + assertTrue(immutableMap.containsKey("USA")); + assertTrue(immutableMap.containsKey("Costa Rica")); + + assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America")); + + mutableMap.remove("USA"); + assertTrue(immutableMap.containsKey("USA")); + + mutableMap.put("Mexico", "North America"); + assertFalse(immutableMap.containsKey("Mexico")); + } + + @Test + @SuppressWarnings("deprecation") + public void whenGuavaImmutableMapFromOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() { + + ImmutableMap immutableMap = ImmutableMap.of("USA", "North America", "Costa Rica", "North America"); + assertTrue(immutableMap.containsKey("USA")); + assertTrue(immutableMap.containsKey("Costa Rica")); + + assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America")); + } + +} diff --git a/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/KeyCheckUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/KeyCheckUnitTest.java new file mode 100644 index 0000000000..dbad2e5b5e --- /dev/null +++ b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/KeyCheckUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.map; + +import org.junit.Test; + +import java.util.Collections; +import java.util.Map; + +import static org.junit.Assert.*; + +public class KeyCheckUnitTest { + + @Test + public void whenKeyIsPresent_thenContainsKeyReturnsTrue() { + Map map = Collections.singletonMap("key", "value"); + + assertTrue(map.containsKey("key")); + assertFalse(map.containsKey("missing")); + } + + @Test + public void whenKeyHasNullValue_thenGetStillWorks() { + Map map = Collections.singletonMap("nothing", null); + + assertTrue(map.containsKey("nothing")); + assertNull(map.get("nothing")); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapMultipleValuesUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapMultipleValuesUnitTest.java new file mode 100644 index 0000000000..721b48ea7b --- /dev/null +++ b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapMultipleValuesUnitTest.java @@ -0,0 +1,119 @@ +package com.baeldung.map; + +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.LinkedHashMultimap; +import com.google.common.collect.Multimap; +import com.google.common.collect.TreeMultimap; +import org.apache.commons.collections4.MultiMap; +import org.apache.commons.collections4.MultiMapUtils; +import org.apache.commons.collections4.MultiValuedMap; +import org.apache.commons.collections4.map.MultiValueMap; +import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; +import org.apache.commons.collections4.multimap.HashSetValuedHashMap; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.*; + +import static org.assertj.core.api.Assertions.assertThat; + +public class MapMultipleValuesUnitTest { + private static final Logger LOG = LoggerFactory.getLogger(MapMultipleValuesUnitTest.class); + + @Test + public void givenHashMap_whenPuttingTwice_thenReturningFirstValue() { + Map map = new HashMap<>(); + assertThat(map.put("key1", "value1")).isEqualTo(null); + assertThat(map.put("key1", "value2")).isEqualTo("value1"); + assertThat(map.get("key1")).isEqualTo("value2"); + } + + @Test + public void givenCollectionAsValue_whenPuttingTwice_thenReturningCollection() { + Map> map = new HashMap<>(); + List list = new ArrayList<>(); + map.put("key1", list); + map.get("key1").add("value1"); + map.get("key1").add("value2"); + assertThat(map.get("key1").get(0)).isEqualTo("value1"); + assertThat(map.get("key1").get(1)).isEqualTo("value2"); + } + + @Test + public void givenCollectionAsValueAndJava8_whenPuttingTwice_thenReturningCollection() { + Map> map = new HashMap<>(); + map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value1"); + map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value2"); + assertThat(map.get("key1").get(0)).isEqualTo("value1"); + assertThat(map.get("key1").get(1)).isEqualTo("value2"); + } + + @Test + public void givenMultiValueMap_whenPuttingTwice_thenReturningValues() { + MultiMap map = new MultiValueMap<>(); + map.put("key1", "value1"); + map.put("key1", "value2"); + assertThat((Collection) map.get("key1")) + .contains("value1", "value2"); + } + + @Test + public void givenArrayListValuedHashMap_whenPuttingDoubleValues_thenReturningAllValues() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("key1", "value1"); + map.put("key1", "value2"); + map.put("key1", "value2"); + assertThat((Collection) map.get("key1")) + .containsExactly("value1", "value2", "value2"); + } + + @Test + public void givenHashSetValuedHashMap_whenPuttingTwiceTheSame_thenReturningOneValue() { + MultiValuedMap map = new HashSetValuedHashMap<>(); + map.put("key1", "value1"); + map.put("key1", "value1"); + assertThat((Collection) map.get("key1")) + .containsExactly("value1"); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenUnmodifiableMultiValuedMap_whenInserting_thenThrowingException() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("key1", "value1"); + map.put("key1", "value2"); + MultiValuedMap immutableMap = + MultiMapUtils.unmodifiableMultiValuedMap(map); + immutableMap.put("key1", "value3"); + } + + @Test + public void givenArrayListMultiMap_whenInserting_thenCorrectOutput() { + Multimap map = ArrayListMultimap.create(); + map.put("key1", "value2"); + map.put("key1", "value1"); + assertThat((Collection) map.get("key1")) + .containsExactly("value2", "value1"); + } + + @Test + public void givenLinkedHashMultiMap_whenInserting_thenReturningValuesInInsertionOrder() { + Multimap map = LinkedHashMultimap.create(); + map.put("key1", "value3"); + map.put("key1", "value1"); + map.put("key1", "value2"); + assertThat((Collection) map.get("key1")) + .containsExactly("value3", "value1", "value2"); + } + + @Test + public void givenTreeMultimap_whenInserting_thenReturningValuesInNaturalOrder() { + Multimap map = TreeMultimap.create(); + map.put("key1", "value3"); + map.put("key1", "value1"); + map.put("key1", "value2"); + assertThat((Collection) map.get("key1")) + .containsExactly("value1", "value2", "value3"); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapUnitTest.java new file mode 100644 index 0000000000..eaf68ccba5 --- /dev/null +++ b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapUnitTest.java @@ -0,0 +1,336 @@ +package com.baeldung.map; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.*; +import java.util.Map.Entry; + +import static org.junit.Assert.*; + +public class MapUnitTest { + private static final Logger LOG = LoggerFactory.getLogger(MapUnitTest.class); + + + @Test + public void givenHashMap_whenRetrievesKeyset_thenCorrect() { + Map map = new HashMap<>(); + map.put("name", "baeldung"); + map.put("type", "blog"); + + Set keys = map.keySet(); + + assertEquals(2, keys.size()); + assertTrue(keys.contains("name")); + assertTrue(keys.contains("type")); + } + + @Test + public void givenHashMap_whenRetrievesValues_thenCorrect() { + Map map = new HashMap<>(); + map.put("name", "baeldung"); + map.put("type", "blog"); + + Collection values = map.values(); + + assertEquals(2, values.size()); + assertTrue(values.contains("baeldung")); + assertTrue(values.contains("blog")); + } + + @Test + public void givenHashMap_whenRetrievesEntries_thenCorrect() { + Map map = new HashMap<>(); + map.put("name", "baeldung"); + map.put("type", "blog"); + + Set> entries = map.entrySet(); + + assertEquals(2, entries.size()); + for (Entry e : entries) { + String key = e.getKey(); + String val = e.getValue(); + assertTrue(key.equals("name") || key.equals("type")); + assertTrue(val.equals("baeldung") || val.equals("blog")); + } + } + + @Test + public void givenKeySet_whenChangeReflectsInMap_thenCorrect() { + Map map = new HashMap<>(); + map.put("name", "baeldung"); + map.put("type", "blog"); + + assertEquals(2, map.size()); + + Set keys = map.keySet(); + + keys.remove("name"); + assertEquals(1, map.size()); + } + + @Test(expected = ConcurrentModificationException.class) + public void givenIterator_whenFailsFastOnModification_thenCorrect() { + Map map = new HashMap<>(); + map.put("name", "baeldung"); + map.put("type", "blog"); + + Set keys = map.keySet(); + Iterator it = keys.iterator(); + map.remove("type"); + while (it.hasNext()) { + String key = it.next(); + } + } + + public void givenIterator_whenRemoveWorks_thenCorrect() { + Map map = new HashMap<>(); + map.put("name", "baeldung"); + map.put("type", "blog"); + + Set keys = map.keySet(); + Iterator it = keys.iterator(); + while (it.hasNext()) { + it.next(); + it.remove(); + } + assertEquals(0, map.size()); + } + + @Test + public void whenHashCodeIsCalledOnPut_thenCorrect() { + MyKey key = new MyKey(1, "name"); + Map map = new HashMap<>(); + map.put(key, "val"); + } + + @Test + public void whenHashCodeIsCalledOnGet_thenCorrect() { + MyKey key = new MyKey(1, "name"); + Map map = new HashMap<>(); + map.put(key, "val"); + map.get(key); + } + + @Test + public void whenGetWorks_thenCorrect() { + Map map = new HashMap<>(); + map.put("key", "val"); + + String val = map.get("key"); + + assertEquals("val", val); + } + + @Test + public void givenNewKey_whenPutReturnsNull_thenCorrect() { + Map map = new HashMap<>(); + + String rtnVal = map.put("key1", "val1"); + + assertNull(rtnVal); + } + + @Test + public void givenUnmappedKey_whenGetReturnsNull_thenCorrect() { + Map map = new HashMap<>(); + + String rtnVal = map.get("key1"); + + assertNull(rtnVal); + } + + @Test + public void givenNullVal_whenPutReturnsNull_thenCorrect() { + Map map = new HashMap<>(); + + String rtnVal = map.put("key1", null); + + assertNull(rtnVal); + } + + @Test + public void givenNullKeyAndVal_whenAccepts_thenCorrect() { + Map map = new HashMap<>(); + + map.put(null, null); + } + + @Test + public void givenNullVal_whenRetrieves_thenCorrect() { + Map map = new HashMap<>(); + map.put("key", null); + + String val = map.get("key"); + + assertNull(val); + } + + @Test + public void whenContainsDistinguishesNullValues_thenCorrect() { + Map map = new HashMap<>(); + + String val1 = map.get("key"); + boolean valPresent = map.containsKey("key"); + + assertNull(val1); + assertFalse(valPresent); + + map.put("key", null); + String val = map.get("key"); + valPresent = map.containsKey("key"); + + assertNull(val); + assertTrue(valPresent); + + } + + @Test + public void whenPutReturnsPrevValue_thenCorrect() { + Map map = new HashMap<>(); + map.put("key1", "val1"); + String rtnVal = map.put("key1", "val2"); + + assertEquals("val1", rtnVal); + } + + @Test + public void whenCallsEqualsOnCollision_thenCorrect() { + HashMap map = new HashMap<>(); + MyKey k1 = new MyKey(1, "firstKey"); + MyKey k2 = new MyKey(2, "secondKey"); + MyKey k3 = new MyKey(2, "thirdKey"); + + LOG.debug("storing value for k1"); + map.put(k1, "firstValue"); + + LOG.debug("storing value for k2"); + map.put(k2, "secondValue"); + + LOG.debug("storing value for k3"); + map.put(k3, "thirdValue"); + + LOG.debug("retrieving value for k1"); + String v1 = map.get(k1); + + LOG.debug("retrieving value for k2"); + String v2 = map.get(k2); + + LOG.debug("retrieving value for k3"); + String v3 = map.get(k3); + + assertEquals("firstValue", v1); + assertEquals("secondValue", v2); + assertEquals("thirdValue", v3); + + } + + @Test + public void givenLinkedHashMap_whenGetsOrderedKeyset_thenCorrect() { + LinkedHashMap map = new LinkedHashMap<>(); + map.put(1, null); + map.put(2, null); + map.put(3, null); + map.put(4, null); + map.put(5, null); + Set keys = map.keySet(); + Integer[] arr = keys.toArray(new Integer[0]); + for (int i = 0; i < arr.length; i++) { + assertEquals(new Integer(i + 1), arr[i]); + + } + } + + @Test + public void givenLinkedHashMap_whenAccessOrderWorks_thenCorrect() { + LinkedHashMap map = new LinkedHashMap<>(16, .75f, true); + map.put(1, null); + map.put(2, null); + map.put(3, null); + map.put(4, null); + map.put(5, null); + Set keys = map.keySet(); + assertEquals("[1, 2, 3, 4, 5]", keys.toString()); + map.get(4); + assertEquals("[1, 2, 3, 5, 4]", keys.toString()); + map.get(1); + assertEquals("[2, 3, 5, 4, 1]", keys.toString()); + map.get(3); + assertEquals("[2, 5, 4, 1, 3]", keys.toString()); + } + + @Test + public void givenLinkedHashMap_whenRemovesEldestEntry_thenCorrect() { + LinkedHashMap map = new MyLinkedHashMap<>(16, .75f, true); + map.put(1, null); + map.put(2, null); + map.put(3, null); + map.put(4, null); + map.put(5, null); + Set keys = map.keySet(); + assertEquals("[1, 2, 3, 4, 5]", keys.toString()); + map.put(6, null); + assertEquals("[2, 3, 4, 5, 6]", keys.toString()); + map.put(7, null); + assertEquals("[3, 4, 5, 6, 7]", keys.toString()); + map.put(8, null); + assertEquals("[4, 5, 6, 7, 8]", keys.toString()); + } + + @Test + public void givenTreeMap_whenOrdersEntriesNaturally_thenCorrect() { + TreeMap map = new TreeMap<>(); + map.put(3, "val"); + map.put(2, "val"); + map.put(1, "val"); + map.put(5, "val"); + map.put(4, "val"); + assertEquals("[1, 2, 3, 4, 5]", map.keySet().toString()); + } + + @Test + public void givenTreeMap_whenOrdersEntriesNaturally_thenCorrect2() { + TreeMap map = new TreeMap<>(); + map.put("c", "val"); + map.put("b", "val"); + map.put("a", "val"); + map.put("e", "val"); + map.put("d", "val"); + + assertEquals("[a, b, c, d, e]", map.keySet().toString()); + } + + @Test + public void givenTreeMap_whenOrdersEntriesByComparator_thenCorrect() { + TreeMap map = new TreeMap<>(Comparator.reverseOrder()); + map.put(3, "val"); + map.put(2, "val"); + map.put(1, "val"); + map.put(5, "val"); + map.put(4, "val"); + + assertEquals("[5, 4, 3, 2, 1]", map.keySet().toString()); + } + + @Test + public void givenTreeMap_whenPerformsQueries_thenCorrect() { + TreeMap map = new TreeMap<>(); + map.put(3, "val"); + map.put(2, "val"); + map.put(1, "val"); + map.put(5, "val"); + map.put(4, "val"); + + Integer highestKey = map.lastKey(); + Integer lowestKey = map.firstKey(); + Set keysLessThan3 = map.headMap(3).keySet(); + Set keysGreaterThanEqTo3 = map.tailMap(3).keySet(); + + assertEquals(new Integer(5), highestKey); + assertEquals(new Integer(1), lowestKey); + assertEquals("[1, 2]", keysLessThan3.toString()); + assertEquals("[3, 4, 5]", keysGreaterThanEqTo3.toString()); + } + +} diff --git a/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapUtilUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapUtilUnitTest.java new file mode 100644 index 0000000000..f8e4c8fd8a --- /dev/null +++ b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MapUtilUnitTest.java @@ -0,0 +1,103 @@ +/** + * + */ +package com.baeldung.map; + +import com.google.common.collect.HashBiMap; +import org.apache.commons.collections4.BidiMap; +import org.apache.commons.collections4.bidimap.DualHashBidiMap; +import org.junit.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertEquals; + +/** + * @author swpraman + * + */ +public class MapUtilUnitTest { + + + @Test + public void whenUsingImperativeWayForSingleKey_shouldReturnSingleKey() { + Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("Tokyo", "Japan"); + capitalCountryMap.put("New Delhi", "India"); + assertEquals("New Delhi", MapUtil.getKey(capitalCountryMap, "India")); + } + + @Test + public void whenUsingImperativeWayForAllKeys_shouldReturnAllKeys() { + Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("Tokyo", "Japan"); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + capitalCountryMap.put("Pretoria", "South Africa"); + capitalCountryMap.put("Bloemfontein", "South Africa"); + + assertEquals(new HashSet(Arrays.asList( + new String[] {"Cape Town", "Pretoria", "Bloemfontein"})), + MapUtil.getKeys(capitalCountryMap, "South Africa")); + } + + @Test + public void whenUsingFunctionalWayForSingleKey_shouldReturnSingleKey() { + Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("Tokyo", "Japan"); + capitalCountryMap.put("Berlin", "Germany"); + assertEquals("Berlin", MapUtil.keys(capitalCountryMap, "Germany").findFirst().get()); + } + + @Test + public void whenUsingFunctionalWayForAllKeys_shouldReturnAllKeys() { + Map capitalCountryMap = new HashMap<>(); + capitalCountryMap.put("Tokyo", "Japan"); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + capitalCountryMap.put("Pretoria", "South Africa"); + capitalCountryMap.put("Bloemfontein", "South Africa"); + assertEquals(new HashSet(Arrays.asList( + new String[] {"Cape Town", "Pretoria", "Bloemfontein"})), + MapUtil.keys(capitalCountryMap, "South Africa").collect(Collectors.toSet())); + } + + @Test + public void whenUsingBidiMap_shouldReturnKey() { + BidiMap capitalCountryMap = new DualHashBidiMap(); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + assertEquals("Berlin", capitalCountryMap.getKey("Germany")); + } + + @Test + public void whenUsingBidiMapAddDuplicateValue_shouldRemoveOldEntry() { + BidiMap capitalCountryMap = new DualHashBidiMap(); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + capitalCountryMap.put("Pretoria", "South Africa"); + assertEquals("Pretoria", capitalCountryMap.getKey("South Africa")); + } + + @Test + public void whenUsingBiMap_shouldReturnKey() { + HashBiMap capitalCountryMap = HashBiMap.create(); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + assertEquals("Berlin", capitalCountryMap.inverse().get("Germany")); + } + + @Test(expected=IllegalArgumentException.class) + public void whenUsingBiMapAddDuplicateValue_shouldThrowException() { + HashBiMap capitalCountryMap = HashBiMap.create(); + capitalCountryMap.put("Berlin", "Germany"); + capitalCountryMap.put("Cape Town", "South Africa"); + capitalCountryMap.put("Pretoria", "South Africa"); + assertEquals("Berlin", capitalCountryMap.inverse().get("Germany")); + } + +} diff --git a/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MultiValuedMapUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MultiValuedMapUnitTest.java new file mode 100644 index 0000000000..686c1cef87 --- /dev/null +++ b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/MultiValuedMapUnitTest.java @@ -0,0 +1,227 @@ +package com.baeldung.map; + +import org.apache.commons.collections4.MultiMapUtils; +import org.apache.commons.collections4.MultiSet; +import org.apache.commons.collections4.MultiValuedMap; +import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; +import org.apache.commons.collections4.multimap.HashSetValuedHashMap; +import org.junit.Test; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +public class MultiValuedMapUnitTest { + + @Test + public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutMethod_thenReturningAllValues() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + + map.put("fruits", "apple"); + map.put("fruits", "orange"); + + assertThat((Collection) map.get("fruits")).containsExactly("apple", "orange"); + + } + + @Test + public void givenMultiValuesMap_whenPuttingMultipleValuesUsingPutAllMethod_thenReturningAllValues() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + + map.putAll("vehicles", Arrays.asList("car", "bike")); + + assertThat((Collection) map.get("vehicles")).containsExactly("car", "bike"); + + } + + @Test + public void givenMultiValuesMap_whenGettingValueUsingGetMethod_thenReturningValue() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + + map.put("fruits", "apple"); + + assertThat((Collection) map.get("fruits")).containsExactly("apple"); + } + + @Test + public void givenMultiValuesMap_whenUsingEntriesMethod_thenReturningMappings() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + + Collection> entries = (Collection>) map.entries(); + + for(Map.Entry entry : entries) { + assertThat(entry.getKey()).contains("fruits"); + assertTrue(entry.getValue().equals("apple") || entry.getValue().equals("orange") ); + } + } + + @Test + public void givenMultiValuesMap_whenUsingKeysMethod_thenReturningAllKeys() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); + + MultiSet keys = map.keys(); + + assertThat((keys)).contains("fruits", "vehicles"); + + } + + @Test + public void givenMultiValuesMap_whenUsingKeySetMethod_thenReturningAllKeys() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); + + Set keys = map.keySet(); + + assertThat(keys).contains("fruits", "vehicles"); + + } + + @Test + public void givenMultiValuesMap_whenUsingValuesMethod_thenReturningAllValues() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); + + assertThat(((Collection) map.values())).contains("apple", "orange", "car", "bike"); + } + + @Test + public void givenMultiValuesMap_whenUsingRemoveMethod_thenReturningUpdatedMap() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); + assertThat(((Collection) map.values())).contains("apple", "orange", "car", "bike"); + + map.remove("fruits"); + + assertThat(((Collection) map.values())).contains("car", "bike"); + + } + + @Test + public void givenMultiValuesMap_whenUsingRemoveMappingMethod_thenReturningUpdatedMapAfterMappingRemoved() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); + assertThat(((Collection) map.values())).contains("apple", "orange", "car", "bike"); + + map.removeMapping("fruits", "apple"); + + assertThat(((Collection) map.values())).contains("orange", "car", "bike"); + } + + @Test + public void givenMultiValuesMap_whenUsingClearMethod_thenReturningEmptyMap() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); + assertThat(((Collection) map.values())).contains("apple", "orange", "car", "bike"); + + map.clear(); + + assertTrue(map.isEmpty()); + } + + @Test + public void givenMultiValuesMap_whenUsingContainsKeyMethod_thenReturningTrue() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); + + assertTrue(map.containsKey("fruits")); + } + + @Test + public void givenMultiValuesMap_whenUsingContainsValueMethod_thenReturningTrue() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); + + assertTrue(map.containsValue("orange")); + } + + @Test + public void givenMultiValuesMap_whenUsingIsEmptyMethod_thenReturningFalse() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); + + assertFalse(map.isEmpty()); + } + + @Test + public void givenMultiValuesMap_whenUsingSizeMethod_thenReturningElementCount() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("vehicles", "car"); + map.put("vehicles", "bike"); + + assertEquals(4, map.size()); + } + + @Test + public void givenArrayListValuedHashMap_whenPuttingDoubleValues_thenReturningAllValues() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + map.put("fruits", "orange"); + + assertThat((Collection) map.get("fruits")).containsExactly("apple", "orange", "orange"); + } + + @Test + public void givenHashSetValuedHashMap_whenPuttingTwiceTheSame_thenReturningOneValue() { + MultiValuedMap map = new HashSetValuedHashMap<>(); + map.put("fruits", "apple"); + map.put("fruits", "apple"); + + assertThat((Collection) map.get("fruits")).containsExactly("apple"); + } + + @Test(expected = UnsupportedOperationException.class) + public void givenUnmodifiableMultiValuedMap_whenInserting_thenThrowingException() { + MultiValuedMap map = new ArrayListValuedHashMap<>(); + map.put("fruits", "apple"); + map.put("fruits", "orange"); + MultiValuedMap immutableMap = MultiMapUtils.unmodifiableMultiValuedMap(map); + + immutableMap.put("fruits", "banana"); + + } + + +} diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index ebdb11925b..3fc978a68c 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -42,6 +42,9 @@ core-java-collections-list core-java-collections-list-2 core-java-collections-list-3 + core-java-collections-maps + core-java-collections-maps-2 + core-java-collections-maps-3 core-java-concurrency-2 From 39abe6bfd14ee2f8f7f248f3c4e7d9feb0f86b01 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Tue, 7 Apr 2020 14:53:59 +0530 Subject: [PATCH 106/187] JAVA-1188: README changes --- core-java-modules/core-java-collections-maps-2/README.md | 2 +- core-java-modules/core-java-collections-maps-3/README.md | 2 +- core-java-modules/core-java-collections-maps/README.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core-java-modules/core-java-collections-maps-2/README.md b/core-java-modules/core-java-collections-maps-2/README.md index da9279b191..f49ba25c8c 100644 --- a/core-java-modules/core-java-collections-maps-2/README.md +++ b/core-java-modules/core-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]](/core-java-collections-maps) [[next -->]](/core-java-collections-maps-3) +- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps) [[next -->]](/core-java-modules/core-java-collections-maps-3) diff --git a/core-java-modules/core-java-collections-maps-3/README.md b/core-java-modules/core-java-collections-maps-3/README.md index 142aa34800..64a3b75d83 100644 --- a/core-java-modules/core-java-collections-maps-3/README.md +++ b/core-java-modules/core-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]](/core-java-collections-maps-2) +- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2) diff --git a/core-java-modules/core-java-collections-maps/README.md b/core-java-modules/core-java-collections-maps/README.md index 1323fb97cd..828f8992e1 100644 --- a/core-java-modules/core-java-collections-maps/README.md +++ b/core-java-modules/core-java-collections-maps/README.md @@ -13,4 +13,4 @@ This module contains articles about Map data structures in Java. - [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 -->]](/core-java-collections-maps-2) +- More articles: [[next -->]](/core-java-modules/core-java-collections-maps-2) From 298cc81d7d16cfd9acbd9dc6ab9933f808414da7 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Tue, 7 Apr 2020 15:03:43 +0530 Subject: [PATCH 107/187] JAVA-1188: main pom changes to remove java-collections-maps --- pom.xml | 3 --- 1 file changed, 3 deletions(-) diff --git a/pom.xml b/pom.xml index e21c13efc2..219c7ce599 100644 --- a/pom.xml +++ b/pom.xml @@ -453,9 +453,6 @@ java-collections-conversions java-collections-conversions-2 - java-collections-maps - java-collections-maps-2 - java-collections-maps-3 javafx From 2986e1ace50b1fe369b2e6856be3def7dc2b00c8 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 17:35:51 +0800 Subject: [PATCH 108/187] Update README.md --- persistence-modules/spring-hibernate4/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/persistence-modules/spring-hibernate4/README.md b/persistence-modules/spring-hibernate4/README.md index cfa13ca3b0..a5a72a9b7e 100644 --- a/persistence-modules/spring-hibernate4/README.md +++ b/persistence-modules/spring-hibernate4/README.md @@ -9,7 +9,6 @@ This module contains articles about Spring with Hibernate 4 - [Stored Procedures with Hibernate](https://www.baeldung.com/stored-procedures-with-hibernate-tutorial) - [Hibernate: save, persist, update, merge, saveOrUpdate](https://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate) - [Eager/Lazy Loading In Hibernate](https://www.baeldung.com/hibernate-lazy-eager-loading) -- [The DAO with Spring and Hibernate](https://www.baeldung.com/persistence-layer-with-spring-and-hibernate) - [Auditing with JPA, Hibernate, and Spring Data JPA](https://www.baeldung.com/database-auditing-jpa) ### Quick Start From 83be0892e7d536956ddc0a65607ba16e0b4b8e07 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Tue, 7 Apr 2020 15:08:09 +0530 Subject: [PATCH 109/187] JAVA-1188: main pom changes to remove java-collections-maps --- pom.xml | 3 --- 1 file changed, 3 deletions(-) diff --git a/pom.xml b/pom.xml index 219c7ce599..d5e2ddd0c7 100644 --- a/pom.xml +++ b/pom.xml @@ -962,9 +962,6 @@ java-collections-conversions java-collections-conversions-2 - java-collections-maps - java-collections-maps-2 - java-collections-maps-3 javafx From 6ffe07efff4ddda7822faa2ca4bcdea1b0e3b3e0 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 17:39:12 +0800 Subject: [PATCH 110/187] Update README.md --- core-java-modules/core-java-8-2/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/core-java-modules/core-java-8-2/README.md b/core-java-modules/core-java-8-2/README.md index 961941aac7..c1c09d2192 100644 --- a/core-java-modules/core-java-8-2/README.md +++ b/core-java-modules/core-java-8-2/README.md @@ -4,7 +4,6 @@ This module contains articles about Java 8 core features ### Relevant Articles: -- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution) - [Run a Java Application from the Command Line](https://www.baeldung.com/java-run-jar-with-arguments) - [Java 8 Stream skip() vs limit()](https://www.baeldung.com/java-stream-skip-vs-limit) - [Guide to Java BiFunction Interface](https://www.baeldung.com/java-bifunction-interface) From 34927fcc12acb04047bd854a93157366b45896fd Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 17:44:36 +0800 Subject: [PATCH 111/187] Update README.md --- core-java-modules/core-java-collections/README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/core-java-modules/core-java-collections/README.md b/core-java-modules/core-java-collections/README.md index 340c2b286e..12e3c5ac17 100644 --- a/core-java-modules/core-java-collections/README.md +++ b/core-java-modules/core-java-collections/README.md @@ -3,7 +3,6 @@ This module contains articles about Java collections ### Relevant Articles: -- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection) - [Introduction to the Java ArrayDeque](https://www.baeldung.com/java-array-deque) - [An Introduction to Java.util.Hashtable Class](https://www.baeldung.com/java-hash-table) - [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe) @@ -13,4 +12,4 @@ This module contains articles about Java collections - [Defining a Char Stack in Java](https://www.baeldung.com/java-char-stack) - [Guide to the Java Queue Interface](https://www.baeldung.com/java-queue) - [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections) -- [[More -->]](/core-java-modules/core-java-collections-2) \ No newline at end of file +- [[More -->]](/core-java-modules/core-java-collections-2) From 959bf74b1e1cf184df9186ea7f68f7032d64f6a2 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 17:48:34 +0800 Subject: [PATCH 112/187] Delete README.md --- apache-olingo/olingo2/README.md | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 apache-olingo/olingo2/README.md diff --git a/apache-olingo/olingo2/README.md b/apache-olingo/olingo2/README.md deleted file mode 100644 index 826cd0133e..0000000000 --- a/apache-olingo/olingo2/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Intro to OData with Olingo](https://www.baeldung.com/olingo) From 9ae4555a4f031263925e7958dd76fc5277e65ec2 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 17:52:32 +0800 Subject: [PATCH 113/187] Update README.md --- algorithms-miscellaneous-3/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/algorithms-miscellaneous-3/README.md b/algorithms-miscellaneous-3/README.md index 00b785c1b2..dd5bbac162 100644 --- a/algorithms-miscellaneous-3/README.md +++ b/algorithms-miscellaneous-3/README.md @@ -13,6 +13,5 @@ This module contains articles about algorithms. Some classes of algorithms, e.g. - [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle) - [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique) - [Creating a Triangle with for Loops in Java](https://www.baeldung.com/java-print-triangle) -- [Efficient Word Frequency Calculator in Java](https://www.baeldung.com/java-word-frequency) - [The K-Means Clustering Algorithm in Java](https://www.baeldung.com/java-k-means-clustering-algorithm) - More articles: [[<-- prev]](/algorithms-miscellaneous-2) [[next -->]](/algorithms-miscellaneous-4) From 0625de19744d47721bc313ce1ef193859cc536c6 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 17:54:20 +0800 Subject: [PATCH 114/187] Update README.md --- core-java-modules/core-java-collections-2/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/core-java-modules/core-java-collections-2/README.md b/core-java-modules/core-java-collections-2/README.md index de5daddb38..e5f6126811 100644 --- a/core-java-modules/core-java-collections-2/README.md +++ b/core-java-modules/core-java-collections-2/README.md @@ -12,4 +12,3 @@ - [Sorting in Java](https://www.baeldung.com/java-sorting) - [Getting the Size of an Iterable in Java](https://www.baeldung.com/java-iterable-size) - [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections) -- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream) From 4ccdaeb5f1f5fa718f63e0ba1a46d38e5b14bce9 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 17:56:49 +0800 Subject: [PATCH 115/187] Update README.md --- spring-core-2/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-core-2/README.md b/spring-core-2/README.md index 1fb591f693..0c0dac3dbf 100644 --- a/spring-core-2/README.md +++ b/spring-core-2/README.md @@ -7,7 +7,6 @@ This module contains articles about core Spring functionality - [Guide to Spring @Autowired](http://www.baeldung.com/spring-autowire) - [Spring Profiles](http://www.baeldung.com/spring-profiles) - [A Spring Custom Annotation for a Better DAO](http://www.baeldung.com/spring-annotation-bean-pre-processor) -- [Running Setup Data on Startup in Spring](http://www.baeldung.com/running-setup-logic-on-startup-in-spring) - [Quick Guide to Spring Bean Scopes](http://www.baeldung.com/spring-bean-scopes) - [Custom Scope in Spring](http://www.baeldung.com/spring-custom-scope) - [@Order in Spring](http://www.baeldung.com/spring-order) From 44517677a68e52717cacce6ab503249fe3d14ff6 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 17:59:28 +0800 Subject: [PATCH 116/187] Update README.md --- spring-core-2/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-core-2/README.md b/spring-core-2/README.md index 0c0dac3dbf..a144f5203c 100644 --- a/spring-core-2/README.md +++ b/spring-core-2/README.md @@ -14,6 +14,5 @@ This module contains articles about core Spring functionality - [Spring Events](https://www.baeldung.com/spring-events) - [Spring Null-Safety Annotations](https://www.baeldung.com/spring-null-safety-annotations) - [Using @Autowired in Abstract Classes](https://www.baeldung.com/spring-autowired-abstract-class) -- [Guide to the Spring BeanFactory](https://www.baeldung.com/spring-beanfactory) - [Reading HttpServletRequest Multiple Times in Spring](https://www.baeldung.com/spring-reading-httpservletrequest-multiple-times) - More articles: [[<-- prev]](/spring-core)[[next -->]](/spring-core-3) From 694ed29f705e3e228b866625dbdfea0b11523ec3 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 7 Apr 2020 18:02:08 +0800 Subject: [PATCH 117/187] Update README.md --- spring-core-2/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-core-2/README.md b/spring-core-2/README.md index a144f5203c..947b816db8 100644 --- a/spring-core-2/README.md +++ b/spring-core-2/README.md @@ -14,5 +14,4 @@ This module contains articles about core Spring functionality - [Spring Events](https://www.baeldung.com/spring-events) - [Spring Null-Safety Annotations](https://www.baeldung.com/spring-null-safety-annotations) - [Using @Autowired in Abstract Classes](https://www.baeldung.com/spring-autowired-abstract-class) -- [Reading HttpServletRequest Multiple Times in Spring](https://www.baeldung.com/spring-reading-httpservletrequest-multiple-times) - More articles: [[<-- prev]](/spring-core)[[next -->]](/spring-core-3) 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 118/187] 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 6640e14f8bec1c63a117a75acebc16a0e4fd14a6 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 8 Apr 2020 13:11:01 +0800 Subject: [PATCH 119/187] Update README.md --- logging-modules/log-mdc/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/logging-modules/log-mdc/README.md b/logging-modules/log-mdc/README.md index b676d3ba76..0d516619ef 100644 --- a/logging-modules/log-mdc/README.md +++ b/logging-modules/log-mdc/README.md @@ -1,7 +1,7 @@ ### Relevant Articles: - TBD - [Improved Java Logging with Mapped Diagnostic Context (MDC)](https://www.baeldung.com/mdc-in-log4j-2-logback) -- [Java Logging with Nested Diagnostic Context (NDC)](https:www.baeldung.com/java-logging-ndc-log4j) +- [Java Logging with Nested Diagnostic Context (NDC)](https://www.baeldung.com/java-logging-ndc-log4j) - [Drools Using Rules from Excel Files](https://www.baeldung.com/drools-excel) ### References From f9ac384b8567a06c65e7b1e47c3ec2c3026a8dda Mon Sep 17 00:00:00 2001 From: Sam Millington Date: Wed, 8 Apr 2020 18:40:34 +0100 Subject: [PATCH 120/187] 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 121/187] 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 From 3786d6309db285b8d8f2b999b2ee020593816050 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 9 Apr 2020 16:48:25 +0800 Subject: [PATCH 122/187] Update README.md --- java-numbers/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/java-numbers/README.md b/java-numbers/README.md index 8f53006b38..f4b76c3c98 100644 --- a/java-numbers/README.md +++ b/java-numbers/README.md @@ -12,4 +12,5 @@ This module contains articles about numbers in Java. - [Calculating the nth Root in Java](https://www.baeldung.com/java-nth-root) - [Convert Double to String, Removing Decimal Places](https://www.baeldung.com/java-double-to-string) - [Changing the Order in a Sum Operation Can Produce Different Results?](https://www.baeldung.com/java-floating-point-sum-order) +- [Using Math.sin with Degrees](https://www.baeldung.com/java-math-sin-degrees) - More articles: [[next -->]](/../java-numbers-2) From d29fef1f518a3d35cb35d74204ba468a263a825b Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Thu, 9 Apr 2020 16:50:03 +0800 Subject: [PATCH 123/187] Update README.md --- core-kotlin-modules/core-kotlin/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-kotlin-modules/core-kotlin/README.md b/core-kotlin-modules/core-kotlin/README.md index 90caccf5c8..151da607ac 100644 --- a/core-kotlin-modules/core-kotlin/README.md +++ b/core-kotlin-modules/core-kotlin/README.md @@ -3,7 +3,7 @@ This module contains articles about Kotlin core features. ### Relevant articles: -- [Introduction to the Kotlin Language](https://www.baeldung.com/kotlin-intro) +- [Introduction to the Kotlin Language](https://www.baeldung.com/kotlin/tutorial) - [Kotlin Java Interoperability](https://www.baeldung.com/kotlin-java-interoperability) - [Get a Random Number in Kotlin](https://www.baeldung.com/kotlin-random-number) - [Create a Java and Kotlin Project with Maven](https://www.baeldung.com/kotlin-maven-java-project) From b132703ce9a61e3ca0a8b6ea69b9790075907265 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Thu, 9 Apr 2020 21:04:10 +0530 Subject: [PATCH 124/187] JWs module dependency fix --- jws/pom.xml | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/jws/pom.xml b/jws/pom.xml index e6ab7e05ec..f867df8051 100644 --- a/jws/pom.xml +++ b/jws/pom.xml @@ -17,7 +17,7 @@ OpenNMS Repository - http://repo.opennms.org/maven2/ + https://repo.opennms.org/maven2/ @@ -27,11 +27,6 @@ jnlp-servlet ${jnlp-servlet.version} - - javax.samples.jnlp - jnlp-jardiff - ${jnlp-jardiff.version} - @@ -84,7 +79,6 @@ 3.0.2 - 1.6.0 1.6.0 From bcf5d50baa5e4b8ce46be437095123a985dcadda Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Thu, 9 Apr 2020 23:42:31 +0530 Subject: [PATCH 125/187] JAVA-1188: Removed duplicate entry from README --- core-java-modules/core-java-collections-maps/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/core-java-modules/core-java-collections-maps/README.md b/core-java-modules/core-java-collections-maps/README.md index 828f8992e1..15cb32fbe8 100644 --- a/core-java-modules/core-java-collections-maps/README.md +++ b/core-java-modules/core-java-collections-maps/README.md @@ -4,7 +4,6 @@ This module contains articles about Map data structures in Java. ### Relevant Articles: - [Guide to the Guava BiMap](https://www.baeldung.com/guava-bimap) -- [A Guide to Java HashMap](https://www.baeldung.com/java-hashmap) - [A Guide to LinkedHashMap in Java](https://www.baeldung.com/java-linked-hashmap) - [A Guide to TreeMap in Java](https://www.baeldung.com/java-treemap) - [How to Store Duplicate Keys in a Map in Java?](https://www.baeldung.com/java-map-duplicate-keys) From db789ae6748a944168dda12c507406e748405315 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Thu, 9 Apr 2020 20:55:15 +0200 Subject: [PATCH 126/187] JAVA-976: Fix spring-security-mvc-login configuration --- .../src/test/java/com/baeldung/SpringContextTest.java | 2 +- .../security/RedirectionSecurityIntegrationTest.java | 2 +- .../src/test/resources/mvc-servlet.xml | 8 -------- 3 files changed, 2 insertions(+), 10 deletions(-) delete mode 100644 spring-security-modules/spring-security-mvc-login/src/test/resources/mvc-servlet.xml diff --git a/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java index 4cf3b736ea..dfc83a40b0 100644 --- a/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/SpringContextTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml", "/mvc-servlet.xml" }) +@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml" }) @WebAppConfiguration public class SpringContextTest { @Test diff --git a/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/security/RedirectionSecurityIntegrationTest.java b/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/security/RedirectionSecurityIntegrationTest.java index 1235e2e69f..e2b444de20 100644 --- a/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/security/RedirectionSecurityIntegrationTest.java +++ b/spring-security-modules/spring-security-mvc-login/src/test/java/com/baeldung/security/RedirectionSecurityIntegrationTest.java @@ -25,7 +25,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml", "/mvc-servlet.xml" }) +@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml" }) @WebAppConfiguration public class RedirectionSecurityIntegrationTest { diff --git a/spring-security-modules/spring-security-mvc-login/src/test/resources/mvc-servlet.xml b/spring-security-modules/spring-security-mvc-login/src/test/resources/mvc-servlet.xml deleted file mode 100644 index aee837c977..0000000000 --- a/spring-security-modules/spring-security-mvc-login/src/test/resources/mvc-servlet.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - \ No newline at end of file From 06a4e640bb6da563db64c2d2d949b2ddbf4c73cf Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Fri, 10 Apr 2020 03:15:39 +0430 Subject: [PATCH 127/187] Fixed a few cassandra related issues --- persistence-modules/java-cassandra/pom.xml | 6 +++ .../src/test/resources/cassandra.yaml | 51 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 persistence-modules/java-cassandra/src/test/resources/cassandra.yaml diff --git a/persistence-modules/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml index 54879fb321..091efaeff4 100644 --- a/persistence-modules/java-cassandra/pom.xml +++ b/persistence-modules/java-cassandra/pom.xml @@ -18,6 +18,12 @@ cassandra-driver-core ${cassandra-driver-core.version} true + + + com.google.guava + guava + + diff --git a/persistence-modules/java-cassandra/src/test/resources/cassandra.yaml b/persistence-modules/java-cassandra/src/test/resources/cassandra.yaml new file mode 100644 index 0000000000..59687444d0 --- /dev/null +++ b/persistence-modules/java-cassandra/src/test/resources/cassandra.yaml @@ -0,0 +1,51 @@ +cluster_name: 'Test Cluster' +hinted_handoff_enabled: true +max_hint_window_in_ms: 10800000 +hinted_handoff_throttle_in_kb: 1024 +max_hints_delivery_threads: 2 +hints_directory: target/embeddedCassandra/hints +authenticator: AllowAllAuthenticator +authorizer: AllowAllAuthorizer +permissions_validity_in_ms: 2000 +partitioner: RandomPartitioner +data_file_directories: + - target/embeddedCassandra/data +commitlog_directory: target/embeddedCassandra/commitlog +cdc_raw_directory: target/embeddedCassandra/cdc +disk_failure_policy: stop +key_cache_size_in_mb: +key_cache_save_period: 14400 +row_cache_size_in_mb: 0 +row_cache_save_period: 0 +saved_caches_directory: target/embeddedCassandra/saved_caches +commitlog_sync: periodic +commitlog_sync_period_in_ms: 10000 +commitlog_segment_size_in_mb: 32 +concurrent_reads: 32 +concurrent_writes: 32 +trickle_fsync: false +trickle_fsync_interval_in_kb: 10240 +thrift_framed_transport_size_in_mb: 15 +thrift_max_message_length_in_mb: 16 +incremental_backups: false +snapshot_before_compaction: false +auto_snapshot: false +column_index_size_in_kb: 64 +compaction_throughput_mb_per_sec: 16 +read_request_timeout_in_ms: 5000 +range_request_timeout_in_ms: 10000 +write_request_timeout_in_ms: 2000 +cas_contention_timeout_in_ms: 1000 +truncate_request_timeout_in_ms: 60000 +request_timeout_in_ms: 10000 +cross_node_timeout: false +endpoint_snitch: SimpleSnitch +dynamic_snitch_update_interval_in_ms: 100 +dynamic_snitch_reset_interval_in_ms: 600000 +dynamic_snitch_badness_threshold: 0.1 +request_scheduler: org.apache.cassandra.scheduler.NoScheduler +index_interval: 128 +seed_provider: + - class_name: org.apache.cassandra.locator.SimpleSeedProvider + parameters: + - seeds: "127.0.0.1" From 7e26a04973e631dcb6ea88cf0e9fbc7b2ad35a34 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Fri, 10 Apr 2020 09:24:15 +0200 Subject: [PATCH 128/187] springboot shedlock building fix --- spring-boot-modules/spring-boot-libraries/pom.xml | 4 ++++ .../shedlock/SpringBootShedlockApplication.java} | 6 +++--- 2 files changed, 7 insertions(+), 3 deletions(-) rename spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/{Application.java => scheduling/shedlock/SpringBootShedlockApplication.java} (71%) diff --git a/spring-boot-modules/spring-boot-libraries/pom.xml b/spring-boot-modules/spring-boot-libraries/pom.xml index 2b1b1b7d12..090967d8a8 100644 --- a/spring-boot-modules/spring-boot-libraries/pom.xml +++ b/spring-boot-modules/spring-boot-libraries/pom.xml @@ -28,6 +28,10 @@ org.springframework.boot spring-boot-starter-tomcat + + org.springframework.boot + spring-boot-starter-data-jpa + org.springframework.boot spring-boot-starter-test diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/Application.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SpringBootShedlockApplication.java similarity index 71% rename from spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/Application.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SpringBootShedlockApplication.java index 15422e1065..cebb234036 100644 --- a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/Application.java +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/scheduling/shedlock/SpringBootShedlockApplication.java @@ -1,4 +1,4 @@ -package com.baeldung; +package com.baeldung.scheduling.shedlock; import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock; import org.springframework.boot.SpringApplication; @@ -8,8 +8,8 @@ import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling @EnableSchedulerLock(defaultLockAtMostFor = "PT30S") -public class Application { +public class SpringBootShedlockApplication { public static void main(String[] args) { - SpringApplication.run(Application.class, args); + SpringApplication.run(SpringBootShedlockApplication.class, args); } } From 52ca4fbcd9e8d1d42eafdb1b4b16326fa09eb404 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 15:29:38 +0800 Subject: [PATCH 129/187] Update README.md --- core-java-modules/core-java-date-operations-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-date-operations-2/README.md b/core-java-modules/core-java-date-operations-2/README.md index 728162ca1a..19c7b98d30 100644 --- a/core-java-modules/core-java-date-operations-2/README.md +++ b/core-java-modules/core-java-date-operations-2/README.md @@ -7,4 +7,5 @@ This module contains articles about date operations in Java. - [Checking If Two Java Dates Are on the Same Day](https://www.baeldung.com/java-check-two-dates-on-same-day) - [Converting Java Date to OffsetDateTime](https://www.baeldung.com/java-convert-date-to-offsetdatetime) - [How to Set the JVM Time Zone](https://www.baeldung.com/java-jvm-time-zone) +- [How to determine day of week by passing specific date in Java?](https://www.baeldung.com/java-get-day-of-week) - [[<-- Prev]](/core-java-modules/core-java-date-operations-1) From bf764f5f44da4adf16a24d08313c85fecf4a93c2 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 15:31:19 +0800 Subject: [PATCH 130/187] Update README.md --- spring-reactive-kotlin/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-reactive-kotlin/README.md b/spring-reactive-kotlin/README.md index 629f7e7f58..d6ce3b7645 100644 --- a/spring-reactive-kotlin/README.md +++ b/spring-reactive-kotlin/README.md @@ -4,3 +4,4 @@ This module contains articles about reactive Kotlin ### Relevant Articles: - [Spring Webflux with Kotlin](https://www.baeldung.com/spring-webflux-kotlin) +- [Kotlin Reactive Microservice With Spring Boot](https://www.baeldung.com/spring-boot-kotlin-reactive-microservice) From e1cf55dc822408210083eff3d52f6502d2c4060f Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 15:40:36 +0800 Subject: [PATCH 131/187] Update README.md --- core-java-modules/core-java-lang-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-lang-2/README.md b/core-java-modules/core-java-lang-2/README.md index 65d40c6a26..3ade982397 100644 --- a/core-java-modules/core-java-lang-2/README.md +++ b/core-java-modules/core-java-lang-2/README.md @@ -10,4 +10,5 @@ This module contains articles about core features in the Java language - [How to Return Multiple Values From a Java Method](https://www.baeldung.com/java-method-return-multiple-values) - [Guide to the Java finally Keyword](https://www.baeldung.com/java-finally-keyword) - [The Java Headless Mode](https://www.baeldung.com/java-headless-mode) +- [Comparing Long Values in Java](https://www.baeldung.com/java-compare-long-values) - [[<-- Prev]](/core-java-modules/core-java-lang) From 404f13f940d2f2d7143f5d6bcd9231c27f63059a Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 15:46:47 +0800 Subject: [PATCH 132/187] Update README.md --- spring-security-modules/spring-security-mvc/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-modules/spring-security-mvc/README.md b/spring-security-modules/spring-security-mvc/README.md index 7d1a492cd3..bb4cfe1a4f 100644 --- a/spring-security-modules/spring-security-mvc/README.md +++ b/spring-security-modules/spring-security-mvc/README.md @@ -10,6 +10,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [HttpSessionListener Example – Monitoring](https://www.baeldung.com/httpsessionlistener_with_metrics) - [Control the Session with Spring Security](https://www.baeldung.com/spring-security-session) +- [The Clear-Site-Data Header in Spring Security](https://www.baeldung.com/spring-security-clear-site-data-header) ### Build the Project From 721f339d8c32ba93f908e021a298e90666544ce5 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 15:50:44 +0800 Subject: [PATCH 133/187] Update README.md --- core-java-modules/core-java-strings/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-strings/README.md b/core-java-modules/core-java-strings/README.md index 4a418db29f..5daae8394a 100644 --- a/core-java-modules/core-java-strings/README.md +++ b/core-java-modules/core-java-strings/README.md @@ -12,3 +12,4 @@ This module contains articles about strings in Java. - [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) - [Java Multi-line String](https://www.baeldung.com/java-multiline-string) - [Guide to Java String Pool](https://www.baeldung.com/java-string-pool) +- [Fixing “constant string too long” Build Error](https://www.baeldung.com/java-constant-string-too-long-error) From 086d6a9531a5f42f1284ed1809254d22226c688a Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 15:54:59 +0800 Subject: [PATCH 134/187] Update README.md --- persistence-modules/hibernate-jpa/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/hibernate-jpa/README.md b/persistence-modules/hibernate-jpa/README.md index d0a253f028..fb48f975bc 100644 --- a/persistence-modules/hibernate-jpa/README.md +++ b/persistence-modules/hibernate-jpa/README.md @@ -13,3 +13,4 @@ This module contains articles specific to use of Hibernate as a JPA implementati - [Enabling Transaction Locks in Spring Data JPA](https://www.baeldung.com/java-jpa-transaction-locks) - [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception) - [JPA/Hibernate Persistence Context](https://www.baeldung.com/jpa-hibernate-persistence-context) +- [Quick Guide to EntityManager#getReference()](https://www.baeldung.com/jpa-entity-manager-get-reference) From f88c53eb4921eb6aac480f4524912e8ef5620f10 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 15:57:27 +0800 Subject: [PATCH 135/187] Update README.md --- core-java-modules/core-java-regex/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-regex/README.md b/core-java-modules/core-java-regex/README.md index 21cd7a95a3..6fdea9f2ca 100644 --- a/core-java-modules/core-java-regex/README.md +++ b/core-java-modules/core-java-regex/README.md @@ -9,3 +9,4 @@ - [Pre-compile Regex Patterns Into Pattern Objects](https://www.baeldung.com/java-regex-pre-compile) - [Difference Between Java Matcher find() and matches()](https://www.baeldung.com/java-matcher-find-vs-matches) - [How to Use Regular Expressions to Replace Tokens in Strings](https://www.baeldung.com/java-regex-token-replacement) +- [Regular Expressions \s and \s+ in Java](https://www.baeldung.com/java-regex-s-splus) From 012465bed2504d614c0c694e24c0f023492ba1dc Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:00:00 +0800 Subject: [PATCH 136/187] Create README.md --- persistence-modules/spring-persistence-simple-2/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 persistence-modules/spring-persistence-simple-2/README.md diff --git a/persistence-modules/spring-persistence-simple-2/README.md b/persistence-modules/spring-persistence-simple-2/README.md new file mode 100644 index 0000000000..a6408df8f2 --- /dev/null +++ b/persistence-modules/spring-persistence-simple-2/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Spring JdbcTemplate Unit Testing](https://www.baeldung.com/spring-jdbctemplate-testing) From 564e7fc0337630a6b7e53a49abbd018dabf3eb06 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:02:20 +0800 Subject: [PATCH 137/187] Create README.md --- algorithms-miscellaneous-6/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 algorithms-miscellaneous-6/README.md diff --git a/algorithms-miscellaneous-6/README.md b/algorithms-miscellaneous-6/README.md new file mode 100644 index 0000000000..d9d6483a39 --- /dev/null +++ b/algorithms-miscellaneous-6/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Boruvka’s Algorithm for Minimum Spanning Trees](https://www.baeldung.com/java-boruvka-algorithm) From 09b03f875416b14694b3491c46cbcf52e796bb91 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:05:30 +0800 Subject: [PATCH 138/187] Update README.md --- algorithms-miscellaneous-6/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/algorithms-miscellaneous-6/README.md b/algorithms-miscellaneous-6/README.md index d9d6483a39..99be63d7ca 100644 --- a/algorithms-miscellaneous-6/README.md +++ b/algorithms-miscellaneous-6/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Boruvka’s Algorithm for Minimum Spanning Trees](https://www.baeldung.com/java-boruvka-algorithm) +- [Gradient Descent in Java](https://www.baeldung.com/java-gradient-descent) From acdcb5cacab872b1ce9b907483efa67a67e9cc23 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:07:16 +0800 Subject: [PATCH 139/187] Update README.md --- core-java-modules/core-java-concurrency-basic-2/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-concurrency-basic-2/README.md b/core-java-modules/core-java-concurrency-basic-2/README.md index e3f7a94e14..c7143baf36 100644 --- a/core-java-modules/core-java-concurrency-basic-2/README.md +++ b/core-java-modules/core-java-concurrency-basic-2/README.md @@ -8,4 +8,5 @@ This module contains articles about basic Java concurrency - [Difference Between Wait and Sleep in Java](https://www.baeldung.com/java-wait-and-sleep) - [Guide to the Synchronized Keyword in Java](https://www.baeldung.com/java-synchronized) - [Life Cycle of a Thread in Java](https://www.baeldung.com/java-thread-lifecycle) -- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic) \ No newline at end of file +- [Guide to AtomicMarkableReference](https://www.baeldung.com/java-atomicmarkablereference) +- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic) From 88afc279cffb8c58ec7f0e5416a34d2efb5ca282 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:10:17 +0800 Subject: [PATCH 140/187] Update README.md --- core-java-modules/core-java-string-operations/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-string-operations/README.md b/core-java-modules/core-java-string-operations/README.md index 18a2649a6a..c40e56bc46 100644 --- a/core-java-modules/core-java-string-operations/README.md +++ b/core-java-modules/core-java-string-operations/README.md @@ -13,4 +13,5 @@ This module contains articles about string operations. - [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline) - [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) - [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode) +- [Java Convert PDF to Base64](https://www.baeldung.com/java-convert-pdf-to-base64) - More articles: [[next -->]](../core-java-string-operations-2) From c34f99f42aac0ea22d6afbbbf356568c1afaa24c Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:21:07 +0800 Subject: [PATCH 141/187] Update README.md --- libraries-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries-3/README.md b/libraries-3/README.md index 62bd3b9f66..ec433960ef 100644 --- a/libraries-3/README.md +++ b/libraries-3/README.md @@ -16,3 +16,4 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [Introduction to Takes](https://www.baeldung.com/java-takes) - [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway) - [Introduction to Alibaba Arthas](https://www.baeldung.com/java-alibaba-arthas-intro) +- [Quick Guide to Spring Cloud Circuit Breaker](https://www.baeldung.com/spring-cloud-circuit-breaker) From 45abeb493b4d34a3b6502faa632d0bcd160cc3c7 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:22:40 +0800 Subject: [PATCH 142/187] Update README.md --- core-java-modules/core-java-concurrency-advanced-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-concurrency-advanced-3/README.md b/core-java-modules/core-java-concurrency-advanced-3/README.md index 2c554e948b..b11cde5158 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/README.md +++ b/core-java-modules/core-java-concurrency-advanced-3/README.md @@ -10,4 +10,5 @@ This module contains articles about advanced topics about multithreading with co - [Guide to RejectedExecutionHandler](https://www.baeldung.com/java-rejectedexecutionhandler) - [Guide to Work Stealing in Java](https://www.baeldung.com/java-work-stealing) - [Asynchronous Programming in Java](https://www.baeldung.com/java-asynchronous-programming) +- [Java Thread Deadlock and Livelock](https://www.baeldung.com/java-deadlock-livelock) - [[<-- previous]](/core-java-modules/core-java-concurrency-advanced-2) From 76d15b81c505e8f82db8f70d786ee09c253622d6 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:25:53 +0800 Subject: [PATCH 143/187] Update README.md --- 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 598acfb927..f818bdb675 100644 --- a/java-numbers-3/README.md +++ b/java-numbers-3/README.md @@ -10,4 +10,5 @@ This module contains articles about numbers in Java. - [Generating Random Numbers in a Range in Java](https://www.baeldung.com/java-generating-random-numbers-in-range) - [Listing Numbers Within a Range in Java](https://www.baeldung.com/java-listing-numbers-within-a-range) - [Fibonacci Series in Java](https://www.baeldung.com/java-fibonacci) +- [Guide to the Number Class in Java](https://www.baeldung.com/java-number-class) - More articles: [[<-- prev]](/java-numbers-2) From cb016c1027f8ec8b9bcea4c87f88fd2a5a622fa0 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:28:18 +0800 Subject: [PATCH 144/187] Update README.md --- core-java-modules/core-java-security-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-security-2/README.md b/core-java-modules/core-java-security-2/README.md index 2eb21fb77e..24a821bd4d 100644 --- a/core-java-modules/core-java-security-2/README.md +++ b/core-java-modules/core-java-security-2/README.md @@ -8,4 +8,5 @@ This module contains articles about core Java Security - [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) +- [Checksums in Java](https://www.baeldung.com/java-checksums) - More articles: [[<-- prev]](/core-java-modules/core-java-security) From 618916b6ab8753bf6d419031d21e9e1db934e8f1 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:31:17 +0800 Subject: [PATCH 145/187] Update README.md --- guava-collections-map/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/guava-collections-map/README.md b/guava-collections-map/README.md index b3ec5e2157..4f8743dcfb 100644 --- a/guava-collections-map/README.md +++ b/guava-collections-map/README.md @@ -9,4 +9,5 @@ This module contains articles about map collections in Guava - [Guide to Guava Multimap](https://www.baeldung.com/guava-multimap) - [Guide to Guava RangeMap](https://www.baeldung.com/guava-rangemap) - [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap) -- [Guide to Guava ClassToInstanceMap](https://www.baeldung.com/guava-class-to-instance-map) \ No newline at end of file +- [Guide to Guava ClassToInstanceMap](https://www.baeldung.com/guava-class-to-instance-map) +- [Using Guava’s MapMaker](https://www.baeldung.com/guava-mapmaker) From 2b27994c13acca8ad0af453eb05c6e82749e6543 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:35:28 +0800 Subject: [PATCH 146/187] Update README.md --- spring-batch/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/spring-batch/README.md b/spring-batch/README.md index d637de269c..3a89459629 100644 --- a/spring-batch/README.md +++ b/spring-batch/README.md @@ -3,6 +3,7 @@ This module contains articles about Spring Batch ### Relevant Articles: + - [Introduction to Spring Batch](https://www.baeldung.com/introduction-to-spring-batch) - [Spring Batch using Partitioner](https://www.baeldung.com/spring-batch-partitioner) - [Spring Batch – Tasklets vs Chunks](https://www.baeldung.com/spring-batch-tasklet-chunk) @@ -10,3 +11,4 @@ This module contains articles about Spring Batch - [Configuring Skip Logic in Spring Batch](https://www.baeldung.com/spring-batch-skip-logic) - [Testing a Spring Batch Job](https://www.baeldung.com/spring-batch-testing-job) - [Configuring Retry Logic in Spring Batch](https://www.baeldung.com/spring-batch-retry-logic) +- [Conditional Flow in Spring Batch](https://www.baeldung.com/spring-batch-conditional-flow) From 44f3912f83a0aa0f7aa4dcdec5a0496d020e7bfa Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:38:35 +0800 Subject: [PATCH 147/187] Update README.md --- core-kotlin-modules/core-kotlin-collections/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-kotlin-modules/core-kotlin-collections/README.md b/core-kotlin-modules/core-kotlin-collections/README.md index bbea5869af..f0da2b4cfd 100644 --- a/core-kotlin-modules/core-kotlin-collections/README.md +++ b/core-kotlin-modules/core-kotlin-collections/README.md @@ -8,3 +8,4 @@ This module contains articles about core Kotlin collections. - [Overview of Kotlin Collections API](https://www.baeldung.com/kotlin-collections-api) - [Converting a List to Map in Kotlin](https://www.baeldung.com/kotlin-list-to-map) - [Filtering Kotlin Collections](https://www.baeldung.com/kotlin-filter-collection) +- [Collection Transformations in Kotlin](https://www.baeldung.com/kotlin-collection-transformations) From fba81f5e629ca568d197622b6d32dbe1c653de15 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:40:10 +0800 Subject: [PATCH 148/187] Update README.md --- guava/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guava/README.md b/guava/README.md index c67a3604ea..71f76c1360 100644 --- a/guava/README.md +++ b/guava/README.md @@ -12,4 +12,4 @@ This module contains articles a Google Guava - [Guide to Mathematical Utilities in Guava](https://www.baeldung.com/guava-math) - [Bloom Filter in Java using Guava](https://www.baeldung.com/guava-bloom-filter) - [Quick Guide to the Guava RateLimiter](https://www.baeldung.com/guava-rate-limiter) - +- [Introduction to Guava Throwables](https://www.baeldung.com/guava-throwables) From a70207b99317ff43992f9704b1832de960132d79 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:42:37 +0800 Subject: [PATCH 149/187] Update README.md --- core-java-modules/core-java-14/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-14/README.md b/core-java-modules/core-java-14/README.md index 0e8278c4f6..13bb468b30 100644 --- a/core-java-modules/core-java-14/README.md +++ b/core-java-modules/core-java-14/README.md @@ -7,3 +7,4 @@ This module contains articles about Java 14. - [Guide to the @Serial Annotation in Java 14](https://www.baeldung.com/java-14-serial-annotation) - [Java Text Blocks](https://www.baeldung.com/java-text-blocks) - [Pattern Matching for instanceof in Java 14](https://www.baeldung.com/java-pattern-matching-instanceof) +- [Helpful NullPointerExceptions in Java 14](https://www.baeldung.com/java-14-nullpointerexception) From 28401da21a1410bd54c2c4be125d68ffc529f933 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:44:41 +0800 Subject: [PATCH 150/187] Create README.md --- libraries-concurrency/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 libraries-concurrency/README.md diff --git a/libraries-concurrency/README.md b/libraries-concurrency/README.md new file mode 100644 index 0000000000..d1ffe81fa8 --- /dev/null +++ b/libraries-concurrency/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Intro to Coroutines with Quasar](https://www.baeldung.com/java-quasar-coroutines) From a1b1870921120ac90c7b68fa3a19004f564b801a Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:46:53 +0800 Subject: [PATCH 151/187] Update README.md --- core-java-modules/core-java-streams-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-streams-3/README.md b/core-java-modules/core-java-streams-3/README.md index a739245399..05c4b99900 100644 --- a/core-java-modules/core-java-streams-3/README.md +++ b/core-java-modules/core-java-streams-3/README.md @@ -9,4 +9,5 @@ This module contains articles about the Stream API in Java. - [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors) - [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams) - [Debugging Java 8 Streams with IntelliJ](https://www.baeldung.com/intellij-debugging-java-streams) +- [Add BigDecimals using the Stream API](https://www.baeldung.com/java-stream-add-bigdecimals) - More articles: [[<-- prev>]](/../core-java-streams-2) From 8e1787ffeacc858d72180a8d0919650feb796e2e Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:48:28 +0800 Subject: [PATCH 152/187] Update README.md --- spring-5-mvc/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-5-mvc/README.md b/spring-5-mvc/README.md index e98012c047..aff8bb227c 100644 --- a/spring-5-mvc/README.md +++ b/spring-5-mvc/README.md @@ -6,3 +6,4 @@ This module contains articles about Spring 5 model-view-controller (MVC) pattern - [Spring Boot and Kotlin](https://www.baeldung.com/spring-boot-kotlin) - [Spring MVC Streaming and SSE Request Processing](https://www.baeldung.com/spring-mvc-sse-streams) - [Interface Driven Controllers in Spring](https://www.baeldung.com/spring-interface-driven-controllers) +- [Returning Plain HTML From a Spring MVC Controller](https://www.baeldung.com/spring-mvc-return-html) From 08472ff2e9e2dc28f7d7975a9d01a81d2e330742 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:50:04 +0800 Subject: [PATCH 153/187] Update README.md --- spring-thymeleaf-3/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-thymeleaf-3/README.md b/spring-thymeleaf-3/README.md index e1ddd727d7..a8e234b067 100644 --- a/spring-thymeleaf-3/README.md +++ b/spring-thymeleaf-3/README.md @@ -2,4 +2,5 @@ This module contains articles about Spring with Thymeleaf -## Relevant Articles: \ No newline at end of file +## Relevant Articles: +- [Add CSS and JS to Thymeleaf](https://www.baeldung.com/spring-thymeleaf-css-js) From fd1b953c2760173a9679638862a3ad79216a7e50 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:51:50 +0800 Subject: [PATCH 154/187] Update README.md --- spring-core-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-core-3/README.md b/spring-core-3/README.md index b2c4f694a8..6c210b23ef 100644 --- a/spring-core-3/README.md +++ b/spring-core-3/README.md @@ -10,4 +10,5 @@ This module contains articles about core Spring functionality - [Spring – Injecting Collections](https://www.baeldung.com/spring-injecting-collections) - [Design Patterns in the Spring Framework](https://www.baeldung.com/spring-framework-design-patterns) - [Injecting a Value in a Static Field in Spring](https://www.baeldung.com/spring-inject-static-field) +- [Difference Between BeanFactory and ApplicationContext](https://www.baeldung.com/spring-beanfactory-vs-applicationcontext) - More articles: [[<-- prev]](/spring-core-2) From 76cdbd811ebe8ad93758b22807b8ff4b331a50c5 Mon Sep 17 00:00:00 2001 From: patkorek Date: Fri, 10 Apr 2020 12:49:52 +0200 Subject: [PATCH 155/187] Modified one method --- .../com/baeldung/strings/ConvertStringToInt.groovy | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy b/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy index 3b179ee193..3b73c31596 100644 --- a/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy @@ -62,10 +62,17 @@ class ConvertStringToInt { def stringNum = "123" int expectedInt = 123 int intNum = new Integer(stringNum).intValue() - int secondIntNum = new Integer(stringNum) assertEquals(intNum, expectedInt) - assertEquals(secondIntNum, expectedInt) + } + + @Test + void givenString_whenUsingNewInteger_thenConvertToInteger() { + def stringNum = "123" + int expectedInt = 123 + int intNum = new Integer(stringNum) + + assertEquals(intNum, expectedInt) } @Test From 949881921e6513972cc7143517c94b85b81f5644 Mon Sep 17 00:00:00 2001 From: patkorek Date: Fri, 10 Apr 2020 13:27:27 +0200 Subject: [PATCH 156/187] Added test case with isInteger() method. --- .../com/baeldung/strings/ConvertStringToInt.groovy | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy b/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy index 3b73c31596..7a4be4a957 100644 --- a/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy @@ -96,4 +96,15 @@ class ConvertStringToInt { def invalidString = null invalidString.toInteger() } + + @Test + void givenString_whenUsingIsInteger_thenCheckIfCorrectValue() { + def invalidString = "123a" + def validString = "123" + def invalidNum = invalidString?.isInteger() ? invalidString as Integer : false + def correctNum = validString?.isInteger() ? validString as Integer : false + + assertEquals(false, invalidNum) + assertEquals(123, correctNum) + } } From 5a1f7ffea8d617a80d38234bb0f097de49747aed Mon Sep 17 00:00:00 2001 From: gindex Date: Fri, 10 Apr 2020 13:36:51 +0200 Subject: [PATCH 157/187] Add blockingHelloWorld() --- .../java/com/baeldung/mono/MonoUnitTest.java | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java b/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java index b493cd1159..f9e67b0a2f 100644 --- a/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java +++ b/reactor-core/src/test/java/com/baeldung/mono/MonoUnitTest.java @@ -12,13 +12,13 @@ import static org.junit.Assert.assertEquals; public class MonoUnitTest { @Test public void whenMonoProducesString_thenBlockAndConsume() { - String expected = "hello world!"; - String result1 = Mono.just(expected).block(); - assertEquals(expected, result1); + String result1 = blockingHelloWorld().block(); + assertEquals("Hello world!", result1); - String result2 = Mono.just(expected).block(Duration.of(1000, ChronoUnit.MILLIS)); - assertEquals(expected, result2); + String result2 = blockingHelloWorld() + .block(Duration.of(1000, ChronoUnit.MILLIS)); + assertEquals("Hello world!", result2); Optional result3 = Mono.empty().blockOptional(); assertEquals(Optional.empty(), result3); @@ -26,14 +26,18 @@ public class MonoUnitTest { @Test public void whenMonoProducesString_thenConsumeNonBlocking() { - String expected = "hello world!"; - Mono.just(expected) - .doOnNext(result -> assertEquals(expected, result)) + blockingHelloWorld() + .doOnNext(result -> assertEquals("Hello world!", result)) .subscribe(); - Mono.just(expected) - .subscribe(result -> assertEquals(expected, result)); + blockingHelloWorld() + .subscribe(result -> assertEquals("Hello world!", result)); } + + private Mono blockingHelloWorld() { + // blocking + return Mono.just("Hello world!"); + } } From 82e69447a54a650c59953fed9b0fab312fe552e6 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Fri, 10 Apr 2020 21:58:48 +0200 Subject: [PATCH 158/187] BAEL-3730: Add example of usage CacheManagerCustomizer in Spring Boot (#9048) --- spring-caching/pom.xml | 4 ++++ .../caching/boot/CacheApplication.java | 14 +++++++++++ .../caching/boot/SimpleCacheCustomizer.java | 24 +++++++++++++++++++ .../SimpleCacheCustomizerIntegrationTest.java | 24 +++++++++++++++++++ 4 files changed, 66 insertions(+) create mode 100644 spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java create mode 100644 spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java create mode 100644 spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java diff --git a/spring-caching/pom.xml b/spring-caching/pom.xml index c3ededbd14..d33f24de1f 100644 --- a/spring-caching/pom.xml +++ b/spring-caching/pom.xml @@ -19,6 +19,10 @@ org.springframework spring-context + + org.springframework.boot + spring-boot-starter-cache + org.springframework spring-web diff --git a/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java b/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java new file mode 100644 index 0000000000..714dc443e0 --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/caching/boot/CacheApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.caching.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; + +@SpringBootApplication +@EnableCaching +public class CacheApplication { + + public static void main(String[] args) { + SpringApplication.run(CacheApplication.class, args); + } +} diff --git a/spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java b/spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java new file mode 100644 index 0000000000..a76a01caae --- /dev/null +++ b/spring-caching/src/main/java/com/baeldung/caching/boot/SimpleCacheCustomizer.java @@ -0,0 +1,24 @@ +package com.baeldung.caching.boot; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.cache.CacheManagerCustomizer; +import org.springframework.cache.concurrent.ConcurrentMapCacheManager; +import org.springframework.stereotype.Component; + +import static java.util.Arrays.asList; + +@Component +public class SimpleCacheCustomizer implements CacheManagerCustomizer { + + private static final Logger LOGGER = LoggerFactory.getLogger(SimpleCacheCustomizer.class); + + static final String USERS_CACHE = "users"; + static final String TRANSACTIONS_CACHE = "transactions"; + + @Override + public void customize(ConcurrentMapCacheManager cacheManager) { + LOGGER.info("Customizing Cache Manager"); + cacheManager.setCacheNames(asList(USERS_CACHE, TRANSACTIONS_CACHE)); + } +} diff --git a/spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java b/spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java new file mode 100644 index 0000000000..56a4bd4745 --- /dev/null +++ b/spring-caching/src/test/java/com/baeldung/caching/boot/SimpleCacheCustomizerIntegrationTest.java @@ -0,0 +1,24 @@ +package com.baeldung.caching.boot; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cache.CacheManager; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SimpleCacheCustomizerIntegrationTest { + + @Autowired + private CacheManager cacheManager; + + @Test + public void givenCacheManagerCustomizerWhenBootstrappedThenCacheManagerCustomized() { + assertThat(cacheManager.getCacheNames()) + .containsOnly(SimpleCacheCustomizer.USERS_CACHE, SimpleCacheCustomizer.TRANSACTIONS_CACHE); + } +} \ No newline at end of file From f154a172398ed6d3b8aa5cda91ad5d3cad08cde6 Mon Sep 17 00:00:00 2001 From: "ramprasad.devarakonda@gmail.com" Date: Tue, 24 Mar 2020 00:55:23 +0000 Subject: [PATCH 159/187] BAEL-3769 | Writing templates for test cases using JUnit 5 --- testing-modules/junit5-annotations/pom.xml | 9 +- .../junit5/templates/UserIdGenerator.java | 5 ++ .../junit5/templates/UserIdGeneratorImpl.java | 15 ++++ .../DisabledOnQAEnvironmentExtension.java | 27 ++++++ .../GenericTypedParameterResolver.java | 26 ++++++ .../UserIdGeneratorImplUnitTest.java | 18 ++++ .../templates/UserIdGeneratorTestCase.java | 37 ++++++++ ...eneratorTestInvocationContextProvider.java | 87 +++++++++++++++++++ .../src/test/resources/application.properties | 1 + 9 files changed, 224 insertions(+), 1 deletion(-) create mode 100644 testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGenerator.java create mode 100644 testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGeneratorImpl.java create mode 100644 testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/DisabledOnQAEnvironmentExtension.java create mode 100644 testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/GenericTypedParameterResolver.java create mode 100644 testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorImplUnitTest.java create mode 100644 testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestCase.java create mode 100644 testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestInvocationContextProvider.java create mode 100644 testing-modules/junit5-annotations/src/test/resources/application.properties diff --git a/testing-modules/junit5-annotations/pom.xml b/testing-modules/junit5-annotations/pom.xml index d0fba4d21b..9e51d0ab55 100644 --- a/testing-modules/junit5-annotations/pom.xml +++ b/testing-modules/junit5-annotations/pom.xml @@ -46,12 +46,19 @@ ${junit.platform.version} test + + org.assertj + assertj-core + ${assertj-core.version} + test + - 5.6.0 + 5.6.2 1.6.0 2.8.2 + 3.11.1 diff --git a/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGenerator.java b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGenerator.java new file mode 100644 index 0000000000..f19adb13c8 --- /dev/null +++ b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGenerator.java @@ -0,0 +1,5 @@ +package com.baeldung.junit5.templates; + +public interface UserIdGenerator { + String generate(String firstName, String lastName); +} diff --git a/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGeneratorImpl.java b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGeneratorImpl.java new file mode 100644 index 0000000000..b39b07bc4b --- /dev/null +++ b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/templates/UserIdGeneratorImpl.java @@ -0,0 +1,15 @@ +package com.baeldung.junit5.templates; + +public class UserIdGeneratorImpl implements UserIdGenerator { + private boolean isFeatureEnabled; + + public UserIdGeneratorImpl(boolean isFeatureEnabled) { + this.isFeatureEnabled = isFeatureEnabled; + } + + public String generate(String firstName, String lastName) { + String initialAndLastName = firstName.substring(0, 1) + .concat(lastName); + return isFeatureEnabled ? "bael".concat(initialAndLastName) : initialAndLastName; + } +} diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/DisabledOnQAEnvironmentExtension.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/DisabledOnQAEnvironmentExtension.java new file mode 100644 index 0000000000..cd8b7b677d --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/DisabledOnQAEnvironmentExtension.java @@ -0,0 +1,27 @@ +package com.baeldung.junit5.templates; + +import org.junit.jupiter.api.extension.ConditionEvaluationResult; +import org.junit.jupiter.api.extension.ExecutionCondition; +import org.junit.jupiter.api.extension.ExtensionContext; + +import java.io.IOException; +import java.util.Properties; + +public class DisabledOnQAEnvironmentExtension implements ExecutionCondition { + @Override + public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { + Properties properties = new Properties(); + try { + properties.load(DisabledOnQAEnvironmentExtension.class.getClassLoader() + .getResourceAsStream("application.properties")); + if ("qa".equalsIgnoreCase(properties.getProperty("env"))) { + String reason = String.format("The test '%s' is disabled on QA environment", context.getDisplayName()); + System.out.println(reason); + return ConditionEvaluationResult.disabled(reason); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + return ConditionEvaluationResult.enabled("Test enabled"); + } +} \ No newline at end of file diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/GenericTypedParameterResolver.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/GenericTypedParameterResolver.java new file mode 100644 index 0000000000..76321be101 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/GenericTypedParameterResolver.java @@ -0,0 +1,26 @@ +package com.baeldung.junit5.templates; + +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ParameterContext; +import org.junit.jupiter.api.extension.ParameterResolutionException; +import org.junit.jupiter.api.extension.ParameterResolver; + +public class GenericTypedParameterResolver implements ParameterResolver { + T data; + + public GenericTypedParameterResolver(T data) { + this.data = data; + } + + @Override + public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + return parameterContext.getParameter() + .getType() + .isInstance(data); + } + + @Override + public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { + return data; + } +} diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorImplUnitTest.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorImplUnitTest.java new file mode 100644 index 0000000000..a2306154a6 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorImplUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.junit5.templates; + +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; + +import static org.assertj.core.api.Assertions.assertThat; + +public class UserIdGeneratorImplUnitTest { + @TestTemplate + @ExtendWith(UserIdGeneratorTestInvocationContextProvider.class) + public void whenUserIdRequested_thenUserIdIsReturnedInCorrectFormat(UserIdGeneratorTestCase testCase) { + UserIdGenerator userIdGenerator = new UserIdGeneratorImpl(testCase.isFeatureEnabled()); + + String actualUserId = userIdGenerator.generate(testCase.getFirstName(), testCase.getLastName()); + + assertThat(actualUserId).isEqualTo(testCase.getExpectedUserId()); + } +} \ No newline at end of file diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestCase.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestCase.java new file mode 100644 index 0000000000..dd41dd5a27 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestCase.java @@ -0,0 +1,37 @@ +package com.baeldung.junit5.templates; + +public class UserIdGeneratorTestCase { + private String displayName; + private boolean isFeatureEnabled; + private String firstName; + private String lastName; + private String expectedUserId; + + public UserIdGeneratorTestCase(String displayName, boolean isFeatureEnabled, String firstName, String lastName, String expectedUserId) { + this.displayName = displayName; + this.isFeatureEnabled = isFeatureEnabled; + this.firstName = firstName; + this.lastName = lastName; + this.expectedUserId = expectedUserId; + } + + public String getDisplayName() { + return displayName; + } + + public boolean isFeatureEnabled() { + return isFeatureEnabled; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public String getExpectedUserId() { + return expectedUserId; + } +} diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestInvocationContextProvider.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestInvocationContextProvider.java new file mode 100644 index 0000000000..277ec03f05 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/templates/UserIdGeneratorTestInvocationContextProvider.java @@ -0,0 +1,87 @@ +package com.baeldung.junit5.templates; + +import org.junit.jupiter.api.extension.*; + +import java.util.List; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class UserIdGeneratorTestInvocationContextProvider implements TestTemplateInvocationContextProvider { + + @Override + public boolean supportsTestTemplate(ExtensionContext extensionContext) { + return true; + } + + @Override + public Stream provideTestTemplateInvocationContexts(ExtensionContext extensionContext) { + boolean featureDisabled = false; + boolean featureEnabled = true; + return Stream.of( + featureDisabledContext( + new UserIdGeneratorTestCase( + "Given feature switch disabled When user name is John Smith Then generated userid is JSmith", + featureDisabled, "John", "Smith", "JSmith")), + featureEnabledContext( + new UserIdGeneratorTestCase( + "Given feature switch enabled When user name is John Smith Then generated userid is baelJSmith", + featureEnabled, "John", "Smith", "baelJSmith")) + ); + } + + private TestTemplateInvocationContext featureDisabledContext(UserIdGeneratorTestCase userIdGeneratorTestCase) { + return new TestTemplateInvocationContext() { + @Override + public String getDisplayName(int invocationIndex) { + return userIdGeneratorTestCase.getDisplayName(); + } + + @Override + public List getAdditionalExtensions() { + return asList( + new GenericTypedParameterResolver(userIdGeneratorTestCase), + new BeforeTestExecutionCallback() { + @Override + public void beforeTestExecution(ExtensionContext extensionContext) { + System.out.println("BeforeTestExecutionCallback:Disabled context"); + } + }, + new AfterTestExecutionCallback() { + @Override + public void afterTestExecution(ExtensionContext extensionContext) { + System.out.println("AfterTestExecutionCallback:Disabled context"); + } + }); + } + }; + } + + private TestTemplateInvocationContext featureEnabledContext(UserIdGeneratorTestCase userIdGeneratorTestCase) { + return new TestTemplateInvocationContext() { + @Override + public String getDisplayName(int invocationIndex) { + return userIdGeneratorTestCase.getDisplayName(); + } + + @Override + public List getAdditionalExtensions() { + return asList( + new GenericTypedParameterResolver(userIdGeneratorTestCase), + new DisabledOnQAEnvironmentExtension(), + new BeforeEachCallback() { + @Override + public void beforeEach(ExtensionContext extensionContext) { + System.out.println("BeforeEachCallback:Enabled context"); + } + }, + new AfterEachCallback() { + @Override + public void afterEach(ExtensionContext extensionContext) { + System.out.println("AfterEachCallback:Enabled context"); + } + }); + } + }; + } +} diff --git a/testing-modules/junit5-annotations/src/test/resources/application.properties b/testing-modules/junit5-annotations/src/test/resources/application.properties new file mode 100644 index 0000000000..bbfa14d866 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/resources/application.properties @@ -0,0 +1 @@ +env=qa \ No newline at end of file From 552c1d805b281c6c575b269892e58d9b13d84b5b Mon Sep 17 00:00:00 2001 From: patkorek Date: Sat, 11 Apr 2020 14:39:36 +0200 Subject: [PATCH 160/187] Moved to com.baeldung.stringtoint package. --- .../baeldung/{strings => stringtoint}/ConvertStringToInt.groovy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename core-groovy/src/test/groovy/com/baeldung/{strings => stringtoint}/ConvertStringToInt.groovy (98%) diff --git a/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy b/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy similarity index 98% rename from core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy rename to core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy index 7a4be4a957..48cf48fa8a 100644 --- a/core-groovy/src/test/groovy/com/baeldung/strings/ConvertStringToInt.groovy +++ b/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy @@ -1,4 +1,4 @@ -package com.baeldung.strings +package com.baeldung.stringtoint import org.junit.Test From 3bdfd8f72681b94c3ca21bea00bf039a387d89dd Mon Sep 17 00:00:00 2001 From: dupirefr Date: Sat, 11 Apr 2020 18:16:13 +0200 Subject: [PATCH 161/187] [JAVA-1265] Review build time * Migrate UserMapperUnitTest to UserMapperIntegrationTest as it uses Spring and takes a lot of time to execute --- jhipster-5/bookstore-monolith/pom.xml | 4 ++-- ...UserMapperUnitTest.java => UserMapperIntegrationTest.java} | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) rename jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/{UserMapperUnitTest.java => UserMapperIntegrationTest.java} (99%) diff --git a/jhipster-5/bookstore-monolith/pom.xml b/jhipster-5/bookstore-monolith/pom.xml index 5eaf761921..233765e0f3 100644 --- a/jhipster-5/bookstore-monolith/pom.xml +++ b/jhipster-5/bookstore-monolith/pom.xml @@ -7,7 +7,7 @@ 0.0.1-SNAPSHOT war Bookstore - + jhipster-5 com.baeldung.jhipster @@ -982,7 +982,7 @@ com.github.eirslett - frontend-maven-plugin + frontend-maven-plugin ${frontend-maven-plugin.version} install-node-and-npm diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperUnitTest.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperIntegrationTest.java similarity index 99% rename from jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperUnitTest.java rename to jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperIntegrationTest.java index cd6a326c06..cd49135d63 100644 --- a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperUnitTest.java +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/service/mapper/UserMapperIntegrationTest.java @@ -26,7 +26,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @SpringBootTest(classes = BookstoreApp.class) -public class UserMapperUnitTest { +public class UserMapperIntegrationTest { private static final String DEFAULT_LOGIN = "johndoe"; From bbae9153a8cb2fe1179736acb4fb38ede9e80e78 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Sat, 11 Apr 2020 22:39:52 +0530 Subject: [PATCH 162/187] Disabling JWS module --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 8d4632fb3e..b3d949d495 100644 --- a/pom.xml +++ b/pom.xml @@ -803,7 +803,7 @@ jenkins/plugins jhipster - jws + libraries @@ -1296,7 +1296,7 @@ jenkins/plugins jhipster - jws + libraries From 4a83c738350acd32e9c6d2035dce0a91238be503 Mon Sep 17 00:00:00 2001 From: Kumar Chandrakant Date: Sun, 12 Apr 2020 10:06:34 +0530 Subject: [PATCH 163/187] Adding codebase for the article tracked under BAEL-2046. (#9055) --- atomikos/README.md | 7 ++ atomikos/pom.xml | 119 ++++++++++++++++++ .../baeldung/atomikos/direct/Application.java | 53 ++++++++ .../baeldung/atomikos/spring/Application.java | 41 ++++++ .../atomikos/spring/config/Config.java | 68 ++++++++++ .../atomikos/spring/jpa/Application.java | 48 +++++++ .../atomikos/spring/jpa/config/Config.java | 38 ++++++ .../spring/jpa/inventory/Inventory.java | 31 +++++ .../spring/jpa/inventory/InventoryConfig.java | 53 ++++++++ .../jpa/inventory/InventoryRepository.java | 9 ++ .../atomikos/spring/jpa/order/Order.java | 42 +++++++ .../spring/jpa/order/OrderConfig.java | 53 ++++++++ .../spring/jpa/order/OrderRepository.java | 9 ++ atomikos/src/main/resources/logback.xml | 13 ++ atomikos/src/main/resources/schema.sql | 10 ++ .../main/resources/transactions.properties | 1 + .../atomikos/direct/ApplicationUnitTest.java | 118 +++++++++++++++++ .../atomikos/spring/ApplicationUnitTest.java | 108 ++++++++++++++++ .../spring/jpa/ApplicationUnitTest.java | 80 ++++++++++++ atomikos/src/test/resources/logback.xml | 13 ++ .../test/resources/transactions.properties | 1 + pom.xml | 4 + 22 files changed, 919 insertions(+) create mode 100644 atomikos/README.md create mode 100644 atomikos/pom.xml create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java create mode 100644 atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java create mode 100644 atomikos/src/main/resources/logback.xml create mode 100644 atomikos/src/main/resources/schema.sql create mode 100644 atomikos/src/main/resources/transactions.properties create mode 100644 atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java create mode 100644 atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java create mode 100644 atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java create mode 100644 atomikos/src/test/resources/logback.xml create mode 100644 atomikos/src/test/resources/transactions.properties diff --git a/atomikos/README.md b/atomikos/README.md new file mode 100644 index 0000000000..19f2e871d4 --- /dev/null +++ b/atomikos/README.md @@ -0,0 +1,7 @@ +## Atomikos + +This module contains articles about Atomikos + +### Relevant Articles: + +- [Guide Transactions Using Atomikos]() diff --git a/atomikos/pom.xml b/atomikos/pom.xml new file mode 100644 index 0000000000..881adae074 --- /dev/null +++ b/atomikos/pom.xml @@ -0,0 +1,119 @@ + + + 4.0.0 + atomikos + atomikos + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + com.atomikos + transactions-jdbc + ${atomikos-version} + + + com.atomikos + transactions-jms + ${atomikos-version} + + + com.atomikos + transactions-hibernate4 + ${atomikos-version} + + + org.springframework + spring-context + ${spring-version} + + + org.springframework + spring-tx + ${spring-version} + + + org.springframework.data + spring-data-jpa + 1.11.23.RELEASE + + + org.springframework + spring-test + ${spring-version} + test + + + org.hibernate + hibernate-entitymanager + ${hibernate.version} + provided + + + javax.transaction + jta + + + + + org.apache.activemq + activemq-core + 5.7.0 + + + org.apache.derby + derby + 10.8.1.2 + + + junit + junit + 4.12 + test + + + + javax.transaction + jta + 1.1 + + + org.apache.geronimo.specs + geronimo-jta_1.0.1B_spec + 1.0 + + + javax.validation + validation-api + 2.0.1.Final + + + org.hibernate.validator + hibernate-validator + 6.1.2.Final + + + javax.el + javax.el-api + 3.0.0 + + + org.glassfish.web + javax.el + 2.2.4 + + + + + 5.0.6 + 5.1.6.RELEASE + 5.4.3.Final + + + \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java b/atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java new file mode 100644 index 0000000000..c51ce70dde --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/direct/Application.java @@ -0,0 +1,53 @@ +package com.baeldung.atomikos.direct; + +import java.sql.Connection; +import java.sql.Statement; +import java.util.UUID; + +import javax.sql.DataSource; + +import com.atomikos.icatch.jta.UserTransactionImp; + +public class Application { + + private DataSource inventoryDataSource; + private DataSource orderDataSource; + + public Application(DataSource inventoryDataSource, DataSource orderDataSource) { + this.inventoryDataSource = inventoryDataSource; + this.orderDataSource = orderDataSource; + } + + public void placeOrder(String productId, int amount) throws Exception { + + UserTransactionImp utx = new UserTransactionImp(); + String orderId = UUID.randomUUID() + .toString(); + boolean rollback = false; + try { + utx.begin(); + Connection inventoryConnection = inventoryDataSource.getConnection(); + Connection orderConnection = orderDataSource.getConnection(); + Statement s1 = inventoryConnection.createStatement(); + String q1 = "update Inventory set balance = balance - " + amount + " where productId ='" + productId + "'"; + s1.executeUpdate(q1); + s1.close(); + Statement s2 = orderConnection.createStatement(); + String q2 = "insert into Orders values ( '" + orderId + "', '" + productId + "', " + amount + " )"; + s2.executeUpdate(q2); + s2.close(); + inventoryConnection.close(); + orderConnection.close(); + } catch (Exception e) { + System.out.println(e.getMessage()); + rollback = true; + } finally { + if (!rollback) + utx.commit(); + else + utx.rollback(); + } + + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java new file mode 100644 index 0000000000..b480e68d8d --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/Application.java @@ -0,0 +1,41 @@ +package com.baeldung.atomikos.spring; + +import java.sql.Connection; +import java.sql.Statement; +import java.util.UUID; + +import javax.sql.DataSource; + +import org.springframework.transaction.annotation.Transactional; + +public class Application { + + private DataSource inventoryDataSource; + private DataSource orderDataSource; + + public Application(DataSource inventoryDataSource, DataSource orderDataSource) { + this.inventoryDataSource = inventoryDataSource; + this.orderDataSource = orderDataSource; + } + + @Transactional(rollbackFor = Exception.class) + public void placeOrder(String productId, int amount) throws Exception { + + String orderId = UUID.randomUUID() + .toString(); + Connection inventoryConnection = inventoryDataSource.getConnection(); + Connection orderConnection = orderDataSource.getConnection(); + Statement s1 = inventoryConnection.createStatement(); + String q1 = "update Inventory set balance = balance - " + amount + " where productId ='" + productId + "'"; + s1.executeUpdate(q1); + s1.close(); + Statement s2 = orderConnection.createStatement(); + String q2 = "insert into Orders values ( '" + orderId + "', '" + productId + "', " + amount + " )"; + s2.executeUpdate(q2); + s2.close(); + inventoryConnection.close(); + orderConnection.close(); + + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java new file mode 100644 index 0000000000..c6ef83c4ca --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/config/Config.java @@ -0,0 +1,68 @@ +package com.baeldung.atomikos.spring.config; + +import java.util.Properties; + +import javax.transaction.SystemException; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.transaction.jta.JtaTransactionManager; + +import com.atomikos.icatch.jta.UserTransactionManager; +import com.atomikos.jdbc.AtomikosDataSourceBean; +import com.baeldung.atomikos.spring.Application; + +@Configuration +@EnableTransactionManagement +public class Config { + + @Bean(initMethod = "init", destroyMethod = "close") + public AtomikosDataSourceBean inventoryDataSource() { + AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean(); + dataSource.setLocalTransactionMode(true); + dataSource.setUniqueResourceName("db1"); + dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties xaProperties = new Properties(); + xaProperties.put("databaseName", "db1"); + xaProperties.put("createDatabase", "create"); + dataSource.setXaProperties(xaProperties); + dataSource.setPoolSize(10); + return dataSource; + } + + @Bean(initMethod = "init", destroyMethod = "close") + public AtomikosDataSourceBean orderDataSource() { + AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean(); + dataSource.setLocalTransactionMode(true); + dataSource.setUniqueResourceName("db2"); + dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties xaProperties = new Properties(); + xaProperties.put("databaseName", "db2"); + xaProperties.put("createDatabase", "create"); + dataSource.setXaProperties(xaProperties); + dataSource.setPoolSize(10); + return dataSource; + } + + @Bean(initMethod = "init", destroyMethod = "close") + public UserTransactionManager userTransactionManager() throws SystemException { + UserTransactionManager userTransactionManager = new UserTransactionManager(); + userTransactionManager.setTransactionTimeout(300); + userTransactionManager.setForceShutdown(true); + return userTransactionManager; + } + + @Bean + public JtaTransactionManager jtaTransactionManager() throws SystemException { + JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(); + jtaTransactionManager.setTransactionManager(userTransactionManager()); + jtaTransactionManager.setUserTransaction(userTransactionManager()); + return jtaTransactionManager; + } + + @Bean + public Application application() { + return new Application(inventoryDataSource(), orderDataSource()); + } +} \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java new file mode 100644 index 0000000000..cf1fef2cd8 --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/Application.java @@ -0,0 +1,48 @@ +package com.baeldung.atomikos.spring.jpa; + +import java.util.Set; +import java.util.UUID; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.atomikos.spring.jpa.inventory.Inventory; +import com.baeldung.atomikos.spring.jpa.inventory.InventoryRepository; +import com.baeldung.atomikos.spring.jpa.order.Order; +import com.baeldung.atomikos.spring.jpa.order.OrderRepository; + +public class Application { + + @Autowired + private InventoryRepository inventoryRepository; + + @Autowired + private OrderRepository orderRepository; + + @Transactional(rollbackFor = Exception.class) + public void placeOrder(String productId, int amount) throws Exception { + + String orderId = UUID.randomUUID() + .toString(); + Inventory inventory = inventoryRepository.findOne(productId); + inventory.setBalance(inventory.getBalance() - amount); + inventoryRepository.save(inventory); + Order order = new Order(); + order.setOrderId(orderId); + order.setProductId(productId); + order.setAmount(new Long(amount)); + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + Validator validator = factory.getValidator(); + Set> violations = validator.validate(order); + if (violations.size() > 0) + throw new Exception("Invalid instance of an order."); + orderRepository.save(order); + + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java new file mode 100644 index 0000000000..6716f19576 --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/config/Config.java @@ -0,0 +1,38 @@ +package com.baeldung.atomikos.spring.jpa.config; + +import javax.transaction.SystemException; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.transaction.jta.JtaTransactionManager; + +import com.atomikos.icatch.jta.UserTransactionManager; +import com.baeldung.atomikos.spring.jpa.Application; + +@Configuration +@EnableTransactionManagement +public class Config { + + @Bean(initMethod = "init", destroyMethod = "close") + public UserTransactionManager userTransactionManager() throws SystemException { + UserTransactionManager userTransactionManager = new UserTransactionManager(); + userTransactionManager.setTransactionTimeout(300); + userTransactionManager.setForceShutdown(true); + return userTransactionManager; + } + + @Bean + public JtaTransactionManager transactionManager() throws SystemException { + JtaTransactionManager jtaTransactionManager = new JtaTransactionManager(); + jtaTransactionManager.setTransactionManager(userTransactionManager()); + jtaTransactionManager.setUserTransaction(userTransactionManager()); + return jtaTransactionManager; + } + + @Bean + public Application application() { + return new Application(); + } + +} \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java new file mode 100644 index 0000000000..999879218c --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/Inventory.java @@ -0,0 +1,31 @@ +package com.baeldung.atomikos.spring.jpa.inventory; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "INVENTORY") +public class Inventory { + + @Id + private String productId; + private Long balance; + + public String getProductId() { + return productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public Long getBalance() { + return balance; + } + + public void setBalance(Long balance) { + this.balance = balance; + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java new file mode 100644 index 0000000000..5301ad6ff2 --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryConfig.java @@ -0,0 +1,53 @@ +package com.baeldung.atomikos.spring.jpa.inventory; + +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; + +import com.atomikos.jdbc.AtomikosDataSourceBean; + +@Configuration +@EnableJpaRepositories(basePackages = "com.baeldung.atomikos.spring.jpa.inventory", entityManagerFactoryRef = "inventoryEntityManager", transactionManagerRef = "transactionManager") +public class InventoryConfig { + + @Bean(initMethod = "init", destroyMethod = "close") + public AtomikosDataSourceBean inventoryDataSource() { + AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean(); + dataSource.setLocalTransactionMode(true); + dataSource.setUniqueResourceName("db1"); + dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties xaProperties = new Properties(); + xaProperties.put("databaseName", "db1"); + xaProperties.put("createDatabase", "create"); + dataSource.setXaProperties(xaProperties); + dataSource.setPoolSize(10); + return dataSource; + } + + @Bean + public EntityManagerFactory inventoryEntityManager() { + HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); + factory.setJpaVendorAdapter(vendorAdapter); + factory.setPackagesToScan("com.baeldung.atomikos.spring.jpa.inventory"); + factory.setDataSource(inventoryDataSource()); + Properties jpaProperties = new Properties(); + //jpaProperties.put("hibernate.show_sql", "true"); + //jpaProperties.put("hibernate.format_sql", "true"); + jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.DerbyDialect"); + jpaProperties.put("hibernate.current_session_context_class", "jta"); + jpaProperties.put("javax.persistence.transactionType", "jta"); + jpaProperties.put("hibernate.transaction.manager_lookup_class", "com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup"); + jpaProperties.put("hibernate.hbm2ddl.auto", "create-drop"); + factory.setJpaProperties(jpaProperties); + factory.afterPropertiesSet(); + return factory.getObject(); + } + +} \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java new file mode 100644 index 0000000000..c3868e51bf --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/inventory/InventoryRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.atomikos.spring.jpa.inventory; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface InventoryRepository extends JpaRepository { + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java new file mode 100644 index 0000000000..4b9ae2dd1d --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/Order.java @@ -0,0 +1,42 @@ +package com.baeldung.atomikos.spring.jpa.order; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.validation.constraints.Max; + +@Entity +@Table(name = "ORDERS") +public class Order { + + @Id + private String orderId; + private String productId; + @Max(5) + private Long amount; + + public String getOrderId() { + return orderId; + } + + public void setOrderId(String orderId) { + this.orderId = orderId; + } + + public String getProductId() { + return productId; + } + + public void setProductId(String productId) { + this.productId = productId; + } + + public Long getAmount() { + return amount; + } + + public void setAmount(Long amount) { + this.amount = amount; + } + +} diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java new file mode 100644 index 0000000000..b4274bb64c --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderConfig.java @@ -0,0 +1,53 @@ +package com.baeldung.atomikos.spring.jpa.order; + +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; + +import com.atomikos.jdbc.AtomikosDataSourceBean; + +@Configuration +@EnableJpaRepositories(basePackages = "com.baeldung.atomikos.spring.jpa.order", entityManagerFactoryRef = "orderEntityManager", transactionManagerRef = "transactionManager") +public class OrderConfig { + + @Bean(initMethod = "init", destroyMethod = "close") + public AtomikosDataSourceBean orderDataSource() { + AtomikosDataSourceBean dataSource = new AtomikosDataSourceBean(); + dataSource.setLocalTransactionMode(true); + dataSource.setUniqueResourceName("db2"); + dataSource.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties xaProperties = new Properties(); + xaProperties.put("databaseName", "db2"); + xaProperties.put("createDatabase", "create"); + dataSource.setXaProperties(xaProperties); + dataSource.setPoolSize(10); + return dataSource; + } + + @Bean + public EntityManagerFactory orderEntityManager() { + HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); + factory.setJpaVendorAdapter(vendorAdapter); + factory.setPackagesToScan("com.baeldung.atomikos.spring.jpa.order"); + factory.setDataSource(orderDataSource()); + Properties jpaProperties = new Properties(); + //jpaProperties.put("hibernate.show_sql", "true"); + //jpaProperties.put("hibernate.format_sql", "true"); + jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.DerbyDialect"); + jpaProperties.put("hibernate.current_session_context_class", "jta"); + jpaProperties.put("javax.persistence.transactionType", "jta"); + jpaProperties.put("hibernate.transaction.manager_lookup_class", "com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup"); + jpaProperties.put("hibernate.hbm2ddl.auto", "create-drop"); + factory.setJpaProperties(jpaProperties); + factory.afterPropertiesSet(); + return factory.getObject(); + } + +} \ No newline at end of file diff --git a/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java new file mode 100644 index 0000000000..2d5610ebca --- /dev/null +++ b/atomikos/src/main/java/com/baeldung/atomikos/spring/jpa/order/OrderRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.atomikos.spring.jpa.order; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface OrderRepository extends JpaRepository { + +} diff --git a/atomikos/src/main/resources/logback.xml b/atomikos/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/atomikos/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/atomikos/src/main/resources/schema.sql b/atomikos/src/main/resources/schema.sql new file mode 100644 index 0000000000..5136ad1284 --- /dev/null +++ b/atomikos/src/main/resources/schema.sql @@ -0,0 +1,10 @@ +CREATE TABLE INVENTORY ( + productId VARCHAR PRIMARY KEY, + balance INT +); + +CREATE TABLE ORDERS ( + orderId VARCHAR PRIMARY KEY, + productId VARCHAR, + amount INT NOT NULL CHECK (amount <= 5) +); \ No newline at end of file diff --git a/atomikos/src/main/resources/transactions.properties b/atomikos/src/main/resources/transactions.properties new file mode 100644 index 0000000000..8e027032fa --- /dev/null +++ b/atomikos/src/main/resources/transactions.properties @@ -0,0 +1 @@ +com.atomikos.icatch.file=logs \ No newline at end of file diff --git a/atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java b/atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java new file mode 100644 index 0000000000..1a467807ba --- /dev/null +++ b/atomikos/src/test/java/com/baeldung/atomikos/direct/ApplicationUnitTest.java @@ -0,0 +1,118 @@ +package com.baeldung.atomikos.direct; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Properties; +import java.util.UUID; + +import javax.sql.DataSource; + +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import com.atomikos.icatch.jta.UserTransactionImp; +import com.atomikos.jdbc.AtomikosDataSourceBean; + +public class ApplicationUnitTest { + + private static DataSource inventoryDataSource; + private static DataSource orderDataSource; + + private static String productId = UUID.randomUUID() + .toString(); + + @Test + @Ignore + public void testPlaceOrderSuccess() throws Exception { + int amount = 1; + long initialBalance = getBalance(inventoryDataSource, productId); + Application application = new Application(inventoryDataSource, orderDataSource); + application.placeOrder(productId, amount); + long finalBalance = getBalance(inventoryDataSource, productId); + assertEquals(initialBalance - amount, finalBalance); + } + + @Test + @Ignore + public void testPlaceOrderFailure() throws Exception { + int amount = 10; + long initialBalance = getBalance(inventoryDataSource, productId); + Application application = new Application(inventoryDataSource, orderDataSource); + application.placeOrder(productId, amount); + long finalBalance = getBalance(inventoryDataSource, productId); + assertEquals(initialBalance, finalBalance); + } + + @BeforeClass + public static void setUp() throws SQLException { + + inventoryDataSource = getDataSource("db1"); + orderDataSource = getDataSource("db2"); + Connection inventoryConnection = inventoryDataSource.getConnection(); + Connection orderConnection = orderDataSource.getConnection(); + String createInventoryTable = "create table Inventory ( " + " productId VARCHAR ( 100 ) PRIMARY KEY, balance INT )"; + String createInventoryRow = "insert into Inventory values ( '" + productId + "', 10000 )"; + Statement s1 = inventoryConnection.createStatement(); + try { + s1.executeUpdate(createInventoryTable); + } catch (Exception e) { + System.out.println("Inventory table exists"); + } + try { + s1.executeUpdate(createInventoryRow); + } catch (Exception e) { + System.out.println("Product row exists"); + } + s1.close(); + String createOrderTable = "create table Orders ( orderId VARCHAR ( 100 ) PRIMARY KEY, productId VARCHAR ( 100 ), amount INT NOT NULL CHECK (amount <= 5) )"; + Statement s2 = orderConnection.createStatement(); + try { + s2.executeUpdate(createOrderTable); + } catch (Exception e) { + System.out.println("Orders table exists"); + } + s2.close(); + inventoryConnection.close(); + orderConnection.close(); + } + + private static DataSource getDataSource(String db) { + + DataSource ds; + AtomikosDataSourceBean ads = new AtomikosDataSourceBean(); + ads.setXaDataSourceClassName("org.apache.derby.jdbc.EmbeddedXADataSource"); + Properties properties = new Properties(); + properties.put("databaseName", db); + properties.put("createDatabase", "create"); + ads.setXaProperties(properties); + ads.setUniqueResourceName(db); + ads.setPoolSize(10); // optional + ads.setBorrowConnectionTimeout(10); // optional + ds = ads; + return ds; + + } + + private static long getBalance(DataSource inventoryDataSource, String productId) throws Exception { + + UserTransactionImp utx = new UserTransactionImp(); + utx.begin(); + Connection inventoryConnection = inventoryDataSource.getConnection(); + Statement s1 = inventoryConnection.createStatement(); + String q1 = "select balance from Inventory where productId='" + productId + "'"; + ResultSet rs1 = s1.executeQuery(q1); + if (rs1 == null || !rs1.next()) + throw new Exception("Product not found: " + productId); + long balance = rs1.getLong(1); + inventoryConnection.close(); + utx.commit(); + return balance; + + } + +} diff --git a/atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java b/atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java new file mode 100644 index 0000000000..0c9392eac4 --- /dev/null +++ b/atomikos/src/test/java/com/baeldung/atomikos/spring/ApplicationUnitTest.java @@ -0,0 +1,108 @@ +package com.baeldung.atomikos.spring; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.UUID; + +import javax.sql.DataSource; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.atomikos.spring.config.Config; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { Config.class }) +public class ApplicationUnitTest { + + private static String productId = UUID.randomUUID() + .toString(); + + @Autowired + Application application; + + @Autowired + DataSource inventoryDataSource; + + @Autowired + DataSource orderDataSource; + + @Test + @Ignore + public void testPlaceOrderSuccess() throws Exception { + int amount = 1; + long initialBalance = getBalance(inventoryDataSource, productId); + application.placeOrder(productId, amount); + long finalBalance = getBalance(inventoryDataSource, productId); + assertEquals(initialBalance - amount, finalBalance); + } + + @Test + @Ignore + public void testPlaceOrderFailure() throws Exception { + int amount = 10; + long initialBalance = getBalance(inventoryDataSource, productId); + try { + application.placeOrder(productId, amount); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + long finalBalance = getBalance(inventoryDataSource, productId); + assertEquals(initialBalance, finalBalance); + } + + @Before + public void setUp() throws SQLException { + + Connection inventoryConnection = inventoryDataSource.getConnection(); + Connection orderConnection = orderDataSource.getConnection(); + String createInventoryTable = "create table Inventory ( " + " productId VARCHAR ( 100 ) PRIMARY KEY, balance INT )"; + String createInventoryRow = "insert into Inventory values ( '" + productId + "', 10000 )"; + Statement s1 = inventoryConnection.createStatement(); + try { + s1.executeUpdate(createInventoryTable); + } catch (Exception e) { + System.out.println("Inventory table exists"); + } + try { + s1.executeUpdate(createInventoryRow); + } catch (Exception e) { + System.out.println("Product row exists"); + } + s1.close(); + String createOrderTable = "create table Orders ( orderId VARCHAR ( 100 ) PRIMARY KEY, productId VARCHAR ( 100 ), amount INT NOT NULL CHECK (amount <= 5) )"; + Statement s2 = orderConnection.createStatement(); + try { + s2.executeUpdate(createOrderTable); + } catch (Exception e) { + System.out.println("Orders table exists"); + } + s2.close(); + inventoryConnection.close(); + orderConnection.close(); + } + + private static long getBalance(DataSource inventoryDataSource, String productId) throws Exception { + + Connection inventoryConnection = inventoryDataSource.getConnection(); + Statement s1 = inventoryConnection.createStatement(); + String q1 = "select balance from Inventory where productId='" + productId + "'"; + ResultSet rs1 = s1.executeQuery(q1); + if (rs1 == null || !rs1.next()) + throw new Exception("Product not found: " + productId); + long balance = rs1.getLong(1); + inventoryConnection.close(); + return balance; + + } + +} diff --git a/atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java b/atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java new file mode 100644 index 0000000000..e6a3c1982c --- /dev/null +++ b/atomikos/src/test/java/com/baeldung/atomikos/spring/jpa/ApplicationUnitTest.java @@ -0,0 +1,80 @@ +package com.baeldung.atomikos.spring.jpa; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.sql.SQLException; +import java.util.UUID; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.atomikos.spring.jpa.config.Config; +import com.baeldung.atomikos.spring.jpa.inventory.Inventory; +import com.baeldung.atomikos.spring.jpa.inventory.InventoryConfig; +import com.baeldung.atomikos.spring.jpa.inventory.InventoryRepository; +import com.baeldung.atomikos.spring.jpa.order.OrderConfig; +import com.baeldung.atomikos.spring.jpa.order.OrderRepository; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { Config.class, InventoryConfig.class, OrderConfig.class }) +public class ApplicationUnitTest { + + private static String productId = UUID.randomUUID() + .toString(); + + @Autowired + Application application; + + @Autowired + InventoryRepository inventoryRepository; + + @Autowired + OrderRepository orderRepository; + + @Test + @Ignore + public void testPlaceOrderSuccess() throws Exception { + int amount = 1; + long initialBalance = getBalance(inventoryRepository, productId); + application.placeOrder(productId, amount); + long finalBalance = getBalance(inventoryRepository, productId); + assertEquals(initialBalance - amount, finalBalance); + } + + @Test + @Ignore + public void testPlaceOrderFailure() throws Exception { + int amount = 10; + long initialBalance = getBalance(inventoryRepository, productId); + try { + application.placeOrder(productId, amount); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + long finalBalance = getBalance(inventoryRepository, productId); + assertEquals(initialBalance, finalBalance); + } + + @Before + public void setUp() throws SQLException { + + Inventory inventory = new Inventory(); + inventory.setProductId(productId); + inventory.setBalance(new Long(10000)); + inventoryRepository.save(inventory); + + } + + private static long getBalance(InventoryRepository inventoryRepository, String productId) throws Exception { + + return inventoryRepository.findOne(productId) + .getBalance(); + + } + +} diff --git a/atomikos/src/test/resources/logback.xml b/atomikos/src/test/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/atomikos/src/test/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/atomikos/src/test/resources/transactions.properties b/atomikos/src/test/resources/transactions.properties new file mode 100644 index 0000000000..8e027032fa --- /dev/null +++ b/atomikos/src/test/resources/transactions.properties @@ -0,0 +1 @@ +com.atomikos.icatch.file=logs \ No newline at end of file diff --git a/pom.xml b/pom.xml index 8d4632fb3e..8a8b8e1b55 100644 --- a/pom.xml +++ b/pom.xml @@ -564,6 +564,8 @@ rxjava-libraries rxjava-observables rxjava-operators + + atomikos @@ -1073,6 +1075,8 @@ rxjava-libraries rxjava-observables rxjava-operators + + atomikos From 40f2f2ea8a431fa6e675ce6d31900f515ea55e31 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Thu, 26 Mar 2020 12:29:05 +0200 Subject: [PATCH 164/187] BAEL-3926 - Java Map with case-insensitive keys --- .../core-java-collections-maps/pom.xml | 7 ++++ .../map/CaseInsensitiveMapUnitTest.java | 37 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java diff --git a/core-java-modules/core-java-collections-maps/pom.xml b/core-java-modules/core-java-collections-maps/pom.xml index c0dd705c1c..b459213e17 100644 --- a/core-java-modules/core-java-collections-maps/pom.xml +++ b/core-java-modules/core-java-collections-maps/pom.xml @@ -26,10 +26,17 @@ ${assertj.version} test + + org.springframework + spring-core + ${spring.version} + test + 4.1 3.6.1 + 5.2.5.RELEASE diff --git a/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java new file mode 100644 index 0000000000..a2171aa326 --- /dev/null +++ b/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.map; + +import org.apache.commons.collections4.map.CaseInsensitiveMap; +import org.junit.Test; +import org.springframework.util.LinkedCaseInsensitiveMap; +import static org.junit.Assert.*; + +import java.util.TreeMap; + +public class CaseInsensitiveMapUnitTest { + @Test + public void givenCaseInsensitiveTreeMap_whenTwoEntriesAdded_thenSizeIsOne(){ + TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + treeMap.put("abc", 1); + treeMap.put("ABC", 2); + + assertEquals(treeMap.size(), 1); + } + + @Test + public void givenCommonsCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ + CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + commonsHashMap.put("abc", 1); + commonsHashMap.put("ABC", 2); + + assertEquals(commonsHashMap.get("aBc"), (Integer)2); + } + + @Test + public void givenLinkedCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ + LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + linkedHashMap.put("abc", 3); + linkedHashMap.remove("aBC"); + + assertEquals(linkedHashMap.size(), 0); + } +} From 7d9d3c5f607260be7a466600bb09b9926a252770 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Sat, 28 Mar 2020 17:50:20 +0300 Subject: [PATCH 165/187] new module has been added --- .../core-java-collections-maps/pom.xml | 7 ---- java-collections-maps-3/README.md | 8 ++++ java-collections-maps-3/pom.xml | 39 +++++++++++++++++++ .../CaseInsensitiveMapUnitTest.java | 7 ++-- pom.xml | 10 ++++- 5 files changed, 59 insertions(+), 12 deletions(-) create mode 100644 java-collections-maps-3/README.md create mode 100644 java-collections-maps-3/pom.xml rename {java-collections-maps/src/test/java/com/baeldung/map => java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys}/CaseInsensitiveMapUnitTest.java (84%) diff --git a/core-java-modules/core-java-collections-maps/pom.xml b/core-java-modules/core-java-collections-maps/pom.xml index b459213e17..c0dd705c1c 100644 --- a/core-java-modules/core-java-collections-maps/pom.xml +++ b/core-java-modules/core-java-collections-maps/pom.xml @@ -26,17 +26,10 @@ ${assertj.version} test - - org.springframework - spring-core - ${spring.version} - test - 4.1 3.6.1 - 5.2.5.RELEASE diff --git a/java-collections-maps-3/README.md b/java-collections-maps-3/README.md new file mode 100644 index 0000000000..9df666296b --- /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 Map With Case-Insensitive Keys](https://www.baeldung.com/java-map-case-insensitive-keys) +- More articles: [[<-- prev>]](/../java-collections-maps) +- 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..0dd915c87b --- /dev/null +++ b/java-collections-maps-3/pom.xml @@ -0,0 +1,39 @@ + + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + 4.0.0 + java-collections-maps-3 + + + + org.springframework + spring-core + ${spring.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + + + 4.1 + 3.6.1 + 5.2.5.RELEASE + + \ No newline at end of file diff --git a/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java similarity index 84% rename from java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java rename to java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index a2171aa326..b12080e368 100644 --- a/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -1,6 +1,7 @@ -package com.baeldung.map; +package com.baeldung.map.caseinsensitivekeys; import org.apache.commons.collections4.map.CaseInsensitiveMap; +import org.junit.Assert; import org.junit.Test; import org.springframework.util.LinkedCaseInsensitiveMap; import static org.junit.Assert.*; @@ -23,7 +24,7 @@ public class CaseInsensitiveMapUnitTest { commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); - assertEquals(commonsHashMap.get("aBc"), (Integer)2); + Assert.assertEquals(commonsHashMap.get("aBc"), (Integer)2); } @Test @@ -32,6 +33,6 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("abc", 3); linkedHashMap.remove("aBC"); - assertEquals(linkedHashMap.size(), 0); + Assert.assertEquals(linkedHashMap.size(), 0); } } diff --git a/pom.xml b/pom.xml index 8a8b8e1b55..cb0c0cf5d7 100644 --- a/pom.xml +++ b/pom.xml @@ -453,6 +453,9 @@ java-collections-conversions java-collections-conversions-2 + java-collections-maps + java-collections-maps-2 + java-collections-maps-3 javafx @@ -564,7 +567,7 @@ rxjava-libraries rxjava-observables rxjava-operators - + atomikos @@ -965,6 +968,9 @@ java-collections-conversions java-collections-conversions-2 + java-collections-maps + java-collections-maps-2 + java-collections-maps-3 javafx @@ -1075,7 +1081,7 @@ rxjava-libraries rxjava-observables rxjava-operators - + atomikos From 5137f8fa209d1a0c2f8847017cb959e0a6db69b1 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Sat, 28 Mar 2020 17:58:34 +0300 Subject: [PATCH 166/187] tests has been added and split --- .../CaseInsensitiveMapUnitTest.java | 63 ++++++++++++++++++- 1 file changed, 60 insertions(+), 3 deletions(-) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index b12080e368..b3653a97c2 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -15,7 +15,37 @@ public class CaseInsensitiveMapUnitTest { treeMap.put("abc", 1); treeMap.put("ABC", 2); - assertEquals(treeMap.size(), 1); + assertEquals(1, treeMap.size()); + + } + + @Test + public void givenCommonsCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ + CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + commonsHashMap.put("abc", 1); + commonsHashMap.put("ABC", 2); + + assertEquals(1, commonsHashMap.size()); + + } + + @Test + public void givenLinkedCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ + LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + linkedHashMap.put("abc", 1); + linkedHashMap.put("ABC", 2); + + assertEquals(1, linkedHashMap.size()); + + } + + @Test + public void givenCaseInsensitiveTreeMap_whenSameEntryAdded_thenValueUpdated(){ + TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + treeMap.put("abc", 1); + treeMap.put("ABC", 2); + + Assert.assertEquals((Integer)2, treeMap.get("aBc")); } @Test @@ -24,7 +54,34 @@ public class CaseInsensitiveMapUnitTest { commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); - Assert.assertEquals(commonsHashMap.get("aBc"), (Integer)2); + Assert.assertEquals((Integer)2, commonsHashMap.get("aBc")); + } + + @Test + public void givenLinkedCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ + LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + linkedHashMap.put("abc", 1); + linkedHashMap.put("ABC", 2); + + Assert.assertEquals((Integer)2, linkedHashMap.get("aBc")); + } + + @Test + public void givenCaseInsensitiveTreeMap_whenEntryRemoved_thenSizeIsZero(){ + TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + treeMap.put("abc", 3); + treeMap.remove("aBC"); + + Assert.assertEquals(0, treeMap.size()); + } + + @Test + public void givenCommonsCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ + CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + commonsHashMap.put("abc", 3); + commonsHashMap.remove("aBC"); + + Assert.assertEquals(0, commonsHashMap.size()); } @Test @@ -33,6 +90,6 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("abc", 3); linkedHashMap.remove("aBC"); - Assert.assertEquals(linkedHashMap.size(), 0); + Assert.assertEquals(0, linkedHashMap.size()); } } From 9fc999311cdc4fa83b733631a4213b48728cb9d7 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Sat, 28 Mar 2020 22:41:07 +0300 Subject: [PATCH 167/187] tests has been added and split --- java-collections-maps-3/README.md | 2 +- .../CaseInsensitiveMapUnitTest.java | 29 +++++++++---------- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/java-collections-maps-3/README.md b/java-collections-maps-3/README.md index 9df666296b..ab6a37d00c 100644 --- a/java-collections-maps-3/README.md +++ b/java-collections-maps-3/README.md @@ -3,6 +3,6 @@ This module contains articles about Map data structures in Java. ### Relevant Articles: -- [Java Map With Case-Insensitive Keys](https://www.baeldung.com/java-map-case-insensitive-keys) +- [Java Map With Case-Insensitive Keys](https://www.baeldung.com/java-map-with-case-insensitive-keys/) - More articles: [[<-- prev>]](/../java-collections-maps) - More articles: [[<-- prev>]](/../java-collections-maps-2) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index b3653a97c2..82feef869a 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -1,17 +1,16 @@ package com.baeldung.map.caseinsensitivekeys; import org.apache.commons.collections4.map.CaseInsensitiveMap; -import org.junit.Assert; import org.junit.Test; import org.springframework.util.LinkedCaseInsensitiveMap; -import static org.junit.Assert.*; - +import java.util.Map; import java.util.TreeMap; +import static org.junit.Assert.*; public class CaseInsensitiveMapUnitTest { @Test public void givenCaseInsensitiveTreeMap_whenTwoEntriesAdded_thenSizeIsOne(){ - TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); treeMap.put("abc", 1); treeMap.put("ABC", 2); @@ -21,7 +20,7 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenCommonsCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ - CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + Map commonsHashMap = new CaseInsensitiveMap<>(); commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); @@ -41,20 +40,20 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenCaseInsensitiveTreeMap_whenSameEntryAdded_thenValueUpdated(){ - TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); treeMap.put("abc", 1); treeMap.put("ABC", 2); - Assert.assertEquals((Integer)2, treeMap.get("aBc")); + assertEquals((Integer)2, treeMap.get("aBc")); } @Test public void givenCommonsCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ - CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + Map commonsHashMap = new CaseInsensitiveMap<>(); commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); - Assert.assertEquals((Integer)2, commonsHashMap.get("aBc")); + assertEquals((Integer)2, commonsHashMap.get("aBc")); } @Test @@ -63,25 +62,25 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("abc", 1); linkedHashMap.put("ABC", 2); - Assert.assertEquals((Integer)2, linkedHashMap.get("aBc")); + assertEquals((Integer)2, linkedHashMap.get("aBc")); } @Test public void givenCaseInsensitiveTreeMap_whenEntryRemoved_thenSizeIsZero(){ - TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); treeMap.put("abc", 3); treeMap.remove("aBC"); - Assert.assertEquals(0, treeMap.size()); + assertEquals(0, treeMap.size()); } @Test public void givenCommonsCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ - CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + Map commonsHashMap = new CaseInsensitiveMap<>(); commonsHashMap.put("abc", 3); commonsHashMap.remove("aBC"); - Assert.assertEquals(0, commonsHashMap.size()); + assertEquals(0, commonsHashMap.size()); } @Test @@ -90,6 +89,6 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("abc", 3); linkedHashMap.remove("aBC"); - Assert.assertEquals(0, linkedHashMap.size()); + assertEquals(0, linkedHashMap.size()); } } From 640f8ce5d28cc78265d13e2f957895e36c7a719c Mon Sep 17 00:00:00 2001 From: omerfinger Date: Sat, 28 Mar 2020 22:50:07 +0300 Subject: [PATCH 168/187] varius get cases --- .../map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index 82feef869a..60dd1da9c0 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -45,6 +45,7 @@ public class CaseInsensitiveMapUnitTest { treeMap.put("ABC", 2); assertEquals((Integer)2, treeMap.get("aBc")); + assertEquals((Integer)2, treeMap.get("ABc")); } @Test @@ -54,6 +55,7 @@ public class CaseInsensitiveMapUnitTest { commonsHashMap.put("ABC", 2); assertEquals((Integer)2, commonsHashMap.get("aBc")); + assertEquals((Integer)2, commonsHashMap.get("ABc")); } @Test @@ -63,6 +65,7 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("ABC", 2); assertEquals((Integer)2, linkedHashMap.get("aBc")); + assertEquals((Integer)2, linkedHashMap.get("ABc")); } @Test From c2e37ce399ab221298a7914275a146c8ce23fb68 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Mon, 30 Mar 2020 13:28:29 +0300 Subject: [PATCH 169/187] changed README, assert has changed --- java-collections-maps-3/README.md | 2 +- .../CaseInsensitiveMapUnitTest.java | 14 ++++++-------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/java-collections-maps-3/README.md b/java-collections-maps-3/README.md index ab6a37d00c..ed68eb00a0 100644 --- a/java-collections-maps-3/README.md +++ b/java-collections-maps-3/README.md @@ -3,6 +3,6 @@ This module contains articles about Map data structures in Java. ### Relevant Articles: -- [Java Map With Case-Insensitive Keys](https://www.baeldung.com/java-map-with-case-insensitive-keys/) + - More articles: [[<-- prev>]](/../java-collections-maps) - More articles: [[<-- prev>]](/../java-collections-maps-2) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index 60dd1da9c0..37d9af7535 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -25,7 +25,6 @@ public class CaseInsensitiveMapUnitTest { commonsHashMap.put("ABC", 2); assertEquals(1, commonsHashMap.size()); - } @Test @@ -35,7 +34,6 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("ABC", 2); assertEquals(1, linkedHashMap.size()); - } @Test @@ -44,8 +42,8 @@ public class CaseInsensitiveMapUnitTest { treeMap.put("abc", 1); treeMap.put("ABC", 2); - assertEquals((Integer)2, treeMap.get("aBc")); - assertEquals((Integer)2, treeMap.get("ABc")); + assertEquals(2, treeMap.get("aBc").intValue()); + assertEquals(2, treeMap.get("ABc").intValue()); } @Test @@ -54,8 +52,8 @@ public class CaseInsensitiveMapUnitTest { commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); - assertEquals((Integer)2, commonsHashMap.get("aBc")); - assertEquals((Integer)2, commonsHashMap.get("ABc")); + assertEquals(2, commonsHashMap.get("aBc").intValue()); + assertEquals(2, commonsHashMap.get("ABc").intValue()); } @Test @@ -64,8 +62,8 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("abc", 1); linkedHashMap.put("ABC", 2); - assertEquals((Integer)2, linkedHashMap.get("aBc")); - assertEquals((Integer)2, linkedHashMap.get("ABc")); + assertEquals(2, linkedHashMap.get("aBc").intValue()); + assertEquals(2, linkedHashMap.get("ABc").intValue()); } @Test From 46843866bd569096bed78d1d261a82363ada9ff2 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Thu, 2 Apr 2020 10:06:43 +0300 Subject: [PATCH 170/187] changed LinkedHashMap to Map interface --- .../map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index 37d9af7535..c64738a266 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -29,7 +29,7 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenLinkedCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ - LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); linkedHashMap.put("abc", 1); linkedHashMap.put("ABC", 2); @@ -58,7 +58,7 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenLinkedCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ - LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); linkedHashMap.put("abc", 1); linkedHashMap.put("ABC", 2); @@ -86,7 +86,7 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenLinkedCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ - LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); linkedHashMap.put("abc", 3); linkedHashMap.remove("aBC"); From 73892202d1aacee43417e413ba14a1ba3b90b67b Mon Sep 17 00:00:00 2001 From: omerfinger Date: Thu, 2 Apr 2020 12:18:03 +0300 Subject: [PATCH 171/187] changed LinkedHashMap to Map interface --- .../map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index c64738a266..833807c692 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -15,7 +15,6 @@ public class CaseInsensitiveMapUnitTest { treeMap.put("ABC", 2); assertEquals(1, treeMap.size()); - } @Test From db989e2322d3214326c3b5b316d566e0260175bb Mon Sep 17 00:00:00 2001 From: omerfinger <43134354+omerfinger@users.noreply.github.com> Date: Wed, 8 Apr 2020 12:12:26 +0300 Subject: [PATCH 172/187] Revert to original pom settings --- java-collections-maps-3/pom.xml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/java-collections-maps-3/pom.xml b/java-collections-maps-3/pom.xml index 0dd915c87b..a397eaa033 100644 --- a/java-collections-maps-3/pom.xml +++ b/java-collections-maps-3/pom.xml @@ -8,9 +8,13 @@ 0.0.1-SNAPSHOT ../parent-java + 4.0.0 java-collections-maps-3 - + 0.1.0-SNAPSHOT + java-collections-maps-3 + jar + org.springframework @@ -36,4 +40,4 @@ 3.6.1 5.2.5.RELEASE - \ No newline at end of file + From 0b2e7e9f7c7089329e783fe3e096fe74cfe4767c Mon Sep 17 00:00:00 2001 From: omerfinger Date: Thu, 26 Mar 2020 12:29:05 +0200 Subject: [PATCH 173/187] BAEL-3926 - Java Map with case-insensitive keys --- .../core-java-collections-maps/pom.xml | 7 ++++ .../map/CaseInsensitiveMapUnitTest.java | 37 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java diff --git a/core-java-modules/core-java-collections-maps/pom.xml b/core-java-modules/core-java-collections-maps/pom.xml index c0dd705c1c..b459213e17 100644 --- a/core-java-modules/core-java-collections-maps/pom.xml +++ b/core-java-modules/core-java-collections-maps/pom.xml @@ -26,10 +26,17 @@ ${assertj.version} test + + org.springframework + spring-core + ${spring.version} + test + 4.1 3.6.1 + 5.2.5.RELEASE diff --git a/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java new file mode 100644 index 0000000000..a2171aa326 --- /dev/null +++ b/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.map; + +import org.apache.commons.collections4.map.CaseInsensitiveMap; +import org.junit.Test; +import org.springframework.util.LinkedCaseInsensitiveMap; +import static org.junit.Assert.*; + +import java.util.TreeMap; + +public class CaseInsensitiveMapUnitTest { + @Test + public void givenCaseInsensitiveTreeMap_whenTwoEntriesAdded_thenSizeIsOne(){ + TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + treeMap.put("abc", 1); + treeMap.put("ABC", 2); + + assertEquals(treeMap.size(), 1); + } + + @Test + public void givenCommonsCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ + CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + commonsHashMap.put("abc", 1); + commonsHashMap.put("ABC", 2); + + assertEquals(commonsHashMap.get("aBc"), (Integer)2); + } + + @Test + public void givenLinkedCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ + LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + linkedHashMap.put("abc", 3); + linkedHashMap.remove("aBC"); + + assertEquals(linkedHashMap.size(), 0); + } +} From b2bc2dc00408c6d1fd223e73258f03a5aac4d5cf Mon Sep 17 00:00:00 2001 From: omerfinger Date: Sat, 28 Mar 2020 17:50:20 +0300 Subject: [PATCH 174/187] new module has been added --- .../core-java-collections-maps/pom.xml | 7 -- java-collections-maps-3/pom.xml | 4 +- .../CaseInsensitiveMapUnitTest.java | 74 +++---------------- .../map/CaseInsensitiveMapUnitTest.java | 37 ---------- 4 files changed, 11 insertions(+), 111 deletions(-) delete mode 100644 java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java diff --git a/core-java-modules/core-java-collections-maps/pom.xml b/core-java-modules/core-java-collections-maps/pom.xml index b459213e17..c0dd705c1c 100644 --- a/core-java-modules/core-java-collections-maps/pom.xml +++ b/core-java-modules/core-java-collections-maps/pom.xml @@ -26,17 +26,10 @@ ${assertj.version} test - - org.springframework - spring-core - ${spring.version} - test - 4.1 3.6.1 - 5.2.5.RELEASE diff --git a/java-collections-maps-3/pom.xml b/java-collections-maps-3/pom.xml index a397eaa033..3888623a7f 100644 --- a/java-collections-maps-3/pom.xml +++ b/java-collections-maps-3/pom.xml @@ -8,13 +8,13 @@ 0.0.1-SNAPSHOT ../parent-java - + 4.0.0 java-collections-maps-3 0.1.0-SNAPSHOT java-collections-maps-3 jar - + org.springframework diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index 833807c692..b12080e368 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -1,94 +1,38 @@ package com.baeldung.map.caseinsensitivekeys; import org.apache.commons.collections4.map.CaseInsensitiveMap; +import org.junit.Assert; import org.junit.Test; import org.springframework.util.LinkedCaseInsensitiveMap; -import java.util.Map; -import java.util.TreeMap; import static org.junit.Assert.*; +import java.util.TreeMap; + public class CaseInsensitiveMapUnitTest { @Test public void givenCaseInsensitiveTreeMap_whenTwoEntriesAdded_thenSizeIsOne(){ - Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); treeMap.put("abc", 1); treeMap.put("ABC", 2); - assertEquals(1, treeMap.size()); - } - - @Test - public void givenCommonsCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ - Map commonsHashMap = new CaseInsensitiveMap<>(); - commonsHashMap.put("abc", 1); - commonsHashMap.put("ABC", 2); - - assertEquals(1, commonsHashMap.size()); - } - - @Test - public void givenLinkedCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ - Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); - linkedHashMap.put("abc", 1); - linkedHashMap.put("ABC", 2); - - assertEquals(1, linkedHashMap.size()); - } - - @Test - public void givenCaseInsensitiveTreeMap_whenSameEntryAdded_thenValueUpdated(){ - Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - treeMap.put("abc", 1); - treeMap.put("ABC", 2); - - assertEquals(2, treeMap.get("aBc").intValue()); - assertEquals(2, treeMap.get("ABc").intValue()); + assertEquals(treeMap.size(), 1); } @Test public void givenCommonsCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ - Map commonsHashMap = new CaseInsensitiveMap<>(); + CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); - assertEquals(2, commonsHashMap.get("aBc").intValue()); - assertEquals(2, commonsHashMap.get("ABc").intValue()); - } - - @Test - public void givenLinkedCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ - Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); - linkedHashMap.put("abc", 1); - linkedHashMap.put("ABC", 2); - - assertEquals(2, linkedHashMap.get("aBc").intValue()); - assertEquals(2, linkedHashMap.get("ABc").intValue()); - } - - @Test - public void givenCaseInsensitiveTreeMap_whenEntryRemoved_thenSizeIsZero(){ - Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - treeMap.put("abc", 3); - treeMap.remove("aBC"); - - assertEquals(0, treeMap.size()); - } - - @Test - public void givenCommonsCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ - Map commonsHashMap = new CaseInsensitiveMap<>(); - commonsHashMap.put("abc", 3); - commonsHashMap.remove("aBC"); - - assertEquals(0, commonsHashMap.size()); + Assert.assertEquals(commonsHashMap.get("aBc"), (Integer)2); } @Test public void givenLinkedCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ - Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); + LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); linkedHashMap.put("abc", 3); linkedHashMap.remove("aBC"); - assertEquals(0, linkedHashMap.size()); + Assert.assertEquals(linkedHashMap.size(), 0); } } diff --git a/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java deleted file mode 100644 index a2171aa326..0000000000 --- a/java-collections-maps/src/test/java/com/baeldung/map/CaseInsensitiveMapUnitTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.map; - -import org.apache.commons.collections4.map.CaseInsensitiveMap; -import org.junit.Test; -import org.springframework.util.LinkedCaseInsensitiveMap; -import static org.junit.Assert.*; - -import java.util.TreeMap; - -public class CaseInsensitiveMapUnitTest { - @Test - public void givenCaseInsensitiveTreeMap_whenTwoEntriesAdded_thenSizeIsOne(){ - TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); - treeMap.put("abc", 1); - treeMap.put("ABC", 2); - - assertEquals(treeMap.size(), 1); - } - - @Test - public void givenCommonsCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ - CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); - commonsHashMap.put("abc", 1); - commonsHashMap.put("ABC", 2); - - assertEquals(commonsHashMap.get("aBc"), (Integer)2); - } - - @Test - public void givenLinkedCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ - LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); - linkedHashMap.put("abc", 3); - linkedHashMap.remove("aBC"); - - assertEquals(linkedHashMap.size(), 0); - } -} From da97125e2068af38e4e3dd53ba196a644b195aa4 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Sat, 28 Mar 2020 17:58:34 +0300 Subject: [PATCH 175/187] tests has been added and split --- .../CaseInsensitiveMapUnitTest.java | 63 ++++++++++++++++++- 1 file changed, 60 insertions(+), 3 deletions(-) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index b12080e368..b3653a97c2 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -15,7 +15,37 @@ public class CaseInsensitiveMapUnitTest { treeMap.put("abc", 1); treeMap.put("ABC", 2); - assertEquals(treeMap.size(), 1); + assertEquals(1, treeMap.size()); + + } + + @Test + public void givenCommonsCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ + CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + commonsHashMap.put("abc", 1); + commonsHashMap.put("ABC", 2); + + assertEquals(1, commonsHashMap.size()); + + } + + @Test + public void givenLinkedCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ + LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + linkedHashMap.put("abc", 1); + linkedHashMap.put("ABC", 2); + + assertEquals(1, linkedHashMap.size()); + + } + + @Test + public void givenCaseInsensitiveTreeMap_whenSameEntryAdded_thenValueUpdated(){ + TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + treeMap.put("abc", 1); + treeMap.put("ABC", 2); + + Assert.assertEquals((Integer)2, treeMap.get("aBc")); } @Test @@ -24,7 +54,34 @@ public class CaseInsensitiveMapUnitTest { commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); - Assert.assertEquals(commonsHashMap.get("aBc"), (Integer)2); + Assert.assertEquals((Integer)2, commonsHashMap.get("aBc")); + } + + @Test + public void givenLinkedCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ + LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + linkedHashMap.put("abc", 1); + linkedHashMap.put("ABC", 2); + + Assert.assertEquals((Integer)2, linkedHashMap.get("aBc")); + } + + @Test + public void givenCaseInsensitiveTreeMap_whenEntryRemoved_thenSizeIsZero(){ + TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + treeMap.put("abc", 3); + treeMap.remove("aBC"); + + Assert.assertEquals(0, treeMap.size()); + } + + @Test + public void givenCommonsCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ + CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + commonsHashMap.put("abc", 3); + commonsHashMap.remove("aBC"); + + Assert.assertEquals(0, commonsHashMap.size()); } @Test @@ -33,6 +90,6 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("abc", 3); linkedHashMap.remove("aBC"); - Assert.assertEquals(linkedHashMap.size(), 0); + Assert.assertEquals(0, linkedHashMap.size()); } } From ac21dcc346f1c3debe4b8bd370f937c5aa6f7ba0 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Sat, 28 Mar 2020 22:41:07 +0300 Subject: [PATCH 176/187] tests has been added and split --- .../CaseInsensitiveMapUnitTest.java | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index b3653a97c2..82feef869a 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -1,17 +1,16 @@ package com.baeldung.map.caseinsensitivekeys; import org.apache.commons.collections4.map.CaseInsensitiveMap; -import org.junit.Assert; import org.junit.Test; import org.springframework.util.LinkedCaseInsensitiveMap; -import static org.junit.Assert.*; - +import java.util.Map; import java.util.TreeMap; +import static org.junit.Assert.*; public class CaseInsensitiveMapUnitTest { @Test public void givenCaseInsensitiveTreeMap_whenTwoEntriesAdded_thenSizeIsOne(){ - TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); treeMap.put("abc", 1); treeMap.put("ABC", 2); @@ -21,7 +20,7 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenCommonsCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ - CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + Map commonsHashMap = new CaseInsensitiveMap<>(); commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); @@ -41,20 +40,20 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenCaseInsensitiveTreeMap_whenSameEntryAdded_thenValueUpdated(){ - TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); treeMap.put("abc", 1); treeMap.put("ABC", 2); - Assert.assertEquals((Integer)2, treeMap.get("aBc")); + assertEquals((Integer)2, treeMap.get("aBc")); } @Test public void givenCommonsCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ - CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + Map commonsHashMap = new CaseInsensitiveMap<>(); commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); - Assert.assertEquals((Integer)2, commonsHashMap.get("aBc")); + assertEquals((Integer)2, commonsHashMap.get("aBc")); } @Test @@ -63,25 +62,25 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("abc", 1); linkedHashMap.put("ABC", 2); - Assert.assertEquals((Integer)2, linkedHashMap.get("aBc")); + assertEquals((Integer)2, linkedHashMap.get("aBc")); } @Test public void givenCaseInsensitiveTreeMap_whenEntryRemoved_thenSizeIsZero(){ - TreeMap treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + Map treeMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); treeMap.put("abc", 3); treeMap.remove("aBC"); - Assert.assertEquals(0, treeMap.size()); + assertEquals(0, treeMap.size()); } @Test public void givenCommonsCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ - CaseInsensitiveMap commonsHashMap = new CaseInsensitiveMap<>(); + Map commonsHashMap = new CaseInsensitiveMap<>(); commonsHashMap.put("abc", 3); commonsHashMap.remove("aBC"); - Assert.assertEquals(0, commonsHashMap.size()); + assertEquals(0, commonsHashMap.size()); } @Test @@ -90,6 +89,6 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("abc", 3); linkedHashMap.remove("aBC"); - Assert.assertEquals(0, linkedHashMap.size()); + assertEquals(0, linkedHashMap.size()); } } From dac08f02db475176443be050cc929b1c40699913 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Sat, 28 Mar 2020 22:50:07 +0300 Subject: [PATCH 177/187] varius get cases --- .../map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index 82feef869a..60dd1da9c0 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -45,6 +45,7 @@ public class CaseInsensitiveMapUnitTest { treeMap.put("ABC", 2); assertEquals((Integer)2, treeMap.get("aBc")); + assertEquals((Integer)2, treeMap.get("ABc")); } @Test @@ -54,6 +55,7 @@ public class CaseInsensitiveMapUnitTest { commonsHashMap.put("ABC", 2); assertEquals((Integer)2, commonsHashMap.get("aBc")); + assertEquals((Integer)2, commonsHashMap.get("ABc")); } @Test @@ -63,6 +65,7 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("ABC", 2); assertEquals((Integer)2, linkedHashMap.get("aBc")); + assertEquals((Integer)2, linkedHashMap.get("ABc")); } @Test From 22a94cd61c2b5f936e85aeecf6c52c7a5f9153d7 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Mon, 30 Mar 2020 13:28:29 +0300 Subject: [PATCH 178/187] changed README, assert has changed --- .../CaseInsensitiveMapUnitTest.java | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index 60dd1da9c0..37d9af7535 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -25,7 +25,6 @@ public class CaseInsensitiveMapUnitTest { commonsHashMap.put("ABC", 2); assertEquals(1, commonsHashMap.size()); - } @Test @@ -35,7 +34,6 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("ABC", 2); assertEquals(1, linkedHashMap.size()); - } @Test @@ -44,8 +42,8 @@ public class CaseInsensitiveMapUnitTest { treeMap.put("abc", 1); treeMap.put("ABC", 2); - assertEquals((Integer)2, treeMap.get("aBc")); - assertEquals((Integer)2, treeMap.get("ABc")); + assertEquals(2, treeMap.get("aBc").intValue()); + assertEquals(2, treeMap.get("ABc").intValue()); } @Test @@ -54,8 +52,8 @@ public class CaseInsensitiveMapUnitTest { commonsHashMap.put("abc", 1); commonsHashMap.put("ABC", 2); - assertEquals((Integer)2, commonsHashMap.get("aBc")); - assertEquals((Integer)2, commonsHashMap.get("ABc")); + assertEquals(2, commonsHashMap.get("aBc").intValue()); + assertEquals(2, commonsHashMap.get("ABc").intValue()); } @Test @@ -64,8 +62,8 @@ public class CaseInsensitiveMapUnitTest { linkedHashMap.put("abc", 1); linkedHashMap.put("ABC", 2); - assertEquals((Integer)2, linkedHashMap.get("aBc")); - assertEquals((Integer)2, linkedHashMap.get("ABc")); + assertEquals(2, linkedHashMap.get("aBc").intValue()); + assertEquals(2, linkedHashMap.get("ABc").intValue()); } @Test From 7848c39d7b634f6b90d3e2832429bfad5be311dd Mon Sep 17 00:00:00 2001 From: omerfinger Date: Thu, 2 Apr 2020 10:06:43 +0300 Subject: [PATCH 179/187] changed LinkedHashMap to Map interface --- .../map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index 37d9af7535..c64738a266 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -29,7 +29,7 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenLinkedCaseInsensitiveMap_whenTwoEntriesAdded_thenSizeIsOne(){ - LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); linkedHashMap.put("abc", 1); linkedHashMap.put("ABC", 2); @@ -58,7 +58,7 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenLinkedCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){ - LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); linkedHashMap.put("abc", 1); linkedHashMap.put("ABC", 2); @@ -86,7 +86,7 @@ public class CaseInsensitiveMapUnitTest { @Test public void givenLinkedCaseInsensitiveMap_whenEntryRemoved_thenSizeIsZero(){ - LinkedCaseInsensitiveMap linkedHashMap = new LinkedCaseInsensitiveMap<>(); + Map linkedHashMap = new LinkedCaseInsensitiveMap<>(); linkedHashMap.put("abc", 3); linkedHashMap.remove("aBC"); From edb8e8b341e45de9c5aec23aedf309c3aeccec96 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Thu, 2 Apr 2020 12:18:03 +0300 Subject: [PATCH 180/187] changed LinkedHashMap to Map interface --- .../map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java index c64738a266..833807c692 100644 --- a/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java +++ b/java-collections-maps-3/src/test/java/com/baeldung/map/caseinsensitivekeys/CaseInsensitiveMapUnitTest.java @@ -15,7 +15,6 @@ public class CaseInsensitiveMapUnitTest { treeMap.put("ABC", 2); assertEquals(1, treeMap.size()); - } @Test From 7930d2c72e6e33d163a475abc7166e02cafb2d89 Mon Sep 17 00:00:00 2001 From: omerfinger Date: Sun, 12 Apr 2020 11:48:00 +0300 Subject: [PATCH 181/187] rebase parent pom on upstream --- pom.xml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/pom.xml b/pom.xml index cb0c0cf5d7..24d9fd1d0b 100644 --- a/pom.xml +++ b/pom.xml @@ -453,8 +453,6 @@ java-collections-conversions java-collections-conversions-2 - java-collections-maps - java-collections-maps-2 java-collections-maps-3 @@ -968,8 +966,6 @@ java-collections-conversions java-collections-conversions-2 - java-collections-maps - java-collections-maps-2 java-collections-maps-3 From a0dd4a537db8332ab8790b0ee0dca3e7a42c3e5f Mon Sep 17 00:00:00 2001 From: gindex Date: Sun, 12 Apr 2020 13:01:52 +0200 Subject: [PATCH 182/187] Revert README.md to 1acadab1 --- reactor-core/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/reactor-core/README.md b/reactor-core/README.md index f2dbd77981..e3cca35f86 100644 --- a/reactor-core/README.md +++ b/reactor-core/README.md @@ -7,4 +7,3 @@ This module contains articles about Reactor Core. - [Intro To Reactor Core](https://www.baeldung.com/reactor-core) - [Combining Publishers in Project Reactor](https://www.baeldung.com/reactor-combine-streams) - [Programmatically Creating Sequences with Project Reactor](https://www.baeldung.com/flux-sequences-reactor) -- [How To Get String From Mono In Reactive Java](http://baeldung.com/string-from-mono/) \ No newline at end of file From 856c0473068fef84d5a68c532bd2ecd28884ea38 Mon Sep 17 00:00:00 2001 From: Eric Martin Date: Sun, 12 Apr 2020 13:53:06 -0500 Subject: [PATCH 183/187] Update terraform/best-practices/k8s-modules/SETUP.md Co-Authored-By: KevinGilmore --- terraform/best-practices/k8s-modules/SETUP.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/terraform/best-practices/k8s-modules/SETUP.md b/terraform/best-practices/k8s-modules/SETUP.md index b7e4c2764d..f00247a293 100644 --- a/terraform/best-practices/k8s-modules/SETUP.md +++ b/terraform/best-practices/k8s-modules/SETUP.md @@ -4,7 +4,7 @@ This sample deploys two services behind a Kubernetes ingress. # Setup instructions -1. Mak sure you have a working Kubernetes environment. Use a simple command such as _kubectl get nodes_ and check its output. +1. Make sure you have a working Kubernetes environment. Use a simple command such as _kubectl get nodes_ and check its output. If you get a list of nodes that contains at least one _ready_ module, you're good to go 2. Download the Terraform package for your environment from Hashicorp's site. Unzip it and put the _terraform_ binary somewhere in the OS's PATH. @@ -18,4 +18,3 @@ This sample deploys two services behind a Kubernetes ingress. 6. Run _terraform destroy_ to remove the previously creates namespace. - From bf0ff591457cef341514a54764c1b944f87b7cd2 Mon Sep 17 00:00:00 2001 From: Eric Martin Date: Sun, 12 Apr 2020 13:53:19 -0500 Subject: [PATCH 184/187] Update terraform/best-practices/k8s-basic/SETUP.md Co-Authored-By: KevinGilmore --- terraform/best-practices/k8s-basic/SETUP.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/terraform/best-practices/k8s-basic/SETUP.md b/terraform/best-practices/k8s-basic/SETUP.md index 479bb75274..35e690d88e 100644 --- a/terraform/best-practices/k8s-basic/SETUP.md +++ b/terraform/best-practices/k8s-basic/SETUP.md @@ -1,6 +1,6 @@ # Setup instructions -1. Mak sure you have a working Kubernetes environment. Use a simple command such as _kubectl get nodes_ and check its output. +1. Make sure you have a working Kubernetes environment. Use a simple command such as _kubectl get nodes_ and check its output. If you get a list of nodes that contains at least one _ready_ module, you're good to go 2. Download the Terraform package for your environment from Hashicorp's site. Unzip it and put the _terraform_ binary somewhere in the OS's PATH. @@ -12,4 +12,3 @@ ''' 5. Wait until Terraform create all resources and run _kubectl get namespaces_. The output should now have a new "hello-terraform" namespace. 6. Run _terraform destroy_ to remove the previously creates namespace. - From a6b0996346beedb9066b1aa0ab334c65ee79080a Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Mon, 13 Apr 2020 22:34:36 +0530 Subject: [PATCH 185/187] BAEL-3909: Update README to include article in correct module --- core-java-modules/core-java-string-operations-2/README.md | 1 + core-java-modules/core-java-string-operations/README.md | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-string-operations-2/README.md b/core-java-modules/core-java-string-operations-2/README.md index 5e92738f5c..bc00c6a915 100644 --- a/core-java-modules/core-java-string-operations-2/README.md +++ b/core-java-modules/core-java-string-operations-2/README.md @@ -11,4 +11,5 @@ This module contains articles about string operations. - [Case-Insensitive String Matching in Java](https://www.baeldung.com/java-case-insensitive-string-matching) - [L-Trim and R-Trim in Java](https://www.baeldung.com/l-trim-and-r-trim-in-java) - [L-Trim and R-Trim Alternatives in Java](https://www.baeldung.com/java-trim-alternatives) +- [Java Convert PDF to Base64](https://www.baeldung.com/java-convert-pdf-to-base64) - More articles: [[<-- prev]](../core-java-string-operations) diff --git a/core-java-modules/core-java-string-operations/README.md b/core-java-modules/core-java-string-operations/README.md index c40e56bc46..18a2649a6a 100644 --- a/core-java-modules/core-java-string-operations/README.md +++ b/core-java-modules/core-java-string-operations/README.md @@ -13,5 +13,4 @@ This module contains articles about string operations. - [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline) - [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) - [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode) -- [Java Convert PDF to Base64](https://www.baeldung.com/java-convert-pdf-to-base64) - More articles: [[next -->]](../core-java-string-operations-2) From bc872d37428127eed4088f141205d1583588159c Mon Sep 17 00:00:00 2001 From: Benjamin Caure Date: Tue, 14 Apr 2020 07:08:04 +0200 Subject: [PATCH 186/187] BAEL-3943 Bson to json (#9079) --- persistence-modules/java-mongodb/README.md | 1 + .../com/baeldung/morphia/domain/Book.java | 88 ++++++++--- .../bsontojson/BsonToJsonIntegrationTest.java | 142 ++++++++++++++++++ .../bsontojson/JsonDateTimeConverter.java | 30 ++++ 4 files changed, 243 insertions(+), 18 deletions(-) create mode 100644 persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonIntegrationTest.java create mode 100644 persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JsonDateTimeConverter.java diff --git a/persistence-modules/java-mongodb/README.md b/persistence-modules/java-mongodb/README.md index a8539e644f..5c3c448b03 100644 --- a/persistence-modules/java-mongodb/README.md +++ b/persistence-modules/java-mongodb/README.md @@ -10,3 +10,4 @@ This module contains articles about MongoDB in Java. - [Geospatial Support in MongoDB](https://www.baeldung.com/mongodb-geospatial-support) - [Introduction to Morphia – Java ODM for MongoDB](https://www.baeldung.com/mongodb-morphia) - [MongoDB Aggregations Using Java](https://www.baeldung.com/java-mongodb-aggregations) +- [MongoDB BSON to JSON](https://www.baeldung.com/bson-to-json) diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java index 172c916ad9..4ed2ab8580 100644 --- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java @@ -1,5 +1,7 @@ package com.baeldung.morphia.domain; +import java.time.LocalDate; +import java.time.LocalDateTime; import java.util.HashSet; import java.util.Set; @@ -29,28 +31,13 @@ public class Book { private double cost; @Reference private Set companionBooks; + @Property + private LocalDateTime publishDate; public Book() { } - public String getTitle() { - return title; - } - - public String getAuthor() { - return author; - } - - public double getCost() { - return cost; - } - - public void addCompanionBooks(Book book) { - if (companionBooks != null) - this.companionBooks.add(book); - } - public Book(String isbn, String title, String author, double cost, Publisher publisher) { this.isbn = isbn; this.title = title; @@ -60,6 +47,71 @@ public class Book { this.companionBooks = new HashSet<>(); } + // Getters and setters ... + public String getIsbn() { + return isbn; + } + + public Book setIsbn(String isbn) { + this.isbn = isbn; + return this; + } + + public String getTitle() { + return title; + } + + public Book setTitle(String title) { + this.title = title; + return this; + } + + public String getAuthor() { + return author; + } + + public Book setAuthor(String author) { + this.author = author; + return this; + } + + public Publisher getPublisher() { + return publisher; + } + + public Book setPublisher(Publisher publisher) { + this.publisher = publisher; + return this; + } + + public double getCost() { + return cost; + } + + public Book setCost(double cost) { + this.cost = cost; + return this; + } + + public LocalDateTime getPublishDate() { + return publishDate; + } + + public Book setPublishDate(LocalDateTime publishDate) { + this.publishDate = publishDate; + return this; + } + + public Set getCompanionBooks() { + return companionBooks; + } + + public Book addCompanionBooks(Book book) { + if (companionBooks != null) + this.companionBooks.add(book); + return this; + } + @Override public String toString() { return "Book [isbn=" + isbn + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", cost=" + cost + "]"; @@ -113,4 +165,4 @@ public class Book { return true; } -} \ No newline at end of file +} diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonIntegrationTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonIntegrationTest.java new file mode 100644 index 0000000000..e382ea4ab2 --- /dev/null +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonIntegrationTest.java @@ -0,0 +1,142 @@ +package com.baeldung.bsontojson; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.sql.Timestamp; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.TimeZone; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.bson.Document; +import org.bson.json.Converter; +import org.bson.json.JsonMode; +import org.bson.json.JsonWriterSettings; +import org.bson.json.StrictJsonWriter; +import org.bson.types.ObjectId; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.morphia.domain.Book; +import com.baeldung.morphia.domain.Publisher; +import com.mongodb.MongoClient; +import com.mongodb.client.MongoDatabase; + +import dev.morphia.Datastore; +import dev.morphia.Morphia; + +public class BsonToJsonIntegrationTest { + + private static final String DB_NAME = "library"; + private static Datastore datastore; + + @BeforeClass + public static void setUp() { + Morphia morphia = new Morphia(); + morphia.mapPackage("com.baeldung.morphia"); + datastore = morphia.createDatastore(new MongoClient(), DB_NAME); + datastore.ensureIndexes(); + + datastore.save(new Book() + .setIsbn("isbn") + .setTitle("title") + .setAuthor("author") + .setCost(3.95) + .setPublisher(new Publisher(new ObjectId("fffffffffffffffffffffffa"),"publisher")) + .setPublishDate(LocalDateTime.parse("2020-01-01T18:13:32Z", DateTimeFormatter.ISO_DATE_TIME)) + .addCompanionBooks(new Book().setIsbn("isbn2"))); + } + + @AfterClass + public static void tearDown() { + datastore.delete(datastore.createQuery(Book.class)); + } + + @Test + public void givenBsonDocument_whenUsingStandardJsonTransformation_thenJsonDateIsObjectEpochTime() { + + String json = null; + try (MongoClient mongoClient = new MongoClient()) { + MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); + Document bson = mongoDatabase.getCollection("Books").find().first(); + json = bson.toJson(); + } + + String expectedJson = "{\"_id\": \"isbn\", " + + "\"className\": \"com.baeldung.morphia.domain.Book\", " + + "\"title\": \"title\", " + + "\"author\": \"author\", " + + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + + "\"name\": \"publisher\"}, " + + "\"price\": 3.95, " + + "\"publishDate\": {\"$date\": 1577898812000}}"; + + assertNotNull(json); + + assertEquals(expectedJson, json); + } + + + @Test + public void givenBsonDocument_whenUsingRelaxedJsonTransformation_thenJsonDateIsObjectIsoDate() { + + String json = null; + try (MongoClient mongoClient = new MongoClient()) { + MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); + Document bson = mongoDatabase.getCollection("Books").find().first(); + json = bson.toJson(JsonWriterSettings + .builder() + .outputMode(JsonMode.RELAXED) + .build()); + } + + String expectedJson = "{\"_id\": \"isbn\", " + + "\"className\": \"com.baeldung.morphia.domain.Book\", " + + "\"title\": \"title\", " + + "\"author\": \"author\", " + + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + + "\"name\": \"publisher\"}, " + + "\"price\": 3.95, " + + "\"publishDate\": {\"$date\": \"2020-01-01T17:13:32Z\"}}"; + + assertNotNull(json); + + assertEquals(expectedJson, json); + } + + @Test + public void givenBsonDocument_whenUsingCustomJsonTransformation_thenJsonDateIsStringField() { + + String json = null; + try (MongoClient mongoClient = new MongoClient()) { + MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME); + Document bson = mongoDatabase.getCollection("Books").find().first(); + json = bson.toJson(JsonWriterSettings + .builder() + .dateTimeConverter(new JsonDateTimeConverter()) + .build()); + } + + String expectedJson = "{\"_id\": \"isbn\", " + + "\"className\": \"com.baeldung.morphia.domain.Book\", " + + "\"title\": \"title\", " + + "\"author\": \"author\", " + + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + + "\"name\": \"publisher\"}, " + + "\"price\": 3.95, " + + "\"publishDate\": \"2020-01-01T17:13:32Z\"}"; + + assertEquals(expectedJson, json); + + } + +} diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JsonDateTimeConverter.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JsonDateTimeConverter.java new file mode 100644 index 0000000000..46023e363f --- /dev/null +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JsonDateTimeConverter.java @@ -0,0 +1,30 @@ +package com.baeldung.bsontojson; + +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.TimeZone; + +import org.bson.json.Converter; +import org.bson.json.StrictJsonWriter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JsonDateTimeConverter implements Converter { + + private static final Logger LOGGER = LoggerFactory.getLogger(JsonDateTimeConverter.class); + static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ISO_INSTANT + .withZone(ZoneId.of("UTC")); + + @Override + public void convert(Long value, StrictJsonWriter writer) { + try { + Instant instant = new Date(value).toInstant(); + String s = DATE_TIME_FORMATTER.format(instant); + writer.writeString(s); + } catch (Exception e) { + LOGGER.error(String.format("Fail to convert offset %d to JSON date", value), e); + } + } +} From 405230e25bf2cf92932b16d6dcc64acff80b9846 Mon Sep 17 00:00:00 2001 From: Kumar Chandrakant Date: Tue, 14 Apr 2020 10:52:05 +0530 Subject: [PATCH 187/187] Testing multithreading (#9088) --- .../core-java-concurrency-testing/.gitignore | 26 --- .../core-java-concurrency-testing/pom.xml | 170 +++++++++--------- 2 files changed, 85 insertions(+), 111 deletions(-) delete mode 100644 core-java-modules/core-java-concurrency-testing/.gitignore diff --git a/core-java-modules/core-java-concurrency-testing/.gitignore b/core-java-modules/core-java-concurrency-testing/.gitignore deleted file mode 100644 index 3de4cc647e..0000000000 --- a/core-java-modules/core-java-concurrency-testing/.gitignore +++ /dev/null @@ -1,26 +0,0 @@ -*.class - -0.* - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* -.resourceCache - -# Packaged files # -*.jar -*.war -*.ear - -# Files generated by integration tests -*.txt -backup-pom.xml -/bin/ -/temp - -#IntelliJ specific -.idea/ -*.iml \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-testing/pom.xml b/core-java-modules/core-java-concurrency-testing/pom.xml index bb3e6f5152..51de83f67c 100644 --- a/core-java-modules/core-java-concurrency-testing/pom.xml +++ b/core-java-modules/core-java-concurrency-testing/pom.xml @@ -1,93 +1,93 @@ - 4.0.0 - core-java-concurrency-testing - 0.1.0-SNAPSHOT - core-java-concurrency-testing - jar + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + core-java-concurrency-testing + 0.1.0-SNAPSHOT + core-java-concurrency-testing + jar - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + - - - junit - junit - 4.13 - test - - - com.googlecode.thread-weaver - threadweaver - 0.2 - test - - - com.google.code.tempus-fugit - tempus-fugit - 1.1 - test - - - com.googlecode.multithreadedtc - multithreadedtc - 1.01 - test - - - org.openjdk.jcstress - jcstress-core - 0.5 - - + + + junit + junit + 4.13 + test + + + com.googlecode.thread-weaver + threadweaver + 0.2 + test + + + com.google.code.tempus-fugit + tempus-fugit + 1.1 + test + + + com.googlecode.multithreadedtc + multithreadedtc + 1.01 + test + + + org.openjdk.jcstress + jcstress-core + 0.5 + + - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - ${javac.target} - ${javac.target} - ${javac.target} - - + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${javac.target} + ${javac.target} + ${javac.target} + + - - org.apache.maven.plugins - maven-shade-plugin - 2.2 - - - main - package - - shade - - - jcstress - - - org.openjdk.jcstress.Main - - - META-INF/TestList - - - - - - - - + + org.apache.maven.plugins + maven-shade-plugin + 2.2 + + + main + package + + shade + + + jcstress + + + org.openjdk.jcstress.Main + + + META-INF/TestList + + + + + + + +