diff --git a/core-java-modules/core-java-16/pom.xml b/core-java-modules/core-java-16/pom.xml index 4adc3ee6d1..a2c0d4855b 100644 --- a/core-java-modules/core-java-16/pom.xml +++ b/core-java-modules/core-java-16/pom.xml @@ -63,4 +63,4 @@ 3.0.0-M5 - \ No newline at end of file + diff --git a/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/enumallt/DinosaurEnum.java b/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/enumallt/DinosaurEnum.java new file mode 100644 index 0000000000..a50f79947c --- /dev/null +++ b/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/enumallt/DinosaurEnum.java @@ -0,0 +1,19 @@ +package com.baeldung.instanceofalternative.enumallt; + +public enum DinosaurEnum { + Anatotitan { + @Override + public String move() { + return "running"; + } + }, + Euraptor { + @Override + public String move() { + return "flying"; + } + }; + + public abstract String move(); + +} diff --git a/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/model/Anatotitan.java b/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/model/Anatotitan.java new file mode 100644 index 0000000000..ce59b58ad7 --- /dev/null +++ b/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/model/Anatotitan.java @@ -0,0 +1,15 @@ +package com.baeldung.instanceofalternative.model; + +public class Anatotitan extends Dinosaur { + // polymorphism + @Override + public String move() { + return "running"; + } + + // non-polymorphism + public String run() { + return "running"; + } + +} diff --git a/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/model/Dinosaur.java b/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/model/Dinosaur.java new file mode 100644 index 0000000000..38055054f5 --- /dev/null +++ b/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/model/Dinosaur.java @@ -0,0 +1,9 @@ +package com.baeldung.instanceofalternative.model; + +public class Dinosaur { + + public String move() { + return "default movement"; + } + +} diff --git a/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/model/Euraptor.java b/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/model/Euraptor.java new file mode 100644 index 0000000000..1de5257a0d --- /dev/null +++ b/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/model/Euraptor.java @@ -0,0 +1,15 @@ +package com.baeldung.instanceofalternative.model; + +public class Euraptor extends Dinosaur { + // polymorphism + @Override + public String move() { + return "flying"; + } + + // non-polymorphism + public String flies() { + return "flying"; + } + +} diff --git a/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/visitorspattern/Anatotitan.java b/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/visitorspattern/Anatotitan.java new file mode 100644 index 0000000000..84d93e7350 --- /dev/null +++ b/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/visitorspattern/Anatotitan.java @@ -0,0 +1,14 @@ +package com.baeldung.instanceofalternative.visitorspattern; + +public class Anatotitan implements Dino { + + String run() { + return "running"; + } + + @Override + public String move(Visitor dinobehave) { + return dinobehave.visit(this); + } + +} diff --git a/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/visitorspattern/Dino.java b/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/visitorspattern/Dino.java new file mode 100644 index 0000000000..ef33baf2a4 --- /dev/null +++ b/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/visitorspattern/Dino.java @@ -0,0 +1,7 @@ +package com.baeldung.instanceofalternative.visitorspattern; + +public interface Dino { + + String move(Visitor dinoMove); + +} diff --git a/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/visitorspattern/DinoVisitorImpl.java b/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/visitorspattern/DinoVisitorImpl.java new file mode 100644 index 0000000000..6fd71374fa --- /dev/null +++ b/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/visitorspattern/DinoVisitorImpl.java @@ -0,0 +1,15 @@ +package com.baeldung.instanceofalternative.visitorspattern; + +public class DinoVisitorImpl implements Visitor { + + @Override + public String visit(Anatotitan anatotitan) { + return anatotitan.run(); + } + + @Override + public String visit(Euraptor euraptor) { + return euraptor.flies(); + } + +} diff --git a/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/visitorspattern/Euraptor.java b/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/visitorspattern/Euraptor.java new file mode 100644 index 0000000000..fdce1e6c0b --- /dev/null +++ b/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/visitorspattern/Euraptor.java @@ -0,0 +1,14 @@ +package com.baeldung.instanceofalternative.visitorspattern; + +public class Euraptor implements Dino { + + String flies() { + return "flying"; + } + + @Override + public String move(Visitor dinobehave) { + return dinobehave.visit(this); + } + +} diff --git a/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/visitorspattern/Visitor.java b/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/visitorspattern/Visitor.java new file mode 100644 index 0000000000..75fada3533 --- /dev/null +++ b/core-java-modules/core-java-16/src/main/java/com/baeldung/instanceof_alternatives/visitorspattern/Visitor.java @@ -0,0 +1,9 @@ +package com.baeldung.instanceofalternative.visitorspattern; + +public interface Visitor { + + String visit(Anatotitan anatotitan); + + String visit(Euraptor euraptor); + +} diff --git a/core-java-modules/core-java-16/src/test/java/com/baeldung/instanceof_alternative_test/EnumUnitTest.java b/core-java-modules/core-java-16/src/test/java/com/baeldung/instanceof_alternative_test/EnumUnitTest.java new file mode 100644 index 0000000000..73faa2a1ef --- /dev/null +++ b/core-java-modules/core-java-16/src/test/java/com/baeldung/instanceof_alternative_test/EnumUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.instanceoftest; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.baeldung.instanceofalternative.enumallt.*; + +public class EnumUnitTest { + @Test + public void givenADinosaurSpecie_whenUsingEnum_thenGetMovementOfEuraptor() { + + assertEquals("flying", moveDinosaurUsingEnum(DinosaurEnum.Euraptor)); + } + + @Test + public void givenADinosaurSpecie_whenUsingEnum_thenGetMovementOfAnatotitan() { + assertEquals("running", moveDinosaurUsingEnum(DinosaurEnum.Anatotitan)); + } + + public static String moveDinosaurUsingEnum(DinosaurEnum dinosaurenum) { + return dinosaurenum.move(); + + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-16/src/test/java/com/baeldung/instanceof_alternative_test/ExampleSetupUnitTest.java b/core-java-modules/core-java-16/src/test/java/com/baeldung/instanceof_alternative_test/ExampleSetupUnitTest.java new file mode 100644 index 0000000000..c42f77849b --- /dev/null +++ b/core-java-modules/core-java-16/src/test/java/com/baeldung/instanceof_alternative_test/ExampleSetupUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.instanceoftest; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.baeldung.instanceofalternative.model.*; + +public class ExampleSetupUnitTest { + + @Test + public void givenADinosaurSpecie_whenUsingInstancof_thenGetMovementOfAnatotitan() { + + assertEquals("running", moveDinosaurUsingInstanceof(new Anatotitan())); + } + + @Test + public void givenADinosaurSpecie_whenUsingInstanceof_thenGetMovementOfEuraptor() { + assertEquals("flying", moveDinosaurUsingInstanceof(new Euraptor())); + } + + public static String moveDinosaurUsingInstanceof(Dinosaur dinosaur) { + + if (dinosaur instanceof Anatotitan) { + + Anatotitan anatotitan = (Anatotitan) dinosaur; + return anatotitan.run(); + } else if (dinosaur instanceof Euraptor) { + Euraptor euraptor = (Euraptor) dinosaur; + return euraptor.flies(); + } + return ""; + } + +} diff --git a/core-java-modules/core-java-16/src/test/java/com/baeldung/instanceof_alternative_test/GetClassUnitTest.java b/core-java-modules/core-java-16/src/test/java/com/baeldung/instanceof_alternative_test/GetClassUnitTest.java new file mode 100644 index 0000000000..6a4886c8a3 --- /dev/null +++ b/core-java-modules/core-java-16/src/test/java/com/baeldung/instanceof_alternative_test/GetClassUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.instanceoftest; + +import static org.junit.Assert.*; +import org.junit.Test; + +import com.baeldung.instanceofalternative.model.*; + +public class GetClassUnitTest { + + @Test + public void givenADinosaurSpecie_whenUsingGetClass_thenGetMovementOfAnatotitan() { + + assertEquals("running", moveDinosaurUsingGetClass(new Anatotitan())); + } + + @Test + public void givenADinosaurSpecie_whenUsingGetClass_thenGetMovementOfEuraptor() { + assertEquals("flying", moveDinosaurUsingGetClass(new Euraptor())); + } + + public static String moveDinosaurUsingGetClass(Dinosaur dinosaur) { + + if (dinosaur.getClass() + .equals(Anatotitan.class)) { + + Anatotitan anatotitan = (Anatotitan) dinosaur; + return anatotitan.run(); + } else if (dinosaur.getClass() + .equals(Euraptor.class)) { + Euraptor euraptor = (Euraptor) dinosaur; + return euraptor.flies(); + } + return ""; + } + +} diff --git a/core-java-modules/core-java-16/src/test/java/com/baeldung/instanceof_alternative_test/PolymorphismUnitTest.java b/core-java-modules/core-java-16/src/test/java/com/baeldung/instanceof_alternative_test/PolymorphismUnitTest.java new file mode 100644 index 0000000000..960ed34c82 --- /dev/null +++ b/core-java-modules/core-java-16/src/test/java/com/baeldung/instanceof_alternative_test/PolymorphismUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.instanceoftest; + +import static org.junit.Assert.*; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.instanceofalternative.model.*; + +public class PolymorphismUnitTest { + + @Test + public void givenADinosaurSpecie_whenUsingPolymorphism_thenGetMovementOfAnatotitan() { + + assertEquals("running", moveDinosaurUsingPolymorphism(new Anatotitan())); + } + + @Test + public void givenADinosaurSpecie_whenUsingPolymorphism_thenGetMovementOfEuraptor() { + assertEquals("flying", moveDinosaurUsingPolymorphism(new Euraptor())); + } + + public static String moveDinosaurUsingPolymorphism(Dinosaur dinosaur) { + return dinosaur.move(); + } + +} diff --git a/core-java-modules/core-java-16/src/test/java/com/baeldung/instanceof_alternative_test/VisitorsPatternUnitTest.java b/core-java-modules/core-java-16/src/test/java/com/baeldung/instanceof_alternative_test/VisitorsPatternUnitTest.java new file mode 100644 index 0000000000..287f7df798 --- /dev/null +++ b/core-java-modules/core-java-16/src/test/java/com/baeldung/instanceof_alternative_test/VisitorsPatternUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.instanceoftest; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.baeldung.instanceofalternative.visitorspattern.*; + +public class VisitorsPatternUnitTest { + + @Test + public void givenADinosaurSpecie_whenUsingVisitorPattern_thenGetMovementOfAnatotitan() { + + assertEquals("running", moveDinosaurUsingVisitorPattern((Dino) new Anatotitan())); + } + + @Test + public void givenADinosaurSpecie_whenUsingVisitorPattern_thenGetMovementOfEuraptor() { + + assertEquals("flying", moveDinosaurUsingVisitorPattern((Dino) new Euraptor())); + } + + public static String moveDinosaurUsingVisitorPattern(Dino dinosaur) { + Visitor visitor = new DinoVisitorImpl(); + + return dinosaur.move(visitor); + } + +} diff --git a/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/exceptions_vs_errors/ErrorExample.java b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/exceptions_vs_errors/ErrorExample.java index 143ca8c57e..904877e01e 100644 --- a/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/exceptions_vs_errors/ErrorExample.java +++ b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/exceptions_vs_errors/ErrorExample.java @@ -1,14 +1,9 @@ package com.baeldung.exception.exceptions_vs_errors; public class ErrorExample { - - public static void main(String[] args) { - overflow(); - } - public static void overflow() { - System.out.println("overflow..."); - overflow(); + public static void main(String[] args) { + throw new AssertionError(); } } diff --git a/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/exceptions_vs_errors/ErrorExampleUnitTest.java b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/exceptions_vs_errors/ErrorExampleUnitTest.java index 9fca24638d..acbb07be1f 100644 --- a/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/exceptions_vs_errors/ErrorExampleUnitTest.java +++ b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/exceptions_vs_errors/ErrorExampleUnitTest.java @@ -3,11 +3,11 @@ package com.baeldung.exception.exceptions_vs_errors; import org.junit.Test; import org.junit.jupiter.api.Assertions; -// Unit test for the ErrorExample class. public class ErrorExampleUnitTest { + @Test public void whenMainMethodIsRun_thenStackOverflowError() { - Assertions.assertThrows(StackOverflowError.class, - () -> ErrorExample.main(null)); + Assertions.assertThrows(AssertionError.class, + () -> ErrorExample.main(null)); } } diff --git a/core-java-modules/core-java-jvm-2/README.md b/core-java-modules/core-java-jvm-2/README.md index 1313a1ce48..b00618a751 100644 --- a/core-java-modules/core-java-jvm-2/README.md +++ b/core-java-modules/core-java-jvm-2/README.md @@ -14,5 +14,4 @@ This module contains articles about working with the Java Virtual Machine (JVM). - [An Introduction to the Constant Pool in the JVM](https://www.baeldung.com/jvm-constant-pool) - [List All the Classes Loaded in the JVM](https://www.baeldung.com/jvm-list-all-classes-loaded) - [Static Fields and Garbage Collection](https://www.baeldung.com/java-static-fields-gc) -- [Difference Between Class.getResource() and ClassLoader.getResource()](https://www.baeldung.com/java-class-vs-classloader-getresource) -- More articles: [[<-- prev]](/core-java-modules/core-java-jvm) +- More articles: [[<-- prev]](/core-java-modules/core-java-jvm) [[next -->]](/core-java-modules/core-java-jvm-3) diff --git a/core-java-modules/core-java-jvm-3/README.md b/core-java-modules/core-java-jvm-3/README.md new file mode 100644 index 0000000000..5c694edaa0 --- /dev/null +++ b/core-java-modules/core-java-jvm-3/README.md @@ -0,0 +1,8 @@ +## Core Java JVM Cookbooks and Examples + +This module contains articles about working with the Java Virtual Machine (JVM). + +### Relevant Articles: + +- [Difference Between Class.getResource() and ClassLoader.getResource()](https://www.baeldung.com/java-class-vs-classloader-getresource) +- More articles: [[<-- prev]](/core-java-modules/core-java-jvm-2) diff --git a/core-java-modules/core-java-jvm-3/pom.xml b/core-java-modules/core-java-jvm-3/pom.xml new file mode 100644 index 0000000000..86c3799c09 --- /dev/null +++ b/core-java-modules/core-java-jvm-3/pom.xml @@ -0,0 +1,21 @@ + + + 4.0.0 + core-java-jvm-3 + 0.1.0-SNAPSHOT + core-java-jvm-3 + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + + + + + \ No newline at end of file diff --git a/core-java-modules/core-java-jvm-2/src/main/java/com/baeldung/resource/ClassGetResourceExample.java b/core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/resource/ClassGetResourceExample.java similarity index 100% rename from core-java-modules/core-java-jvm-2/src/main/java/com/baeldung/resource/ClassGetResourceExample.java rename to core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/resource/ClassGetResourceExample.java diff --git a/core-java-modules/core-java-jvm-2/src/main/java/com/baeldung/resource/ClassLoaderGetResourceExample.java b/core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/resource/ClassLoaderGetResourceExample.java similarity index 100% rename from core-java-modules/core-java-jvm-2/src/main/java/com/baeldung/resource/ClassLoaderGetResourceExample.java rename to core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/resource/ClassLoaderGetResourceExample.java diff --git a/core-java-modules/core-java-jvm-2/src/main/resources/com/baeldung/resource/example.txt b/core-java-modules/core-java-jvm-3/src/resources/com/baeldung/resource/example.txt similarity index 100% rename from core-java-modules/core-java-jvm-2/src/main/resources/com/baeldung/resource/example.txt rename to core-java-modules/core-java-jvm-3/src/resources/com/baeldung/resource/example.txt diff --git a/core-java-modules/core-java-jvm-2/src/test/java/com/baeldung/resource/ClassGetResourceUnitTest.java b/core-java-modules/core-java-jvm-3/test/java/com/baeldung/resource/ClassGetResourceUnitTest.java similarity index 100% rename from core-java-modules/core-java-jvm-2/src/test/java/com/baeldung/resource/ClassGetResourceUnitTest.java rename to core-java-modules/core-java-jvm-3/test/java/com/baeldung/resource/ClassGetResourceUnitTest.java diff --git a/core-java-modules/core-java-jvm-2/src/test/java/com/baeldung/resource/ClassLoaderGetResourceUnitTest.java b/core-java-modules/core-java-jvm-3/test/java/com/baeldung/resource/ClassLoaderGetResourceUnitTest.java similarity index 100% rename from core-java-modules/core-java-jvm-2/src/test/java/com/baeldung/resource/ClassLoaderGetResourceUnitTest.java rename to core-java-modules/core-java-jvm-3/test/java/com/baeldung/resource/ClassLoaderGetResourceUnitTest.java diff --git a/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/anonymousclass/EmailSenderService.java b/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/anonymousclass/EmailSenderService.java new file mode 100644 index 0000000000..f0c41b1cc9 --- /dev/null +++ b/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/anonymousclass/EmailSenderService.java @@ -0,0 +1,10 @@ +package com.baeldung.anonymousclass; + +public class EmailSenderService implements SenderService { + + @Override + public String callSender(Sender sender) { + return sender.send("Email Notification"); + } + +} diff --git a/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/anonymousclass/Sender.java b/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/anonymousclass/Sender.java new file mode 100644 index 0000000000..9e59960c14 --- /dev/null +++ b/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/anonymousclass/Sender.java @@ -0,0 +1,7 @@ +package com.baeldung.anonymousclass; + +public interface Sender { + + String send(final String message); + +} diff --git a/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/anonymousclass/SenderService.java b/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/anonymousclass/SenderService.java new file mode 100644 index 0000000000..cbb0977f89 --- /dev/null +++ b/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/anonymousclass/SenderService.java @@ -0,0 +1,7 @@ +package com.baeldung.anonymousclass; + +public interface SenderService { + + String callSender(Sender sender); + +} diff --git a/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/anonymousclass/SmsSenderService.java b/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/anonymousclass/SmsSenderService.java new file mode 100644 index 0000000000..9c84664ec4 --- /dev/null +++ b/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/anonymousclass/SmsSenderService.java @@ -0,0 +1,10 @@ +package com.baeldung.anonymousclass; + +public class SmsSenderService implements SenderService { + + @Override + public String callSender(Sender sender) { + return sender.send("SMS Notification"); + } + +} diff --git a/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/anonymousclass/AnonymousClassToLambdaIntegrationTest.java b/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/anonymousclass/AnonymousClassToLambdaIntegrationTest.java new file mode 100644 index 0000000000..b329e003f4 --- /dev/null +++ b/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/anonymousclass/AnonymousClassToLambdaIntegrationTest.java @@ -0,0 +1,34 @@ +package com.baeldung.anonymousclass; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class AnonymousClassToLambdaIntegrationTest { + + @Test + public void whenPassingAnonymousClass_thenSuccess() { + final SenderService emailSenderService = new EmailSenderService(); + + final String emailNotif = emailSenderService.callSender(new Sender() { + @Override + public String send(String message) { + return message; + } + }); + + assertEquals(emailNotif, "Email Notification"); + } + + @Test + public void whenPassingLambdaExpression_thenSuccess() { + final SenderService smsSenderService = new SmsSenderService(); + + final String smsNotif = smsSenderService.callSender((String message) -> { + return message; + }); + + assertEquals(smsNotif, "SMS Notification"); + } + +} diff --git a/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/generics/Animal.java b/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/generics/Animal.java new file mode 100644 index 0000000000..fd247a4eff --- /dev/null +++ b/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/generics/Animal.java @@ -0,0 +1,22 @@ +package com.baeldung.generics; + +abstract class Animal { + + protected final String type; + protected final String name; + + protected Animal(String type, String name) { + this.type = type; + this.name = name; + } + + abstract String makeSound(); + + public String getType() { + return type; + } + + public String getName() { + return name; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/generics/AnimalDemo.java b/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/generics/AnimalDemo.java new file mode 100644 index 0000000000..3d33180fa3 --- /dev/null +++ b/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/generics/AnimalDemo.java @@ -0,0 +1,26 @@ +package com.baeldung.generics; + +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class AnimalDemo { + + private static final Logger logger = LoggerFactory.getLogger(AnimalDemo.class); + + public static void main(String[] args) { + List cats = new ArrayList<>(); + cats.add(new Cat("Persian", "Bono")); + cats.add(new Cat("Egyptian", "Lulu")); + cats.add(new Cat("Siamese", "Ra")); + + order(cats); + logger.info("Ordered cats: {}", cats); + } + + public static > void order(List list) { + list.sort(Comparable::compareTo); + } +} diff --git a/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/generics/Cat.java b/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/generics/Cat.java new file mode 100644 index 0000000000..bb6f9ba8f0 --- /dev/null +++ b/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/generics/Cat.java @@ -0,0 +1,41 @@ +package com.baeldung.generics; + +import java.util.Objects; + +class Cat extends Animal implements Comparable { + public Cat(String type, String name) { + super(type, name); + } + + @Override + public String makeSound() { + return "Meow"; + } + + /** + * Warning: Inconsistent with the equals method. + */ + @Override + public int compareTo(Cat cat) { + return this.getName().length() - cat.getName().length(); + } + + @Override + public String toString() { + return "Cat{" + "type='" + type + '\'' + ", name='" + name + '\'' + '}'; + } + + @Override + public int hashCode() { + return Objects.hash(type, name); + } + + @Override + public boolean equals(Object o) { + if(o == this) return true; + if(!(o instanceof Cat)) return false; + Cat cat = (Cat) o; + return type.equals(cat.type) && name.equals(cat.name); + } + +} diff --git a/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/generics/CollectionUtils.java b/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/generics/CollectionUtils.java new file mode 100644 index 0000000000..6d84f5199b --- /dev/null +++ b/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/generics/CollectionUtils.java @@ -0,0 +1,56 @@ +package com.baeldung.generics; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class CollectionUtils { + + private CollectionUtils() { + } + + public static void print(T item) { + System.out.println(item); + } + + public static void swap(List list, int src, int des) { + swapHelper(list, src, des); + } + + private static void swapHelper(List list, int src, int des) { + list.set(src, list.set(des, list.get(src))); + } + + public static List mergeTypeParameter(List listOne, List listTwo) { + return Stream.concat(listOne.stream(), listTwo.stream()) + .collect(Collectors.toList()); + } + + public static List mergeWildcard(List listOne, List listTwo) { + return Stream.concat(listOne.stream(), listTwo.stream()) + .collect(Collectors.toList()); + } + + public static long sum(List numbers) { + return numbers.stream() + .mapToLong(Number::longValue) + .sum(); + } + + public static long sumTypeParameter(List numbers) { + return numbers.stream() + .mapToLong(Number::longValue) + .sum(); + } + + public static long sumWildcard(List numbers) { + return numbers.stream() + .mapToLong(Number::longValue) + .sum(); + } + + public static void addNumber(List list, Integer number) { + list.add(number); + } + +} diff --git a/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/generics/CollectionUtilsDemo.java b/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/generics/CollectionUtilsDemo.java new file mode 100644 index 0000000000..012d9a3110 --- /dev/null +++ b/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/generics/CollectionUtilsDemo.java @@ -0,0 +1,48 @@ +package com.baeldung.generics; + +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class CollectionUtilsDemo { + + private static final Logger logger = LoggerFactory.getLogger(CollectionUtilsDemo.class); + + public static void main(String[] args) { + CollectionUtils.print("Baeldung"); + + List numbers1 = new ArrayList<>(); + numbers1.add(5); + numbers1.add(10L); + + List numbers2 = new ArrayList<>(); + numbers2.add(15f); + numbers2.add(20.0); + + List numbersMerged = CollectionUtils.mergeTypeParameter(numbers1, numbers2); + logger.info("Merged numbers: {}", numbersMerged); + + List numbers = new ArrayList<>(); + numbers.add(5); + numbers.add(10L); + numbers.add(15f); + numbers.add(20.0); + + logger.info("Sum: {}", CollectionUtils.sum(numbers)); + logger.info("Sum (wildcard): {}", CollectionUtils.sumWildcard(numbers)); + logger.info("Sum (type parameter): {}", CollectionUtils.sumTypeParameter(numbers)); + + List integers = new ArrayList<>(); + integers.add(5); + logger.info("Sum integers (wildcard): {}", CollectionUtils.sumWildcard(integers)); + + CollectionUtils.addNumber(numbers, 4); + CollectionUtils.addNumber(integers, 5); + + logger.info("Before swap: {}", numbers); + CollectionUtils.swap(numbers, 0, 1); + logger.info("After swap: {}", numbers); + } +} diff --git a/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/generics/Dog.java b/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/generics/Dog.java new file mode 100644 index 0000000000..cec6f39422 --- /dev/null +++ b/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/generics/Dog.java @@ -0,0 +1,14 @@ +package com.baeldung.generics; + +public class Dog extends Animal { + + public Dog(String type, String name) { + super(type, name); + } + + @Override + public String makeSound() { + return "Wuf"; + } + +} diff --git a/core-java-modules/core-java-lang-5/src/test/java/com/baeldung/convertinttochar/ConvertCharToIntUnitTest.java b/core-java-modules/core-java-lang-5/src/test/java/com/baeldung/convertinttochar/ConvertCharToIntUnitTest.java new file mode 100644 index 0000000000..75826cd7be --- /dev/null +++ b/core-java-modules/core-java-lang-5/src/test/java/com/baeldung/convertinttochar/ConvertCharToIntUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.convertinttochar; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class ConvertCharToIntUnitTest { + + @Test + public void givenAChar_whenUsingGetNumericValue_thenExpectedNumericType() { + //char value + char c = '7'; + // using getNumericValue + int n = Character.getNumericValue(c); + + assertEquals(7, n); + } + + @Test + public void givenAChar_whenSubtracting0_thenExpectedNumericType() { + //char value + char c = '7'; + // subtract '0' from the char + int n = c - '0'; + + assertEquals(7, n); + } + + @Test + public void givenAChar_whenUsingParseInt_thenExpectedNumericType() { + //char value + char c = '7'; + // using parseInt + int n = Integer.parseInt(String.valueOf(c)); + + assertEquals(7, n); + } + + @Test + public void givenAChar_whenCastingFromCharToInt_thenExpectedUnicodeRepresentation() { + //char value + char c = '7'; + //cast to int + assertEquals(55, (int) c); + } + +} diff --git a/core-java-modules/core-java-lang-5/src/test/java/com/baeldung/convertinttochar/ConvertIntToCharUnitTest.java b/core-java-modules/core-java-lang-5/src/test/java/com/baeldung/convertinttochar/ConvertIntToCharUnitTest.java new file mode 100644 index 0000000000..276bcbc55b --- /dev/null +++ b/core-java-modules/core-java-lang-5/src/test/java/com/baeldung/convertinttochar/ConvertIntToCharUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.convertinttochar; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class ConvertIntToCharUnitTest { + + @Test + public void givenAnInt_whenAdding0_thenExpectedCharType() { + int num = 7; + //add '0' to convert int to char + char c = (char) ('0' + num); + + assertEquals('7', c); + } + + @Test + public void givenAnInt_whenUsingForDigit_thenExpectedCharType() { + int num = 7; + // Convert using forDigit() method + char c = Character.forDigit(num, 10); + + assertEquals('7', c); + } + + @Test + public void givenAnInt_whenUsingToString_thenExpectedCharType() { + int num = 7; + //convert int to char using toString() + char c = Integer.toString(num) + .charAt(0); + + assertEquals('7', c); + } +} diff --git a/core-java-modules/core-java-lang-math-3/src/main/java/com/baeldung/math/pascaltriangle/PascalTriangle.java b/core-java-modules/core-java-lang-math-3/src/main/java/com/baeldung/math/pascaltriangle/PascalTriangle.java new file mode 100644 index 0000000000..ae47a48375 --- /dev/null +++ b/core-java-modules/core-java-lang-math-3/src/main/java/com/baeldung/math/pascaltriangle/PascalTriangle.java @@ -0,0 +1,48 @@ +package com.baeldung.math.pascaltriangle; + +public class PascalTriangle { + + public static int factorial(int i) { + if (i == 0) { + return 1; + } + return i * factorial(i - 1); + } + + private static void printUseRecursion(int n) { + for (int i = 0; i <= n; i++) { + for (int j = 0; j <= n - i; j++) { + System.out.print(" "); + } + + for (int k = 0; k <= i; k++) { + System.out.print(" " + factorial(i) / (factorial(i - k) * factorial(k))); + } + + System.out.println(); + } + } + +public static void printUseBinomialExpansion(int n) { + for (int line = 1; line <= n; line++) { + for (int j = 0; j <= n - line; j++) { + System.out.print(" "); + } + + int k = 1; + for (int i = 1; i <= line; i++) { + System.out.print(k + " "); + k = k * (line - i) / i; + } + + System.out.println(); + } +} + + public static void main(String[] args) { + int n = 5; + printUseRecursion(n); +// printUseBinomialExpansion(n); + } + +} diff --git a/core-java-modules/core-java-lang-operators-2/pom.xml b/core-java-modules/core-java-lang-operators-2/pom.xml index c36250f1ae..9d925c553a 100644 --- a/core-java-modules/core-java-lang-operators-2/pom.xml +++ b/core-java-modules/core-java-lang-operators-2/pom.xml @@ -38,4 +38,4 @@ - \ No newline at end of file + diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 53ad13a3c0..ed98e9d322 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -73,6 +73,7 @@ core-java-jndi core-java-jvm core-java-jvm-2 + core-java-jvm-3 core-java-lambdas core-java-lang core-java-lang-2 diff --git a/ddd-contexts/infrastructure/pom.xml b/ddd-contexts/ddd-contexts-infrastructure/pom.xml similarity index 87% rename from ddd-contexts/infrastructure/pom.xml rename to ddd-contexts/ddd-contexts-infrastructure/pom.xml index 6107991ceb..beceaa7fb2 100644 --- a/ddd-contexts/infrastructure/pom.xml +++ b/ddd-contexts/ddd-contexts-infrastructure/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.dddcontexts.infrastructure - infrastructure + ddd-contexts-infrastructure 1.0 jar @@ -18,17 +18,17 @@ com.baeldung.dddcontexts.shippingcontext - shippingcontext + ddd-contexts-shippingcontext ${appmodules.version} com.baeldung.dddcontexts.ordercontext - ordercontext + ddd-contexts-ordercontext ${appmodules.version} com.baeldung.dddcontexts.sharedkernel - sharedkernel + ddd-contexts-sharedkernel ${appmodules.version} diff --git a/ddd-contexts/infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/db/InMemoryOrderStore.java b/ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/db/InMemoryOrderStore.java similarity index 100% rename from ddd-contexts/infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/db/InMemoryOrderStore.java rename to ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/db/InMemoryOrderStore.java diff --git a/ddd-contexts/infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/events/SimpleEventBus.java b/ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/events/SimpleEventBus.java similarity index 100% rename from ddd-contexts/infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/events/SimpleEventBus.java rename to ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/events/SimpleEventBus.java diff --git a/ddd-contexts/infrastructure/src/main/java/module-info.java b/ddd-contexts/ddd-contexts-infrastructure/src/main/java/module-info.java similarity index 100% rename from ddd-contexts/infrastructure/src/main/java/module-info.java rename to ddd-contexts/ddd-contexts-infrastructure/src/main/java/module-info.java diff --git a/ddd-contexts/mainapp/pom.xml b/ddd-contexts/ddd-contexts-mainapp/pom.xml similarity index 93% rename from ddd-contexts/mainapp/pom.xml rename to ddd-contexts/ddd-contexts-mainapp/pom.xml index 8046ae4e7d..6f7461e15b 100644 --- a/ddd-contexts/mainapp/pom.xml +++ b/ddd-contexts/ddd-contexts-mainapp/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.dddcontexts.mainapp - mainapp + ddd-contexts-mainapp 1.0 jar @@ -18,7 +18,7 @@ com.baeldung.dddcontexts.infrastructure - infrastructure + ddd-contexts-infrastructure ${appmodules.version} diff --git a/ddd-contexts/mainapp/src/main/java/com/baeldung/dddcontexts/mainapp/Application.java b/ddd-contexts/ddd-contexts-mainapp/src/main/java/com/baeldung/dddcontexts/mainapp/Application.java similarity index 100% rename from ddd-contexts/mainapp/src/main/java/com/baeldung/dddcontexts/mainapp/Application.java rename to ddd-contexts/ddd-contexts-mainapp/src/main/java/com/baeldung/dddcontexts/mainapp/Application.java diff --git a/ddd-contexts/mainapp/src/main/java/module-info.java b/ddd-contexts/ddd-contexts-mainapp/src/main/java/module-info.java similarity index 100% rename from ddd-contexts/mainapp/src/main/java/module-info.java rename to ddd-contexts/ddd-contexts-mainapp/src/main/java/module-info.java diff --git a/ddd-contexts/ordercontext/pom.xml b/ddd-contexts/ddd-contexts-ordercontext/pom.xml similarity index 92% rename from ddd-contexts/ordercontext/pom.xml rename to ddd-contexts/ddd-contexts-ordercontext/pom.xml index e29f109b71..d6e5811357 100644 --- a/ddd-contexts/ordercontext/pom.xml +++ b/ddd-contexts/ddd-contexts-ordercontext/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.dddcontexts.ordercontext - ordercontext + ddd-contexts-ordercontext 1.0 jar @@ -17,7 +17,7 @@ com.baeldung.dddcontexts.sharedkernel - sharedkernel + ddd-contexts-sharedkernel ${appmodules.version} diff --git a/ddd-contexts/ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/CustomerOrder.java b/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/CustomerOrder.java similarity index 100% rename from ddd-contexts/ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/CustomerOrder.java rename to ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/CustomerOrder.java diff --git a/ddd-contexts/ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/OrderItem.java b/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/OrderItem.java similarity index 100% rename from ddd-contexts/ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/OrderItem.java rename to ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/OrderItem.java diff --git a/ddd-contexts/ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/repository/CustomerOrderRepository.java b/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/repository/CustomerOrderRepository.java similarity index 100% rename from ddd-contexts/ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/repository/CustomerOrderRepository.java rename to ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/repository/CustomerOrderRepository.java diff --git a/ddd-contexts/ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/CustomerOrderService.java b/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/CustomerOrderService.java similarity index 100% rename from ddd-contexts/ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/CustomerOrderService.java rename to ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/CustomerOrderService.java diff --git a/ddd-contexts/ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/OrderService.java b/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/OrderService.java similarity index 100% rename from ddd-contexts/ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/OrderService.java rename to ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/OrderService.java diff --git a/ddd-contexts/ordercontext/src/main/java/module-info.java b/ddd-contexts/ddd-contexts-ordercontext/src/main/java/module-info.java similarity index 100% rename from ddd-contexts/ordercontext/src/main/java/module-info.java rename to ddd-contexts/ddd-contexts-ordercontext/src/main/java/module-info.java diff --git a/ddd-contexts/sharedkernel/pom.xml b/ddd-contexts/ddd-contexts-sharedkernel/pom.xml similarity index 95% rename from ddd-contexts/sharedkernel/pom.xml rename to ddd-contexts/ddd-contexts-sharedkernel/pom.xml index 5d31973c92..7c159dc741 100644 --- a/ddd-contexts/sharedkernel/pom.xml +++ b/ddd-contexts/ddd-contexts-sharedkernel/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.dddcontexts.sharedkernel - sharedkernel + ddd-contexts-sharedkernel 1.0 jar diff --git a/ddd-contexts/sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/ApplicationEvent.java b/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/ApplicationEvent.java similarity index 100% rename from ddd-contexts/sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/ApplicationEvent.java rename to ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/ApplicationEvent.java diff --git a/ddd-contexts/sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventBus.java b/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventBus.java similarity index 100% rename from ddd-contexts/sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventBus.java rename to ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventBus.java diff --git a/ddd-contexts/sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventSubscriber.java b/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventSubscriber.java similarity index 100% rename from ddd-contexts/sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventSubscriber.java rename to ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventSubscriber.java diff --git a/ddd-contexts/sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/service/ApplicationService.java b/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/service/ApplicationService.java similarity index 100% rename from ddd-contexts/sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/service/ApplicationService.java rename to ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/service/ApplicationService.java diff --git a/ddd-contexts/sharedkernel/src/main/java/module-info.java b/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/module-info.java similarity index 100% rename from ddd-contexts/sharedkernel/src/main/java/module-info.java rename to ddd-contexts/ddd-contexts-sharedkernel/src/main/java/module-info.java diff --git a/ddd-contexts/shippingcontext/pom.xml b/ddd-contexts/ddd-contexts-shippingcontext/pom.xml similarity index 91% rename from ddd-contexts/shippingcontext/pom.xml rename to ddd-contexts/ddd-contexts-shippingcontext/pom.xml index 2fb9e83645..5abdf70948 100644 --- a/ddd-contexts/shippingcontext/pom.xml +++ b/ddd-contexts/ddd-contexts-shippingcontext/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.dddcontexts.shippingcontext - shippingcontext + ddd-contexts-shippingcontext 1.0 jar @@ -17,7 +17,7 @@ com.baeldung.dddcontexts.sharedkernel - sharedkernel + ddd-contexts-sharedkernel ${appmodules.version} diff --git a/ddd-contexts/shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/PackageItem.java b/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/PackageItem.java similarity index 100% rename from ddd-contexts/shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/PackageItem.java rename to ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/PackageItem.java diff --git a/ddd-contexts/shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/Parcel.java b/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/Parcel.java similarity index 100% rename from ddd-contexts/shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/Parcel.java rename to ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/Parcel.java diff --git a/ddd-contexts/shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/ShippableOrder.java b/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/ShippableOrder.java similarity index 100% rename from ddd-contexts/shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/ShippableOrder.java rename to ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/ShippableOrder.java diff --git a/ddd-contexts/shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/repository/ShippingOrderRepository.java b/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/repository/ShippingOrderRepository.java similarity index 100% rename from ddd-contexts/shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/repository/ShippingOrderRepository.java rename to ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/repository/ShippingOrderRepository.java diff --git a/ddd-contexts/shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ParcelShippingService.java b/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ParcelShippingService.java similarity index 100% rename from ddd-contexts/shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ParcelShippingService.java rename to ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ParcelShippingService.java diff --git a/ddd-contexts/shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ShippingService.java b/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ShippingService.java similarity index 100% rename from ddd-contexts/shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ShippingService.java rename to ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ShippingService.java diff --git a/ddd-contexts/shippingcontext/src/main/java/module-info.java b/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/module-info.java similarity index 100% rename from ddd-contexts/shippingcontext/src/main/java/module-info.java rename to ddd-contexts/ddd-contexts-shippingcontext/src/main/java/module-info.java diff --git a/ddd-contexts/pom.xml b/ddd-contexts/pom.xml index 1a764a65b9..961a1d1624 100644 --- a/ddd-contexts/pom.xml +++ b/ddd-contexts/pom.xml @@ -16,11 +16,11 @@ - sharedkernel - infrastructure - shippingcontext - ordercontext - mainapp + ddd-contexts-sharedkernel + ddd-contexts-infrastructure + ddd-contexts-shippingcontext + ddd-contexts-ordercontext + ddd-contexts-mainapp diff --git a/di-modules/cdi/pom.xml b/di-modules/cdi/pom.xml index 6b2382ba0e..647192bed2 100644 --- a/di-modules/cdi/pom.xml +++ b/di-modules/cdi/pom.xml @@ -10,7 +10,7 @@ com.baeldung parent-spring-5 0.0.1-SNAPSHOT - ../parent-spring-5 + ../../parent-spring-5 diff --git a/httpclient-simple/src/main/java/com/baeldung/handler/CustomHttpClientResponseHandler.java b/httpclient-simple/src/main/java/com/baeldung/handler/CustomHttpClientResponseHandler.java new file mode 100644 index 0000000000..5472da3a97 --- /dev/null +++ b/httpclient-simple/src/main/java/com/baeldung/handler/CustomHttpClientResponseHandler.java @@ -0,0 +1,11 @@ +package com.baeldung.handler; + +import org.apache.hc.core5.http.ClassicHttpResponse; +import org.apache.hc.core5.http.io.HttpClientResponseHandler; + +public class CustomHttpClientResponseHandler implements HttpClientResponseHandler { + @Override + public ClassicHttpResponse handleResponse(ClassicHttpResponse response) { + return response; + } +} \ No newline at end of file diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/sec/HttpClientCookieLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/sec/HttpClientCookieLiveTest.java index 75286e5b2e..82a2d8e9d6 100644 --- a/httpclient-simple/src/test/java/com/baeldung/httpclient/sec/HttpClientCookieLiveTest.java +++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/sec/HttpClientCookieLiveTest.java @@ -1,114 +1,87 @@ package com.baeldung.httpclient.sec; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.cookie.ClientCookie; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.cookie.BasicClientCookie; -import org.apache.http.protocol.BasicHttpContext; -import org.apache.http.protocol.HttpContext; -import com.baeldung.httpclient.ResponseUtil; +import com.baeldung.handler.CustomHttpClientResponseHandler; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.cookie.BasicCookieStore; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.client5.http.impl.cookie.BasicClientCookie; +import org.apache.hc.client5.http.protocol.HttpClientContext; + +import org.apache.hc.core5.http.protocol.BasicHttpContext; +import org.apache.hc.core5.http.protocol.HttpContext; +import org.junit.jupiter.api.Test; import java.io.IOException; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -public class HttpClientCookieLiveTest { - - private CloseableHttpClient instance; - - private CloseableHttpResponse response; - - private static Logger log = LoggerFactory.getLogger(HttpClientCookieLiveTest.class); - - @Before - public final void before() { - instance = HttpClientBuilder.create().build(); - } - - @After - public final void after() throws IllegalStateException, IOException { - ResponseUtil.closeResponse(response); - } - - // tests +class HttpClientCookieLiveTest { @Test - public final void whenSettingCookiesOnARequest_thenCorrect() throws IOException { - instance = HttpClientBuilder.create().build(); + final void whenSettingCookiesOnARequest_thenCorrect() throws IOException { final HttpGet request = new HttpGet("http://www.github.com"); request.setHeader("Cookie", "JSESSIONID=1234"); - - response = instance.execute(request); - - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = (CloseableHttpResponse) client.execute(request, new CustomHttpClientResponseHandler());) { + assertThat(response.getCode(), equalTo(200)); + } } @Test - public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws IOException { + final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws IOException { final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); cookie.setDomain(".github.com"); - cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true"); - + cookie.setAttribute("domain", "true"); cookie.setPath("/"); cookieStore.addCookie(cookie); - - DefaultHttpClient client = new DefaultHttpClient(); - client.setCookieStore(cookieStore); - final HttpGet request = new HttpGet("https://www.github.com"); + try (CloseableHttpClient client = HttpClientBuilder.create() + .setDefaultCookieStore(cookieStore) + .build(); CloseableHttpResponse response = (CloseableHttpResponse) client.execute(request, new CustomHttpClientResponseHandler())) { - response = (CloseableHttpResponse) client.execute(request); - - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertThat(response.getCode(), equalTo(200)); + } } @Test - public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws IOException { + final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws IOException { final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); cookie.setDomain(".github.com"); - cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true"); + cookie.setAttribute("domain", "true"); cookie.setPath("/"); cookieStore.addCookie(cookie); - instance = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build(); - final HttpGet request = new HttpGet("http://www.github.com"); - response = instance.execute(request); + try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build(); + CloseableHttpResponse response = (CloseableHttpResponse) client.execute(request, new CustomHttpClientResponseHandler())) { + + assertThat(response.getCode(), equalTo(200)); + } - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } @Test - public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws IOException { + final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws IOException { final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); cookie.setDomain(".github.com"); cookie.setPath("/"); cookieStore.addCookie(cookie); - instance = HttpClientBuilder.create().build(); - final HttpGet request = new HttpGet("http://www.github.com"); - final HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); // localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // before 4.3 - response = instance.execute(request, localContext); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + try (CloseableHttpClient client = HttpClientBuilder.create().build(); + CloseableHttpResponse response = (CloseableHttpResponse) client.execute(request, localContext, new CustomHttpClientResponseHandler())) { + assertThat(response.getCode(), equalTo(200)); + } } } diff --git a/json-modules/json-2/pom.xml b/json-modules/json-2/pom.xml index ecffd719c7..ee58ab8b25 100644 --- a/json-modules/json-2/pom.xml +++ b/json-modules/json-2/pom.xml @@ -108,6 +108,17 @@ + + commons-io + commons-io + 2.11.0 + + + org.junit.jupiter + junit-jupiter + RELEASE + test + diff --git a/json-modules/json-2/src/main/java/com/baeldung/jsonvaluegetter/JSONObjectValueGetter.java b/json-modules/json-2/src/main/java/com/baeldung/jsonvaluegetter/JSONObjectValueGetter.java new file mode 100644 index 0000000000..f8d38106fd --- /dev/null +++ b/json-modules/json-2/src/main/java/com/baeldung/jsonvaluegetter/JSONObjectValueGetter.java @@ -0,0 +1,87 @@ +package com.baeldung.jsonvaluegetter; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.List; + +public class JSONObjectValueGetter { + + /** + * Get values associated with the provided key in the given JSONObject instance + * + * @param jsonObject JSONObject instance in which to search the key + * @param key Key we're interested in + * + * @return List of values associated with the given key, in the order of appearance. + * If the key is absent, empty list is returned. + */ + public List getValuesInObject(JSONObject jsonObject, String key) { + List accumulatedValues = new ArrayList<>(); + for (String currentKey : jsonObject.keySet()) { + Object value = jsonObject.get(currentKey); + if (currentKey.equals(key)) { + accumulatedValues.add(value.toString()); + } + + if (value instanceof JSONObject) { + accumulatedValues.addAll(getValuesInObject((JSONObject)value, key)); + } else if (value instanceof JSONArray) { + accumulatedValues.addAll(getValuesInArray((JSONArray)value, key)); + } + } + + return accumulatedValues; + } + + /** + * Get values associated with the provided key in the given JSONArray instance + * + * @param jsonArray JSONArray instance in which to search the key + * @param key Key we're interested in + * + * @return List of values associated with the given key, in the order of appearance. + * If the key is absent, empty list is returned. + */ + public List getValuesInArray(JSONArray jsonArray, String key) { + List accumulatedValues = new ArrayList<>(); + for (Object obj : jsonArray) { + if (obj instanceof JSONArray) { + accumulatedValues.addAll(getValuesInArray((JSONArray)obj, key)); + } else if (obj instanceof JSONObject) { + accumulatedValues.addAll(getValuesInObject((JSONObject)obj, key)); + } + } + + return accumulatedValues; + } + + /** + * Among all the values associated with the given key, get the N-th value + * + * @param jsonObject JSONObject instance in which to search the key + * @param key Key we're interested in + * @param N Index of the value to get + * + * @return N-th value associated with the key, or null if the key is absent or + * the number of values associated with the key is less than N + */ + public String getNthValue(JSONObject jsonObject, String key, int N) { + List values = getValuesInObject(jsonObject, key); + return (values.size() >= N) ? values.get(N - 1) : null; + } + + /** + * Count the number of values associated with the given key + * + * @param jsonObject JSONObject instance in which to count the key + * @param key Key we're interested in + * + * @return The number of values associated with the given key + */ + public int getCount(JSONObject jsonObject, String key) { + List values = getValuesInObject(jsonObject, key); + return values.size(); + } +} diff --git a/json-modules/json-2/src/test/java/com/baeldung/jsonvaluegetter/JSONObjectValueGetterUnitTest.java b/json-modules/json-2/src/test/java/com/baeldung/jsonvaluegetter/JSONObjectValueGetterUnitTest.java new file mode 100644 index 0000000000..fc17e700eb --- /dev/null +++ b/json-modules/json-2/src/test/java/com/baeldung/jsonvaluegetter/JSONObjectValueGetterUnitTest.java @@ -0,0 +1,69 @@ +package com.baeldung.jsonvaluegetter; + +import org.apache.commons.io.IOUtils; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +public class JSONObjectValueGetterUnitTest { + + private static JSONObject jsonObject; + private static JSONObjectValueGetter jsonObjectValueGetter = new JSONObjectValueGetter(); + + @BeforeAll + public static void loadJsonContent() throws IOException { + InputStream inputStream = JSONObjectValueGetterUnitTest.class.getClassLoader().getResourceAsStream("employee.json"); + String jsonString = IOUtils.toString(inputStream, "UTF-8"); + jsonObject = new JSONObject(jsonString); + } + + @Test + public void getValueDirectly() { + JSONArray family = jsonObject.getJSONArray("family"); + JSONObject sonObject = family.getJSONObject(1); + JSONObject sonData = sonObject.getJSONObject("son"); + String sonName = sonData.getString("name"); + Assertions.assertEquals(sonName, "Peter"); + } + + @Test + public void getAllAssociatedValuesRecursively() { + List values = jsonObjectValueGetter.getValuesInObject(jsonObject, "son"); + Assertions.assertEquals(values.size(), 1); + + String sonString = values.get(0); + Assertions.assertTrue(sonString.contains("Peter")); + Assertions.assertTrue(sonString.contains("Schoolboy")); + Assertions.assertTrue(sonString.contains("11")); + + values = jsonObjectValueGetter.getValuesInObject(jsonObject, "name"); + Assertions.assertEquals(values.size(), 3); + + Assertions.assertEquals(values.get(0), "Bob"); + Assertions.assertEquals(values.get(1), "Alice"); + Assertions.assertEquals(values.get(2), "Peter"); + } + + @Test + public void getNthValueRecursively() { + Assertions.assertEquals(jsonObjectValueGetter.getNthValue(jsonObject, "name", 1), "Bob"); + Assertions.assertEquals(jsonObjectValueGetter.getNthValue(jsonObject, "name", 2), "Alice"); + Assertions.assertEquals(jsonObjectValueGetter.getNthValue(jsonObject, "name", 3), "Peter"); + Assertions.assertNull(jsonObjectValueGetter.getNthValue(jsonObject, "nonExistingKey", 1)); + } + + @Test + public void getCountRecursively() { + Assertions.assertEquals(jsonObjectValueGetter.getCount(jsonObject, "name"), 3); + Assertions.assertEquals(jsonObjectValueGetter.getCount(jsonObject, "age"), 3); + Assertions.assertEquals(jsonObjectValueGetter.getCount(jsonObject, "occupation"), 1); + Assertions.assertEquals(jsonObjectValueGetter.getCount(jsonObject, "nonExistingKey"), 0); + } +} diff --git a/json-modules/json-2/src/test/resources/employee.json b/json-modules/json-2/src/test/resources/employee.json new file mode 100644 index 0000000000..095190212a --- /dev/null +++ b/json-modules/json-2/src/test/resources/employee.json @@ -0,0 +1,30 @@ +{ + "name" : "Bob", + "profession" : "Software engineer", + "department" : "Research", + "age" : 40, + "family" : [ + { + "wife" : { + "name" : "Alice", + "profession" : "Doctor", + "age" : 38 + } + }, + { + "son" : { + "name" : "Peter", + "occupation" : "Schoolboy", + "age" : 11 + } + } + ], + "performance" : [ + { + "2020" : 4.5 + }, + { + "2021" : 4.8 + } + ] +} \ No newline at end of file diff --git a/maven-modules/multimodulemavenproject/daomodule/pom.xml b/maven-modules/multimodulemavenproject/maven-daomodule/pom.xml similarity index 96% rename from maven-modules/multimodulemavenproject/daomodule/pom.xml rename to maven-modules/multimodulemavenproject/maven-daomodule/pom.xml index 626a6f707a..474cc20adb 100644 --- a/maven-modules/multimodulemavenproject/daomodule/pom.xml +++ b/maven-modules/multimodulemavenproject/maven-daomodule/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.daomodule - daomodule + maven-daomodule 1.0 jar diff --git a/maven-modules/multimodulemavenproject/daomodule/src/main/java/com/baeldung/daomodule/Dao.java b/maven-modules/multimodulemavenproject/maven-daomodule/src/main/java/com/baeldung/daomodule/Dao.java similarity index 100% rename from maven-modules/multimodulemavenproject/daomodule/src/main/java/com/baeldung/daomodule/Dao.java rename to maven-modules/multimodulemavenproject/maven-daomodule/src/main/java/com/baeldung/daomodule/Dao.java diff --git a/maven-modules/multimodulemavenproject/daomodule/src/main/java/module-info.java b/maven-modules/multimodulemavenproject/maven-daomodule/src/main/java/module-info.java similarity index 100% rename from maven-modules/multimodulemavenproject/daomodule/src/main/java/module-info.java rename to maven-modules/multimodulemavenproject/maven-daomodule/src/main/java/module-info.java diff --git a/maven-modules/multimodulemavenproject/entitymodule/pom.xml b/maven-modules/multimodulemavenproject/maven-entitymodule/pom.xml similarity index 96% rename from maven-modules/multimodulemavenproject/entitymodule/pom.xml rename to maven-modules/multimodulemavenproject/maven-entitymodule/pom.xml index e2a453b9c2..a9b169a8b9 100644 --- a/maven-modules/multimodulemavenproject/entitymodule/pom.xml +++ b/maven-modules/multimodulemavenproject/maven-entitymodule/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.entitymodule - entitymodule + maven-entitymodule 1.0 jar diff --git a/maven-modules/multimodulemavenproject/entitymodule/src/main/java/com/baeldung/entitymodule/User.java b/maven-modules/multimodulemavenproject/maven-entitymodule/src/main/java/com/baeldung/entitymodule/User.java similarity index 100% rename from maven-modules/multimodulemavenproject/entitymodule/src/main/java/com/baeldung/entitymodule/User.java rename to maven-modules/multimodulemavenproject/maven-entitymodule/src/main/java/com/baeldung/entitymodule/User.java diff --git a/maven-modules/multimodulemavenproject/entitymodule/src/main/java/module-info.java b/maven-modules/multimodulemavenproject/maven-entitymodule/src/main/java/module-info.java similarity index 100% rename from maven-modules/multimodulemavenproject/entitymodule/src/main/java/module-info.java rename to maven-modules/multimodulemavenproject/maven-entitymodule/src/main/java/module-info.java diff --git a/maven-modules/multimodulemavenproject/mainappmodule/pom.xml b/maven-modules/multimodulemavenproject/maven-mainappmodule/pom.xml similarity index 89% rename from maven-modules/multimodulemavenproject/mainappmodule/pom.xml rename to maven-modules/multimodulemavenproject/maven-mainappmodule/pom.xml index c376a2b04e..0dd11ef991 100644 --- a/maven-modules/multimodulemavenproject/mainappmodule/pom.xml +++ b/maven-modules/multimodulemavenproject/maven-mainappmodule/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.mainappmodule - mainappmodule + maven-mainappmodule 1.0 jar @@ -17,17 +17,17 @@ com.baeldung.entitymodule - entitymodule + maven-entitymodule ${entitymodule.version} com.baeldung.daomodule - daomodule + maven-daomodule ${daomodule.version} com.baeldung.userdaomodule - userdaomodule + maven-userdaomodule ${userdaomodule.version} diff --git a/maven-modules/multimodulemavenproject/mainappmodule/src/main/java/com/baeldung/mainappmodule/Application.java b/maven-modules/multimodulemavenproject/maven-mainappmodule/src/main/java/com/baeldung/mainappmodule/Application.java similarity index 100% rename from maven-modules/multimodulemavenproject/mainappmodule/src/main/java/com/baeldung/mainappmodule/Application.java rename to maven-modules/multimodulemavenproject/maven-mainappmodule/src/main/java/com/baeldung/mainappmodule/Application.java diff --git a/maven-modules/multimodulemavenproject/mainappmodule/src/main/java/module-info.java b/maven-modules/multimodulemavenproject/maven-mainappmodule/src/main/java/module-info.java similarity index 100% rename from maven-modules/multimodulemavenproject/mainappmodule/src/main/java/module-info.java rename to maven-modules/multimodulemavenproject/maven-mainappmodule/src/main/java/module-info.java diff --git a/maven-modules/multimodulemavenproject/userdaomodule/pom.xml b/maven-modules/multimodulemavenproject/maven-userdaomodule/pom.xml similarity index 97% rename from maven-modules/multimodulemavenproject/userdaomodule/pom.xml rename to maven-modules/multimodulemavenproject/maven-userdaomodule/pom.xml index 4df29457c5..c7ceada17d 100644 --- a/maven-modules/multimodulemavenproject/userdaomodule/pom.xml +++ b/maven-modules/multimodulemavenproject/maven-userdaomodule/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.userdaomodule - userdaomodule + maven-userdaomodule 1.0 jar diff --git a/maven-modules/multimodulemavenproject/userdaomodule/src/main/java/com/baeldung/userdaomodule/UserDao.java b/maven-modules/multimodulemavenproject/maven-userdaomodule/src/main/java/com/baeldung/userdaomodule/UserDao.java similarity index 100% rename from maven-modules/multimodulemavenproject/userdaomodule/src/main/java/com/baeldung/userdaomodule/UserDao.java rename to maven-modules/multimodulemavenproject/maven-userdaomodule/src/main/java/com/baeldung/userdaomodule/UserDao.java diff --git a/maven-modules/multimodulemavenproject/userdaomodule/src/main/java/module-info.java b/maven-modules/multimodulemavenproject/maven-userdaomodule/src/main/java/module-info.java similarity index 100% rename from maven-modules/multimodulemavenproject/userdaomodule/src/main/java/module-info.java rename to maven-modules/multimodulemavenproject/maven-userdaomodule/src/main/java/module-info.java diff --git a/maven-modules/multimodulemavenproject/pom.xml b/maven-modules/multimodulemavenproject/pom.xml index fbafa7ebff..db0bda3e6e 100644 --- a/maven-modules/multimodulemavenproject/pom.xml +++ b/maven-modules/multimodulemavenproject/pom.xml @@ -17,10 +17,10 @@ - entitymodule - daomodule - userdaomodule - mainappmodule + maven-entitymodule + maven-daomodule + maven-userdaomodule + maven-mainappmodule diff --git a/maven-modules/version-collision/pom.xml b/maven-modules/version-collision/pom.xml index 9c1b9641c8..820689abfa 100644 --- a/maven-modules/version-collision/pom.xml +++ b/maven-modules/version-collision/pom.xml @@ -13,8 +13,8 @@ - project-a - project-b + version-collision-project-a + version-collision-project-b project-collision diff --git a/maven-modules/version-collision/project-collision/pom.xml b/maven-modules/version-collision/project-collision/pom.xml index 74f117cdbb..1ef4440719 100644 --- a/maven-modules/version-collision/project-collision/pom.xml +++ b/maven-modules/version-collision/project-collision/pom.xml @@ -14,7 +14,7 @@ com.baeldung - project-a + version-collision-project-a 0.0.1-SNAPSHOT @@ -26,7 +26,7 @@ com.baeldung - project-b + version-collision-project-b 0.0.1-SNAPSHOT diff --git a/maven-modules/version-collision/project-a/pom.xml b/maven-modules/version-collision/version-collision-project-a/pom.xml similarity index 92% rename from maven-modules/version-collision/project-a/pom.xml rename to maven-modules/version-collision/version-collision-project-a/pom.xml index ca06c7daca..6130334b2c 100644 --- a/maven-modules/version-collision/project-a/pom.xml +++ b/maven-modules/version-collision/version-collision-project-a/pom.xml @@ -3,7 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - project-a + version-collision-project-a version-collision diff --git a/maven-modules/version-collision/project-b/pom.xml b/maven-modules/version-collision/version-collision-project-b/pom.xml similarity index 92% rename from maven-modules/version-collision/project-b/pom.xml rename to maven-modules/version-collision/version-collision-project-b/pom.xml index a7185ab22d..e2e7294cd2 100644 --- a/maven-modules/version-collision/project-b/pom.xml +++ b/maven-modules/version-collision/version-collision-project-b/pom.xml @@ -3,7 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - project-b + version-collision-project-b version-collision diff --git a/maven-modules/version-overriding-plugins/pom.xml b/maven-modules/version-overriding-plugins/pom.xml index 79109a83e1..b98a444bd4 100644 --- a/maven-modules/version-overriding-plugins/pom.xml +++ b/maven-modules/version-overriding-plugins/pom.xml @@ -13,8 +13,8 @@ - child-a - child-b + version-overriding-child-a + version-overriding-child-b diff --git a/maven-modules/version-overriding-plugins/child-a/pom.xml b/maven-modules/version-overriding-plugins/version-overriding-child-a/pom.xml similarity index 95% rename from maven-modules/version-overriding-plugins/child-a/pom.xml rename to maven-modules/version-overriding-plugins/version-overriding-child-a/pom.xml index 45098ccef0..48b5782f72 100644 --- a/maven-modules/version-overriding-plugins/child-a/pom.xml +++ b/maven-modules/version-overriding-plugins/version-overriding-child-a/pom.xml @@ -3,7 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - child-a + version-overriding-child-a pom diff --git a/maven-modules/version-overriding-plugins/child-b/pom.xml b/maven-modules/version-overriding-plugins/version-overriding-child-b/pom.xml similarity index 89% rename from maven-modules/version-overriding-plugins/child-b/pom.xml rename to maven-modules/version-overriding-plugins/version-overriding-child-b/pom.xml index f86a3c2096..8e52b34dbc 100644 --- a/maven-modules/version-overriding-plugins/child-b/pom.xml +++ b/maven-modules/version-overriding-plugins/version-overriding-child-b/pom.xml @@ -3,7 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - child-b + version-overriding-child-b version-overriding-plugins diff --git a/parent-spring-5/pom.xml b/parent-spring-5/pom.xml index 3525522ea7..80a8c7d77d 100644 --- a/parent-spring-5/pom.xml +++ b/parent-spring-5/pom.xml @@ -24,9 +24,9 @@ - 5.3.23 + 5.3.24 5.7.3 1.5.10.RELEASE - \ No newline at end of file + diff --git a/persistence-modules/blaze-persistence/README.md b/persistence-modules/blaze-persistence/README.md new file mode 100644 index 0000000000..7d843af9ea --- /dev/null +++ b/persistence-modules/blaze-persistence/README.md @@ -0,0 +1 @@ +### Relevant Articles: diff --git a/persistence-modules/blaze-persistence/pom.xml b/persistence-modules/blaze-persistence/pom.xml new file mode 100644 index 0000000000..cc57785fe9 --- /dev/null +++ b/persistence-modules/blaze-persistence/pom.xml @@ -0,0 +1,121 @@ + + + 4.0.0 + blaze-persistence + 1.0-SNAPSHOT + blaze-persistence + + + org.springframework.boot + spring-boot-starter-parent + 2.4.0 + + + + + UTF-8 + 1.8 + 1.8 + 1.6.8 + + + + + + com.blazebit + blaze-persistence-bom + ${blaze-persistence.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + com.blazebit + blaze-persistence-core-api + + + com.blazebit + blaze-persistence-core-impl + + + com.blazebit + blaze-persistence-integration-hibernate-5.4 + + + + + com.blazebit + blaze-persistence-entity-view-api + + + com.blazebit + blaze-persistence-entity-view-impl + + + com.blazebit + blaze-persistence-entity-view-processor + + + + + com.blazebit + blaze-persistence-integration-entity-view-spring + + + com.blazebit + blaze-persistence-integration-spring-data-2.4 + + + + + org.springframework + spring-context + + + org.springframework + spring-orm + + + + com.h2database + h2 + + + + + org.springframework + spring-test + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-api + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/BlazePersistenceApplication.java b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/BlazePersistenceApplication.java new file mode 100644 index 0000000000..e2976aaf37 --- /dev/null +++ b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/BlazePersistenceApplication.java @@ -0,0 +1,57 @@ +package com.baeldung; + +import com.baeldung.model.Person; +import com.baeldung.model.Post; +import com.baeldung.repository.PersonRepository; +import com.baeldung.repository.PostRepository; +import com.baeldung.repository.PostViewRepository; +import com.baeldung.view.PostWithAuthorView; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BlazePersistenceApplication implements CommandLineRunner { + + private static final Logger logger = LoggerFactory.getLogger(BlazePersistenceApplication.class); + + @Autowired + private PersonRepository personRepository; + + @Autowired + private PostRepository postRepository; + + @Autowired + private PostViewRepository postViewRepository; + + public static void main(String[] args) { + SpringApplication.run(BlazePersistenceApplication.class, args); + } + + @Override + public void run(String... args) { + + logger.info("All Posts:"); + Iterable posts = postRepository.findAll(); + posts.forEach(p -> logger.info(String.valueOf(p))); + + logger.info("Posts with title 'Spring' or author 'Peter':"); + Iterable postsFiltered = postRepository.findBy("Spring", "Peter"); + postsFiltered.forEach(p -> logger.info(String.valueOf(p))); + + logger.info("Find all post with author view:"); + Iterable postsView = postViewRepository.findAll(); + postsView.forEach(p -> logger.info(String.valueOf(p))); + + logger.info("Person with at least two posts:"); + Iterable personIterable = personRepository.find(); + personIterable.forEach(p -> logger.info(String.valueOf(p))); + + logger.info("All Persons:"); + Iterable personIterableAll = personRepository.findAll(); + personIterableAll.forEach(p -> logger.info(String.valueOf(p))); + } +} \ No newline at end of file diff --git a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/config/BlazePersistenceConfiguration.java b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/config/BlazePersistenceConfiguration.java new file mode 100644 index 0000000000..0ec2e881ed --- /dev/null +++ b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/config/BlazePersistenceConfiguration.java @@ -0,0 +1,35 @@ +package com.baeldung.config; + +import com.blazebit.persistence.Criteria; +import com.blazebit.persistence.CriteriaBuilderFactory; +import com.blazebit.persistence.integration.view.spring.EnableEntityViews; +import com.blazebit.persistence.spi.CriteriaBuilderConfiguration; +import com.blazebit.persistence.spring.data.repository.config.EnableBlazeRepositories; +import com.blazebit.persistence.view.EntityViewManager; +import com.blazebit.persistence.view.spi.EntityViewConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import javax.persistence.EntityManagerFactory; + +@Configuration +@EnableEntityViews(basePackages = {"com.baeldung.view"}) +@EnableBlazeRepositories(basePackages = "com.baeldung.repository") +public class BlazePersistenceConfiguration { + + @Autowired + private EntityManagerFactory entityManagerFactory; + + @Bean + public CriteriaBuilderFactory createCriteriaBuilderFactory() { + CriteriaBuilderConfiguration config = Criteria.getDefault(); + return config.createCriteriaBuilderFactory(entityManagerFactory); + } + + @Bean + public EntityViewManager createEntityViewManager(CriteriaBuilderFactory criteriaBuilderFactory, + EntityViewConfiguration entityViewConfiguration) { + return entityViewConfiguration.createEntityViewManager(criteriaBuilderFactory); + } +} \ No newline at end of file diff --git a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/model/Person.java b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/model/Person.java new file mode 100644 index 0000000000..a6daade80d --- /dev/null +++ b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/model/Person.java @@ -0,0 +1,72 @@ +package com.baeldung.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import java.util.HashSet; +import java.util.Set; + +@Entity +public class Person { + + @Id + @GeneratedValue + private Long id; + + private String name; + + private int age; + + @OneToMany(mappedBy = "author") + private Set posts = new HashSet<>(); + + public Person() { + } + + public Person(String name, int age) { + this.name = name; + this.age = age; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Set getPosts() { + return posts; + } + + public void setPosts(Set posts) { + this.posts = posts; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + @Override + public String toString() { + return "Person{" + + "id=" + id + + ", name='" + name + '\'' + + ", age=" + age + + '}'; + } +} diff --git a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/model/Post.java b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/model/Post.java new file mode 100644 index 0000000000..6fc10dc730 --- /dev/null +++ b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/model/Post.java @@ -0,0 +1,68 @@ +package com.baeldung.model; + +import javax.persistence.*; + +@Entity +public class Post { + + @Id + @GeneratedValue + private Long id; + + private String title; + + private String content; + + @ManyToOne(fetch = FetchType.LAZY) + private Person author; + + public Post() { + } + + public Post(String title, String content, Person author) { + this.title = title; + this.content = content; + this.author = author; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public Person getAuthor() { + return author; + } + + public void setAuthor(Person author) { + this.author = author; + } + + @Override + public String toString() { + return "Post{" + + "id=" + id + + ", title='" + title + '\'' + + ", content='" + content + '\'' + + '}'; + } +} diff --git a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/repository/PersonRepository.java b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/repository/PersonRepository.java new file mode 100644 index 0000000000..12b197e8be --- /dev/null +++ b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/repository/PersonRepository.java @@ -0,0 +1,47 @@ +package com.baeldung.repository; + +import com.baeldung.model.Person; +import com.baeldung.model.Post; +import com.blazebit.persistence.CriteriaBuilder; +import com.blazebit.persistence.CriteriaBuilderFactory; +import org.springframework.stereotype.Repository; + +import javax.persistence.EntityManager; +import javax.transaction.Transactional; + +@Repository +@Transactional +public class PersonRepository { + + private final EntityManager entityManager; + + private final CriteriaBuilderFactory builderFactory; + + public PersonRepository(EntityManager entityManager, CriteriaBuilderFactory builderFactory) { + this.entityManager = entityManager; + this.builderFactory = builderFactory; + } + + public Iterable findPostsByPerson() { + CriteriaBuilder postCriteriaBuilder = builderFactory.create(entityManager, Post.class) + .from(Person.class, "person") + .select("person.posts"); + return postCriteriaBuilder.getResultList(); + } + + public Iterable findAll() { + return builderFactory.create(entityManager, Person.class).getResultList(); + } + + public Iterable find() { + CriteriaBuilder personCriteriaBuilder = builderFactory.create(entityManager, Person.class, "p") + .where("p.age") + .betweenExpression("18") + .andExpression("40") + .where("SIZE(p.posts)").geExpression("2") + .orderByAsc("p.name") + .orderByAsc("p.id"); + return personCriteriaBuilder.getResultList(); + } + +} diff --git a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/repository/PostRepository.java b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/repository/PostRepository.java new file mode 100644 index 0000000000..cf7edffe62 --- /dev/null +++ b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/repository/PostRepository.java @@ -0,0 +1,48 @@ +package com.baeldung.repository; + +import com.baeldung.model.Post; +import com.baeldung.view.PostWithAuthorView; +import com.blazebit.persistence.CriteriaBuilder; +import com.blazebit.persistence.CriteriaBuilderFactory; +import com.blazebit.persistence.view.EntityViewManager; +import com.blazebit.persistence.view.EntityViewSetting; +import org.springframework.stereotype.Repository; + +import javax.persistence.EntityManager; +import javax.transaction.Transactional; + +@Repository +@Transactional +public class PostRepository { + + private final EntityManager entityManager; + + private final CriteriaBuilderFactory builderFactory; + + private final EntityViewManager viewManager; + + public PostRepository(EntityManager entityManager, CriteriaBuilderFactory builderFactory, + EntityViewManager viewManager) { + this.entityManager = entityManager; + this.builderFactory = builderFactory; + this.viewManager = viewManager; + } + + public Iterable findAll() { + return builderFactory.create(entityManager, Post.class).getResultList(); + } + + public Iterable findBy(final String title, final String authorName) { + CriteriaBuilder postCriteriaBuilder = builderFactory.create(entityManager, Post.class, "p") + .whereOr() + .where("p.title").like().value(title + "%").noEscape() + .where("p.author.name").eq(authorName) + .endOr(); + + CriteriaBuilder postWithAuthorViewCriteriaBuilder = + viewManager.applySetting(EntityViewSetting + .create(PostWithAuthorView.class), postCriteriaBuilder); + + return postWithAuthorViewCriteriaBuilder.getResultList(); + } +} diff --git a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/repository/PostViewRepository.java b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/repository/PostViewRepository.java new file mode 100644 index 0000000000..ef241c73a2 --- /dev/null +++ b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/repository/PostViewRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.repository; + +import com.baeldung.view.PostWithAuthorView; +import com.blazebit.persistence.spring.data.repository.EntityViewRepository; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +@Repository +@Transactional(readOnly = true) +public interface PostViewRepository extends EntityViewRepository { +} diff --git a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/view/PersonView.java b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/view/PersonView.java new file mode 100644 index 0000000000..e9dd184629 --- /dev/null +++ b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/view/PersonView.java @@ -0,0 +1,16 @@ +package com.baeldung.view; + +import com.baeldung.model.Person; +import com.blazebit.persistence.view.EntityView; +import com.blazebit.persistence.view.IdMapping; + +@EntityView(Person.class) +public interface PersonView { + + @IdMapping + Long getId(); + + int getAge(); + + String getName(); +} diff --git a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/view/PostView.java b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/view/PostView.java new file mode 100644 index 0000000000..b335cda385 --- /dev/null +++ b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/view/PostView.java @@ -0,0 +1,18 @@ +package com.baeldung.view; + +import com.baeldung.model.Post; +import com.blazebit.persistence.view.EntityView; +import com.blazebit.persistence.view.IdMapping; +import com.blazebit.persistence.view.Mapping; + +@EntityView(Post.class) +public interface PostView { + + @IdMapping + Long getId(); + + @Mapping("UPPER(title)") + String getTitle(); + + String getContent(); +} diff --git a/persistence-modules/blaze-persistence/src/main/java/com/baeldung/view/PostWithAuthorView.java b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/view/PostWithAuthorView.java new file mode 100644 index 0000000000..8a34a4e34a --- /dev/null +++ b/persistence-modules/blaze-persistence/src/main/java/com/baeldung/view/PostWithAuthorView.java @@ -0,0 +1,10 @@ +package com.baeldung.view; + +import com.baeldung.model.Post; +import com.blazebit.persistence.view.EntityView; + +@EntityView(Post.class) +public interface PostWithAuthorView extends PostView { + PersonView getAuthor(); + +} diff --git a/persistence-modules/blaze-persistence/src/main/resources/application.properties b/persistence-modules/blaze-persistence/src/main/resources/application.properties new file mode 100644 index 0000000000..de4a62720a --- /dev/null +++ b/persistence-modules/blaze-persistence/src/main/resources/application.properties @@ -0,0 +1,9 @@ +spring.h2.console.enabled=true +spring.jpa.show-sql=true +logging.level.org.hibernate.SQL=DEBUG +spring.jpa.hibernate.ddl-auto=create +spring.datasource.url=jdbc:h2:mem:test +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password=sa +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect \ No newline at end of file diff --git a/persistence-modules/blaze-persistence/src/main/resources/data.sql b/persistence-modules/blaze-persistence/src/main/resources/data.sql new file mode 100644 index 0000000000..0ed609a2a4 --- /dev/null +++ b/persistence-modules/blaze-persistence/src/main/resources/data.sql @@ -0,0 +1,11 @@ +INSERT INTO Person(id, name, age) VALUES(1, 'Peter', 18); +INSERT INTO Person(id, name, age) VALUES(2, 'Emily', 36); +INSERT INTO Person(id, name, age) VALUES(3, 'John', 27); + +INSERT INTO Post(id, title, content, author_id) VALUES(1, 'Blaze Persistence', 'Blaze Content', 1); +INSERT INTO Post(id, title, content, author_id) VALUES(2, 'Jacoco', 'Jacoco Content', 1); +INSERT INTO Post(id, title, content, author_id) VALUES(3, 'Spring', 'Spring Content', 2); +INSERT INTO Post(id, title, content, author_id) VALUES(4, 'Spring Boot', 'Spring Boot Content', 3); +INSERT INTO Post(id, title, content, author_id) VALUES(5, 'Java 17', 'Java Content', 3); +INSERT INTO Post(id, title, content, author_id) VALUES(6, 'Functional Programming', 'Functional Programming Content', 3); +INSERT INTO Post(id, title, content, author_id) VALUES(7, 'Unit Testing', 'Unit Testing Content', 3); \ No newline at end of file diff --git a/persistence-modules/blaze-persistence/src/test/java/com/baeldung/PersonUnitTest.java b/persistence-modules/blaze-persistence/src/test/java/com/baeldung/PersonUnitTest.java new file mode 100644 index 0000000000..16434d52d0 --- /dev/null +++ b/persistence-modules/blaze-persistence/src/test/java/com/baeldung/PersonUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung; + +import com.baeldung.model.Person; +import com.baeldung.model.Post; +import com.baeldung.repository.PersonRepository; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@ContextConfiguration(classes = TestContextConfig.class) +@ExtendWith(SpringExtension.class) +public class PersonUnitTest { + + @Autowired + private PersonRepository personRepository; + + @Test + public void whenFind_thenReturnCorrectListSize() { + final Iterable listIterable = personRepository.find(); + final List list = new ArrayList<>(); + listIterable.forEach(list::add); + assertEquals(2, list.size()); + assertEquals("John", list.get(0).getName()); + } + + @Test + public void whenFindAll_thenReturnCorrectListSize() { + final Iterable listIterable = personRepository.findAll(); + final List list = new ArrayList<>(); + listIterable.forEach(list::add); + assertEquals(3, list.size()); + } + + @Test + public void whenFindPostsByPerson_thenReturnCorrectListSize() { + final Iterable listIterable = personRepository.findPostsByPerson(); + final List list = new ArrayList<>(); + listIterable.forEach(list::add); + assertEquals(7, list.size()); + } + +} diff --git a/persistence-modules/blaze-persistence/src/test/java/com/baeldung/PostUnitTest.java b/persistence-modules/blaze-persistence/src/test/java/com/baeldung/PostUnitTest.java new file mode 100644 index 0000000000..0af01de088 --- /dev/null +++ b/persistence-modules/blaze-persistence/src/test/java/com/baeldung/PostUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung; + +import com.baeldung.model.Post; +import com.baeldung.repository.PostRepository; +import com.baeldung.repository.PostViewRepository; +import com.baeldung.view.PostView; +import com.baeldung.view.PostWithAuthorView; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@ContextConfiguration(classes = TestContextConfig.class) +@ExtendWith(SpringExtension.class) +public class PostUnitTest { + + @Autowired + private PostViewRepository postViewRepository; + + @Autowired + private PostRepository postRepository; + + @Test + public void whenFindAll_thenReturnCorrectListViewSize() { + final Iterable listIterable = postViewRepository.findAll(); + final List list = new ArrayList<>(); + listIterable.forEach(list::add); + assertEquals(7, list.size()); + } + + @Test + public void givenPostIdAndAuthorName_whenFind_thenReturnCorrectResult() { + final Iterable listIterable = + postRepository.findBy("Spring", "Peter"); + final List list = new ArrayList<>(); + listIterable.forEach(list::add); + assertEquals(4, list.size()); + } + + @Test + public void whenFindAll_thenReturnCorrectListSize() { + final Iterable listIterable = postRepository.findAll(); + final List list = new ArrayList<>(); + listIterable.forEach(list::add); + assertEquals(7, list.size()); + } + +} diff --git a/persistence-modules/blaze-persistence/src/test/java/com/baeldung/TestContextConfig.java b/persistence-modules/blaze-persistence/src/test/java/com/baeldung/TestContextConfig.java new file mode 100644 index 0000000000..1df1fb21d9 --- /dev/null +++ b/persistence-modules/blaze-persistence/src/test/java/com/baeldung/TestContextConfig.java @@ -0,0 +1,15 @@ +package com.baeldung; + +import com.blazebit.persistence.integration.view.spring.EnableEntityViews; +import com.blazebit.persistence.spring.data.repository.config.EnableBlazeRepositories; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung") +@EnableEntityViews(basePackages = {"com.baeldung.view"}) +@EnableBlazeRepositories(basePackages = "com.baeldung.repository") +public class TestContextConfig { + + +} diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index bff23cffc1..c17e793dbc 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -18,6 +18,7 @@ apache-bookkeeper apache-cayenne apache-derby + blaze-persistence core-java-persistence core-java-persistence-2 deltaspike diff --git a/rxjava-modules/rxjava-core-2/README.md b/rxjava-modules/rxjava-core-2/README.md new file mode 100644 index 0000000000..72c9fba62c --- /dev/null +++ b/rxjava-modules/rxjava-core-2/README.md @@ -0,0 +1,5 @@ +## RxJava + +This module contains articles about RxJava. + +### Relevant articles: diff --git a/rxjava-modules/rxjava-core-2/pom.xml b/rxjava-modules/rxjava-core-2/pom.xml new file mode 100644 index 0000000000..ccadf38ba3 --- /dev/null +++ b/rxjava-modules/rxjava-core-2/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + rxjava-core-2 + 1.0-SNAPSHOT + rxjava-core-2 + + + com.baeldung.rxjava-modules + rxjava-modules + 0.0.1-SNAPSHOT + + + \ No newline at end of file diff --git a/rxjava-modules/rxjava-core-2/src/main/java/com/baeldung/rxjava/justvscallable/EmployeeRepository.java b/rxjava-modules/rxjava-core-2/src/main/java/com/baeldung/rxjava/justvscallable/EmployeeRepository.java new file mode 100644 index 0000000000..03d95e2c8a --- /dev/null +++ b/rxjava-modules/rxjava-core-2/src/main/java/com/baeldung/rxjava/justvscallable/EmployeeRepository.java @@ -0,0 +1,5 @@ +package com.baeldung.rxjava.justvscallable; + +public interface EmployeeRepository { + String findById(Long id); +} diff --git a/rxjava-modules/rxjava-core-2/src/main/resources/logback.xml b/rxjava-modules/rxjava-core-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/rxjava-modules/rxjava-core-2/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/rxjava-modules/rxjava-core-2/src/test/java/com/baeldung/rxjava/justvscallable/SingleJustVsFromCallableTest.java b/rxjava-modules/rxjava-core-2/src/test/java/com/baeldung/rxjava/justvscallable/SingleJustVsFromCallableTest.java new file mode 100644 index 0000000000..d0de86fed8 --- /dev/null +++ b/rxjava-modules/rxjava-core-2/src/test/java/com/baeldung/rxjava/justvscallable/SingleJustVsFromCallableTest.java @@ -0,0 +1,70 @@ +package com.baeldung.rxjava.justvscallable; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import rx.Single; +import rx.observers.TestSubscriber; + +class SingleJustVsFromCallableTest { + + public EmployeeRepository repository = mock(EmployeeRepository.class); + + @BeforeEach + public void beforeEach() { + reset(repository); + } + + @Test + void givenNoSubscriber_whenUsingJust_thenDataIsFetched() { + Mockito.when(repository.findById(123L)) + .thenReturn("John Doe"); + + Single employee = Single.just(repository.findById(123L)); + + Mockito.verify(repository, times(1)) + .findById(123L); + } + + @Test + void givenASubscriber_whenUsingJust_thenReturnTheCorrectValue() { + TestSubscriber testSubscriber = new TestSubscriber<>(); + Mockito.when(repository.findById(123L)) + .thenReturn("John Doe"); + + Single employee = Single.just(repository.findById(123L)); + employee.subscribe(testSubscriber); + + testSubscriber.assertValue("John Doe"); + testSubscriber.assertCompleted(); + } + + @Test + void givenNoSubscriber_whenUsingFromCallable_thenNoDataIsFetched() { + Single employee = Single.fromCallable(() -> repository.findById(123L)); + + Mockito.verify(repository, never()) + .findById(123L); + } + + @Test + void givenASubscriber_whenUsingFromCallable_thenReturnCorrectValue() { + TestSubscriber testSubscriber = new TestSubscriber<>(); + Mockito.when(repository.findById(123L)) + .thenReturn("John Doe"); + + Single employee = Single.fromCallable(() -> repository.findById(123L)); + employee.subscribe(testSubscriber); + + Mockito.verify(repository, times(1)) + .findById(123L); + testSubscriber.assertCompleted(); + testSubscriber.assertValue("John Doe"); + } +} \ No newline at end of file diff --git a/security-modules/jwt/.gitignore b/security-modules/jwt/.gitignore new file mode 100644 index 0000000000..f83e8cf07c --- /dev/null +++ b/security-modules/jwt/.gitignore @@ -0,0 +1,3 @@ +.idea +target +*.iml diff --git a/security-modules/jwt/pom.xml b/security-modules/jwt/pom.xml new file mode 100644 index 0000000000..5ec563dcfa --- /dev/null +++ b/security-modules/jwt/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + jwt + jwt + jar + + + com.baeldung + security-modules + 1.0.0-SNAPSHOT + + + + + com.auth0 + java-jwt + ${auth0-jwt.version} + + + + + 4.2.1 + + + \ No newline at end of file diff --git a/security-modules/jwt/src/main/java/com/baeldung/jwt/auth0/Auth0JsonWebToken.java b/security-modules/jwt/src/main/java/com/baeldung/jwt/auth0/Auth0JsonWebToken.java new file mode 100644 index 0000000000..0d5e7a4839 --- /dev/null +++ b/security-modules/jwt/src/main/java/com/baeldung/jwt/auth0/Auth0JsonWebToken.java @@ -0,0 +1,99 @@ +package com.baeldung.jwt.auth0; + +import java.util.Date; +import java.util.UUID; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTVerifier; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.exceptions.JWTVerificationException; +import com.auth0.jwt.interfaces.Claim; +import com.auth0.jwt.interfaces.DecodedJWT; + +public class Auth0JsonWebToken { + + private static final String SECRET = "baeldung"; + private static final String ISSUER = "Baeldung"; + private static final String SUBJECT = "Baeldung Details"; + private static final String DATA_CLAIM = "userId"; + private static final String DATA = "1234"; + private static final long TOKEN_VALIDITY_IN_MILLIS = 5000L; + + private static Algorithm algorithm; + private static JWTVerifier verifier; + + public static void initialize() { + algorithm = Algorithm.HMAC256(SECRET); + + verifier = JWT.require(algorithm) + .withIssuer(ISSUER) + .build(); + } + + private static String createJWT() { + String jwtToken = JWT.create() + .withIssuer(ISSUER) + .withSubject(SUBJECT) + .withClaim(DATA_CLAIM, DATA) + .withIssuedAt(new Date()) + .withExpiresAt(new Date(System.currentTimeMillis() + TOKEN_VALIDITY_IN_MILLIS)) + .withJWTId(UUID.randomUUID() + .toString()) + .withNotBefore(new Date(System.currentTimeMillis() + 1000L)) + .sign(algorithm); + + return jwtToken; + } + + private static DecodedJWT verifyJWT(String jwtToken) { + try { + DecodedJWT decodedJWT = verifier.verify(jwtToken); + return decodedJWT; + } catch (JWTVerificationException e) { + System.out.println(e.getMessage()); + } + return null; + } + + private static boolean isJWTExpired(DecodedJWT decodedJWT) { + Date expiresAt = decodedJWT.getExpiresAt(); + return expiresAt.getTime() < System.currentTimeMillis(); + } + + private static String getClaim(DecodedJWT decodedJWT, String claimName) { + Claim claim = decodedJWT.getClaim(claimName); + return claim != null ? claim.asString() : null; + } + + public static void main(String args[]) throws InterruptedException { + + initialize(); + + String jwtToken = createJWT(); + System.out.println("Created JWT : " + jwtToken); + + DecodedJWT decodedJWT = verifyJWT(jwtToken); + if (decodedJWT == null) { + System.out.println("JWT Verification Failed"); + } + + Thread.sleep(1000L); + + decodedJWT = verifyJWT(jwtToken); + if (decodedJWT != null) { + System.out.println("Token Issued At : " + decodedJWT.getIssuedAt()); + System.out.println("Token Expires At : " + decodedJWT.getExpiresAt()); + System.out.println("Subject : " + decodedJWT.getSubject()); + System.out.println("Data : " + getClaim(decodedJWT, DATA_CLAIM)); + System.out.println("Header : " + decodedJWT.getHeader()); + System.out.println("Payload : " + decodedJWT.getPayload()); + System.out.println("Signature : " + decodedJWT.getSignature()); + System.out.println("Algorithm : " + decodedJWT.getAlgorithm()); + System.out.println("JWT Id : " + decodedJWT.getId()); + + Boolean isExpired = isJWTExpired(decodedJWT); + System.out.println("Is Expired : " + isExpired); + } + } + +} diff --git a/security-modules/jwt/src/test/java/com/baeldung/jwt/auth0/Auth0JsonWebTokenUnitTest.java b/security-modules/jwt/src/test/java/com/baeldung/jwt/auth0/Auth0JsonWebTokenUnitTest.java new file mode 100644 index 0000000000..a9c3b4185d --- /dev/null +++ b/security-modules/jwt/src/test/java/com/baeldung/jwt/auth0/Auth0JsonWebTokenUnitTest.java @@ -0,0 +1,127 @@ +package com.baeldung.jwt.auth0; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.Date; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTVerifier; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.exceptions.IncorrectClaimException; +import com.auth0.jwt.exceptions.SignatureVerificationException; +import com.auth0.jwt.exceptions.TokenExpiredException; +import com.auth0.jwt.interfaces.Claim; +import com.auth0.jwt.interfaces.DecodedJWT; + +public class Auth0JsonWebTokenUnitTest { + + private static final String SECRET = "baeldung"; + private static final String SECRET_NEW = "baeldung.com"; + private static final String ISSUER = "Baeldung"; + private static final String DATA_CLAIM = "userId"; + private static final String DATA = "1234"; + + private static Algorithm algorithm; + private static Algorithm algorithmWithDifferentSecret; + private static JWTVerifier verifier; + private static String jwtToken; + + @BeforeAll + public static void setUp() { + algorithm = Algorithm.HMAC256(SECRET); + + algorithmWithDifferentSecret = Algorithm.HMAC256(SECRET_NEW); + + verifier = JWT.require(algorithm) + .withIssuer(ISSUER) + .build(); + } + + private static boolean isJWTExpired(DecodedJWT decodedJWT) { + Date expiresAt = decodedJWT.getExpiresAt(); + return expiresAt.getTime() < System.currentTimeMillis(); + } + + private static DecodedJWT verifyJWT(String jwtToken) { + DecodedJWT decodedJWT = verifier.verify(jwtToken); + return decodedJWT; + } + + @Test + public void givenJWT_whenNotExpired_thenCheckingIfNotExpired() { + + jwtToken = JWT.create() + .withIssuer(ISSUER) + .withClaim(DATA_CLAIM, DATA) + .withExpiresAt(new Date(System.currentTimeMillis() + 1000L)) + .sign(algorithm); + + DecodedJWT decodedJWT = verifyJWT(jwtToken); + assertNotNull(decodedJWT); + assertFalse(isJWTExpired(decodedJWT)); + } + + @Test + public void givenJWT_whenExpired_thenCheckingIfExpired() { + + jwtToken = JWT.create() + .withIssuer(ISSUER) + .withClaim(DATA_CLAIM, DATA) + .withExpiresAt(new Date(System.currentTimeMillis() - 1000L)) + .sign(algorithm); + + assertThrows(TokenExpiredException.class, () -> { + verifyJWT(jwtToken); + }); + } + + @Test + public void givenJWT_whenCreatedWithCustomClaim_thenCheckingForCustomClaim() { + + jwtToken = JWT.create() + .withIssuer(ISSUER) + .withClaim(DATA_CLAIM, DATA) + .withExpiresAt(new Date(System.currentTimeMillis() + 1000L)) + .sign(algorithm); + + DecodedJWT decodedJWT = verifyJWT(jwtToken); + assertNotNull(decodedJWT); + + Claim claim = decodedJWT.getClaim(DATA_CLAIM); + assertEquals(DATA, claim.asString()); + } + + @Test + public void givenJWT_whenCreatedWithNotBefore_thenThrowException() { + + jwtToken = JWT.create() + .withIssuer(ISSUER) + .withClaim(DATA_CLAIM, DATA) + .withNotBefore(new Date(System.currentTimeMillis() + 1000L)) + .sign(algorithm); + + assertThrows(IncorrectClaimException.class, () -> { + verifyJWT(jwtToken); + }); + } + + @Test + public void givenJWT_whenVerifyingUsingDifferentSecret_thenThrowException() { + + jwtToken = JWT.create() + .withIssuer(ISSUER) + .withClaim(DATA_CLAIM, DATA) + .withExpiresAt(new Date(System.currentTimeMillis() + 1000L)) + .sign(algorithmWithDifferentSecret); + + assertThrows(SignatureVerificationException.class, () -> { + verifyJWT(jwtToken); + }); + } +} diff --git a/security-modules/pom.xml b/security-modules/pom.xml index 480ee0819e..1ed081a273 100644 --- a/security-modules/pom.xml +++ b/security-modules/pom.xml @@ -20,8 +20,9 @@ jee-7-security jjwt + jwt oauth2-framework-impl - sql-injection-samples + sql-injection-samples \ No newline at end of file diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml index 9de7e473f8..b7fdfdfc60 100644 --- a/spring-activiti/pom.xml +++ b/spring-activiti/pom.xml @@ -9,12 +9,10 @@ Demo project for Spring Boot - - com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -32,18 +30,21 @@ org.activiti - activiti-spring-boot-starter-basic - ${activiti.version} - - - org.activiti - activiti-spring-boot-starter-security + activiti-spring-boot-starter ${activiti.version} + + org.springframework.boot + spring-boot-starter-web + org.springframework.boot spring-boot-starter-thymeleaf + + org.springframework.boot + spring-boot-starter-security + com.h2database h2 @@ -70,7 +71,7 @@ - 6.0.0 + 7.1.0.M6 2.17.1 diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/config/ProcessController.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/ProcessController.java index 671b246328..c680af304d 100644 --- a/spring-activiti/src/main/java/com/baeldung/activiti/security/config/ProcessController.java +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/ProcessController.java @@ -2,14 +2,11 @@ package com.baeldung.activiti.security.config; import java.util.List; -import org.activiti.engine.IdentityService; import org.activiti.engine.RuntimeService; import org.activiti.engine.TaskService; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Task; -import org.activiti.spring.SpringProcessEngineConfiguration; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @@ -22,21 +19,9 @@ public class ProcessController { @Autowired private TaskService taskService; - @Autowired - private IdentityService identityService; - - @Autowired - SpringProcessEngineConfiguration config; - @GetMapping("/protected-process") public String startProcess() { - String userId = SecurityContextHolder.getContext() - .getAuthentication() - .getName(); - - identityService.setAuthenticatedUserId(userId); - ProcessInstance pi = runtimeService.startProcessInstanceByKey("protected-process"); List usertasks = taskService.createTaskQuery() diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/config/SpringSecurityGroupManager.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/SpringSecurityGroupManager.java deleted file mode 100644 index 00fc674e22..0000000000 --- a/spring-activiti/src/main/java/com/baeldung/activiti/security/config/SpringSecurityGroupManager.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.baeldung.activiti.security.config; - -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import org.activiti.engine.identity.Group; -import org.activiti.engine.identity.GroupQuery; -import org.activiti.engine.impl.GroupQueryImpl; -import org.activiti.engine.impl.Page; -import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl; -import org.activiti.engine.impl.persistence.entity.GroupEntityImpl; -import org.activiti.engine.impl.persistence.entity.GroupEntityManagerImpl; -import org.activiti.engine.impl.persistence.entity.data.GroupDataManager; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.provisioning.JdbcUserDetailsManager; - -public class SpringSecurityGroupManager extends GroupEntityManagerImpl { - - private JdbcUserDetailsManager userManager; - - public SpringSecurityGroupManager(ProcessEngineConfigurationImpl processEngineConfiguration, GroupDataManager groupDataManager) { - super(processEngineConfiguration, groupDataManager); - } - - @Override - public List findGroupByQueryCriteria(GroupQueryImpl query, Page page) { - - if (query.getUserId() != null) { - return findGroupsByUser(query.getUserId()); - } - return null; - } - - @Override - public long findGroupCountByQueryCriteria(GroupQueryImpl query) { - return findGroupByQueryCriteria(query, null).size(); - } - - @Override - public List findGroupsByUser(String userId) { - UserDetails userDetails = userManager.loadUserByUsername(userId); - System.out.println("group manager"); - if (userDetails != null) { - List groups = userDetails.getAuthorities() - .stream() - .map(a -> a.getAuthority()) - .map(a -> { - Group g = new GroupEntityImpl(); - g.setId(a); - return g; - }) - .collect(Collectors.toList()); - return groups; - } - return null; - } - - public void setUserManager(JdbcUserDetailsManager userManager) { - this.userManager = userManager; - } - - public Group createNewGroup(String groupId) { - throw new UnsupportedOperationException("This operation is not supported!"); - - } - - @Override - public void delete(String groupId) { - throw new UnsupportedOperationException("This operation is not supported!"); - - } - - public GroupQuery createNewGroupQuery() { - throw new UnsupportedOperationException("This operation is not supported!"); - } - - public List findGroupsByNativeQuery(Map parameterMap, int firstResult, int maxResults) { - throw new UnsupportedOperationException("This operation is not supported!"); - } - - public long findGroupCountByNativeQuery(Map parameterMap) { - throw new UnsupportedOperationException("This operation is not supported!"); - } - -} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/config/SpringSecurityUserManager.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/config/SpringSecurityUserManager.java deleted file mode 100644 index ce9863eb6c..0000000000 --- a/spring-activiti/src/main/java/com/baeldung/activiti/security/config/SpringSecurityUserManager.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.baeldung.activiti.security.config; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import org.activiti.engine.identity.Group; -import org.activiti.engine.identity.User; -import org.activiti.engine.identity.UserQuery; -import org.activiti.engine.impl.Page; -import org.activiti.engine.impl.UserQueryImpl; -import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl; -import org.activiti.engine.impl.persistence.entity.GroupEntityImpl; -import org.activiti.engine.impl.persistence.entity.UserEntity; -import org.activiti.engine.impl.persistence.entity.UserEntityImpl; -import org.activiti.engine.impl.persistence.entity.UserEntityManagerImpl; -import org.activiti.engine.impl.persistence.entity.data.UserDataManager; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.provisioning.JdbcUserDetailsManager; - -public class SpringSecurityUserManager extends UserEntityManagerImpl { - - private JdbcUserDetailsManager userManager; - - public SpringSecurityUserManager(ProcessEngineConfigurationImpl processEngineConfiguration, UserDataManager userDataManager, JdbcUserDetailsManager userManager) { - super(processEngineConfiguration, userDataManager); - this.userManager = userManager; - } - - @Override - public UserEntity findById(String userId) { - UserDetails userDetails = userManager.loadUserByUsername(userId); - if (userDetails != null) { - UserEntityImpl user = new UserEntityImpl(); - user.setId(userId); - return user; - } - return null; - - } - - @Override - public List findUserByQueryCriteria(UserQueryImpl query, Page page) { - List users = null; - if (query.getGroupId() != null) { - users = userManager.findUsersInGroup(query.getGroupId()) - .stream() - .map(username -> { - User user = new UserEntityImpl(); - user.setId(username); - return user; - }) - .collect(Collectors.toList()); - if (page != null) { - return users.subList(page.getFirstResult(), page.getFirstResult() + page.getMaxResults()); - - } - return users; - } - - if (query.getId() != null) { - UserDetails userDetails = userManager.loadUserByUsername(query.getId()); - if (userDetails != null) { - UserEntityImpl user = new UserEntityImpl(); - user.setId(query.getId()); - return Collections.singletonList(user); - } - } - return null; - } - - @Override - public Boolean checkPassword(String userId, String password) { - return true; - } - - public void setUserManager(JdbcUserDetailsManager userManager) { - this.userManager = userManager; - } - - public User createNewUser(String userId) { - throw new UnsupportedOperationException("This operation is not supported!"); - } - - public void updateUser(User updatedUser) { - throw new UnsupportedOperationException("This operation is not supported!"); - - } - - public void delete(UserEntity userEntity) { - throw new UnsupportedOperationException("This operation is not supported!"); - - } - - @Override - public void deletePicture(User user) { - UserEntity userEntity = (UserEntity) user; - if (userEntity.getPictureByteArrayRef() != null) { - userEntity.getPictureByteArrayRef() - .delete(); - } - } - - public void delete(String userId) { - throw new UnsupportedOperationException("This operation is not supported!"); - - } - - public long findUserCountByQueryCriteria(UserQueryImpl query) { - return findUserByQueryCriteria(query, null).size(); - } - - public List findGroupsByUser(String userId) { - UserDetails userDetails = userManager.loadUserByUsername(userId); - if (userDetails != null) { - List groups = userDetails.getAuthorities() - .stream() - .map(a -> a.getAuthority()) - .map(a -> { - Group g = new GroupEntityImpl(); - g.setId(a); - return g; - }) - .collect(Collectors.toList()); - return groups; - } - return null; - } - - public UserQuery createNewUserQuery() { - throw new UnsupportedOperationException("This operation is not supported!"); - } - - public List findUsersByNativeQuery(Map parameterMap, int firstResult, int maxResults) { - throw new UnsupportedOperationException("This operation is not supported!"); - } - - public long findUserCountByNativeQuery(Map parameterMap) { - throw new UnsupportedOperationException("This operation is not supported!"); - - } - -} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/withactiviti/SecurityConfig.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/withactiviti/SecurityConfig.java deleted file mode 100644 index f471600553..0000000000 --- a/spring-activiti/src/main/java/com/baeldung/activiti/security/withactiviti/SecurityConfig.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.activiti.security.withactiviti; - -import org.activiti.engine.IdentityService; -import org.activiti.spring.security.IdentityServiceUserDetailsService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -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.WebSecurityConfigurerAdapter; - -@Configuration -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - protected void configure(HttpSecurity http) throws Exception { - http.antMatcher("/**") - .authorizeRequests() - .antMatchers("/protected-process*") - .authenticated() - .anyRequest() - .permitAll() - .and() - .formLogin() - .loginPage("/login") - .defaultSuccessUrl("/homepage") - .failureUrl("/login?error=true") - .and() - .csrf() - .disable() - .logout() - .logoutSuccessUrl("/login"); - } - - @Autowired - private IdentityService identityService; - - @Bean - public IdentityServiceUserDetailsService userDetailsService() { - return new IdentityServiceUserDetailsService(identityService); - } - - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(userDetailsService()); - } - -} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/withactiviti/SpringSecurityActivitiApplication.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/withactiviti/SpringSecurityActivitiApplication.java deleted file mode 100644 index 2270a4d684..0000000000 --- a/spring-activiti/src/main/java/com/baeldung/activiti/security/withactiviti/SpringSecurityActivitiApplication.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.activiti.security.withactiviti; - -import org.activiti.engine.IdentityService; -import org.activiti.engine.identity.Group; -import org.activiti.engine.identity.User; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; - -@SpringBootApplication(scanBasePackages = { "com.baeldung.activiti.security.config", "com.baeldung.activiti.security.withactiviti" }) -public class SpringSecurityActivitiApplication { - - public static void main(String[] args) { - SpringApplication.run(SpringSecurityActivitiApplication.class, args); - } - - @Bean - InitializingBean usersAndGroupsInitializer(IdentityService identityService) { - return new InitializingBean() { - public void afterPropertiesSet() throws Exception { - User user = identityService.newUser("activiti_user"); - user.setPassword("pass"); - identityService.saveUser(user); - - Group group = identityService.newGroup("user"); - group.setName("ROLE_USER"); - group.setType("USER"); - identityService.saveGroup(group); - identityService.createMembership(user.getId(), group.getId()); - } - }; - } -} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/ActivitiSpringSecurityApplication.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/ActivitiSpringSecurityApplication.java deleted file mode 100644 index 5878a5d678..0000000000 --- a/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/ActivitiSpringSecurityApplication.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.activiti.security.withspring; - -import org.activiti.engine.impl.persistence.entity.data.impl.MybatisGroupDataManager; -import org.activiti.engine.impl.persistence.entity.data.impl.MybatisUserDataManager; -import org.activiti.spring.SpringProcessEngineConfiguration; -import org.activiti.spring.boot.SecurityAutoConfiguration; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.security.provisioning.JdbcUserDetailsManager; - -import com.baeldung.activiti.security.config.SpringSecurityGroupManager; -import com.baeldung.activiti.security.config.SpringSecurityUserManager; - -@SpringBootApplication(exclude = SecurityAutoConfiguration.class, scanBasePackages = { "com.baeldung.activiti.security.config", "com.baeldung.activiti.security.withspring" }) -public class ActivitiSpringSecurityApplication { - - public static void main(String[] args) { - SpringApplication.run(ActivitiSpringSecurityApplication.class, args); - } - - @Autowired - private SpringProcessEngineConfiguration processEngineConfiguration; - - @Autowired - private JdbcUserDetailsManager userManager; - - @Bean - InitializingBean processEngineInitializer() { - return new InitializingBean() { - public void afterPropertiesSet() throws Exception { - processEngineConfiguration.setUserEntityManager(new SpringSecurityUserManager(processEngineConfiguration, new MybatisUserDataManager(processEngineConfiguration), userManager)); - processEngineConfiguration.setGroupEntityManager(new SpringSecurityGroupManager(processEngineConfiguration, new MybatisGroupDataManager(processEngineConfiguration))); - } - }; - } -} diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/SecurityConfig.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/SecurityConfig.java index df1991c3e4..8dc3eee05e 100644 --- a/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/SecurityConfig.java +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/SecurityConfig.java @@ -1,22 +1,19 @@ package com.baeldung.activiti.security.withspring; -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -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.WebSecurityConfigurerAdapter; -import org.springframework.security.provisioning.JdbcUserDetailsManager; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; +import org.springframework.security.web.SecurityFilterChain; @Configuration -public class SecurityConfig extends WebSecurityConfigurerAdapter { +public class SecurityConfig { - @Autowired - private DataSource dataSource; - - protected void configure(HttpSecurity http) throws Exception { + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.antMatcher("/**") .authorizeRequests() .antMatchers("/protected-process*") @@ -33,18 +30,16 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { .disable() .logout() .logoutSuccessUrl("/login"); + return http.build(); } @Bean - public JdbcUserDetailsManager userDetailsManager() { - JdbcUserDetailsManager manager = new JdbcUserDetailsManager(); - manager.setDataSource(dataSource); - return manager; - } + public UserDetailsService userDetailsService() { + UserDetails user = User.withUsername("user") + .password("{noop}pass") + .authorities("ROLE_ACTIVITI_USER") + .build(); - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(userDetailsManager()); + return new InMemoryUserDetailsManager(user); } - } diff --git a/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/SpringSecurityActivitiApplication.java b/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/SpringSecurityActivitiApplication.java new file mode 100644 index 0000000000..84aa4b2b0d --- /dev/null +++ b/spring-activiti/src/main/java/com/baeldung/activiti/security/withspring/SpringSecurityActivitiApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.activiti.security.withspring; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication(scanBasePackages = { "com.baeldung.activiti.security.config", "com.baeldung.activiti.security.withspring" }) +public class SpringSecurityActivitiApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringSecurityActivitiApplication.class, args); + } + +} diff --git a/spring-activiti/src/main/java/com/baeldung/activitiwithspring/ActivitiWithSpringApplication.java b/spring-activiti/src/main/java/com/baeldung/activitiwithspring/ActivitiWithSpringApplication.java index d43ae3cc35..b3cf66b0f7 100644 --- a/spring-activiti/src/main/java/com/baeldung/activitiwithspring/ActivitiWithSpringApplication.java +++ b/spring-activiti/src/main/java/com/baeldung/activitiwithspring/ActivitiWithSpringApplication.java @@ -2,9 +2,8 @@ package com.baeldung.activitiwithspring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration; -@SpringBootApplication(exclude = {SecurityAutoConfiguration.class}) +@SpringBootApplication public class ActivitiWithSpringApplication { public static void main(String[] args) { SpringApplication.run(ActivitiWithSpringApplication.class, args); diff --git a/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiSpringSecurityIntegrationTest.java b/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiSpringSecurityIntegrationTest.java index 7f99483fcf..43a159efbd 100644 --- a/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiSpringSecurityIntegrationTest.java +++ b/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiSpringSecurityIntegrationTest.java @@ -1,33 +1,22 @@ package com.baeldung.activitiwithspring; -import org.activiti.engine.IdentityService; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; -import com.baeldung.activiti.security.withspring.ActivitiSpringSecurityApplication; +import com.baeldung.activiti.security.withspring.SpringSecurityActivitiApplication; @RunWith(SpringRunner.class) -@SpringBootTest(classes = ActivitiSpringSecurityApplication.class) +@SpringBootTest(classes = SpringSecurityActivitiApplication.class) @WebAppConfiguration @AutoConfigureTestDatabase public class ActivitiSpringSecurityIntegrationTest { - @Autowired - private IdentityService identityService; @Test - public void whenUserExists_thenOk() { - identityService.setUserPicture("spring_user", null); - } - - @Test(expected = UsernameNotFoundException.class) - public void whenUserNonExistent_thenSpringException() { - identityService.setUserPicture("user3", null); + public void contextLoads() { } } diff --git a/spring-boot-modules/spring-boot-libraries/pom.xml b/spring-boot-modules/spring-boot-libraries/pom.xml index 7ac7043abc..d8ca53f013 100644 --- a/spring-boot-modules/spring-boot-libraries/pom.xml +++ b/spring-boot-modules/spring-boot-libraries/pom.xml @@ -226,8 +226,8 @@ 2.1 2.6.0 3.3.0 - 4.10.0 - 0.2.0 + 7.6.0 + 0.7.0 2.8.2 diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/ratelimiting/bucket4japp/service/PricingPlanService.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/ratelimiting/bucket4japp/service/PricingPlanService.java index 7d8a718601..c4f7747171 100644 --- a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/ratelimiting/bucket4japp/service/PricingPlanService.java +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/ratelimiting/bucket4japp/service/PricingPlanService.java @@ -7,7 +7,6 @@ import org.springframework.stereotype.Service; import io.github.bucket4j.Bandwidth; import io.github.bucket4j.Bucket; -import io.github.bucket4j.Bucket4j; @Service public class PricingPlanService { @@ -24,7 +23,7 @@ public class PricingPlanService { } private Bucket bucket(Bandwidth limit) { - return Bucket4j.builder() + return Bucket.builder() .addLimit(limit) .build(); } diff --git a/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/ratelimiting/bucket4japp/Bucket4jUsageUnitTest.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/ratelimiting/bucket4japp/Bucket4jUsageUnitTest.java index fbf63ba403..8b9fba6dd3 100644 --- a/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/ratelimiting/bucket4japp/Bucket4jUsageUnitTest.java +++ b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/ratelimiting/bucket4japp/Bucket4jUsageUnitTest.java @@ -1,7 +1,7 @@ package com.baeldung.ratelimiting.bucket4japp; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Duration; import java.util.concurrent.CountDownLatch; @@ -13,7 +13,6 @@ import org.junit.jupiter.api.Test; import io.github.bucket4j.Bandwidth; import io.github.bucket4j.Bucket; -import io.github.bucket4j.Bucket4j; import io.github.bucket4j.Refill; public class Bucket4jUsageUnitTest { @@ -22,7 +21,7 @@ public class Bucket4jUsageUnitTest { public void givenBucketLimit_whenExceedLimit_thenConsumeReturnsFalse() { Refill refill = Refill.intervally(10, Duration.ofMinutes(1)); Bandwidth limit = Bandwidth.classic(10, refill); - Bucket bucket = Bucket4j.builder() + Bucket bucket = Bucket.builder() .addLimit(limit) .build(); @@ -34,7 +33,7 @@ public class Bucket4jUsageUnitTest { @Test public void givenMultipletLimits_whenExceedSmallerLimit_thenConsumeReturnsFalse() { - Bucket bucket = Bucket4j.builder() + Bucket bucket = Bucket.builder() .addLimit(Bandwidth.classic(10, Refill.intervally(10, Duration.ofMinutes(1)))) .addLimit(Bandwidth.classic(5, Refill.intervally(5, Duration.ofSeconds(20)))) .build(); @@ -49,7 +48,7 @@ public class Bucket4jUsageUnitTest { public void givenBucketLimit_whenThrottleRequests_thenConsumeReturnsTrue() throws InterruptedException { Refill refill = Refill.intervally(1, Duration.ofSeconds(2)); Bandwidth limit = Bandwidth.classic(1, refill); - Bucket bucket = Bucket4j.builder() + Bucket bucket = Bucket.builder() .addLimit(limit) .build(); @@ -65,8 +64,8 @@ public class Bucket4jUsageUnitTest { static class AssertTryConsume implements Runnable { - private Bucket bucket; - private CountDownLatch latch; + private final Bucket bucket; + private final CountDownLatch latch; AssertTryConsume(Bucket bucket, CountDownLatch latch) { this.bucket = bucket; diff --git a/spring-cloud-modules/spring-cloud-archaius/pom.xml b/spring-cloud-modules/spring-cloud-archaius/pom.xml index 66b7bb9b19..4d7ca3943d 100644 --- a/spring-cloud-modules/spring-cloud-archaius/pom.xml +++ b/spring-cloud-modules/spring-cloud-archaius/pom.xml @@ -16,12 +16,12 @@ - additional-sources-simple - basic-config - dynamodb-config - extra-configs - jdbc-config - zookeeper-config + spring-cloud-archaius-additionalsources + spring-cloud-archaius-basic-config + spring-cloud-archaius-dynamodb-config + spring-cloud-archaius-extra-configs + spring-cloud-archaius-jdbc-config + spring-cloud-archaius-zookeeper-config diff --git a/spring-cloud-modules/spring-cloud-archaius/basic-config/pom.xml b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/pom.xml similarity index 84% rename from spring-cloud-modules/spring-cloud-archaius/basic-config/pom.xml rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/pom.xml index 5e2eb47928..f523e79bac 100644 --- a/spring-cloud-modules/spring-cloud-archaius/basic-config/pom.xml +++ b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/pom.xml @@ -3,9 +3,9 @@ xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - basic-config + spring-cloud-archaius-additional-sources-simple 1.0.0-SNAPSHOT - basic-config + spring-cloud-archaius-additionalsources jar diff --git a/spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/AdditionalSourcesSimpleApplication.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/AdditionalSourcesSimpleApplication.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/AdditionalSourcesSimpleApplication.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/AdditionalSourcesSimpleApplication.java diff --git a/spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/config/ApplicationPropertiesConfigurations.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/config/ApplicationPropertiesConfigurations.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/config/ApplicationPropertiesConfigurations.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/config/ApplicationPropertiesConfigurations.java diff --git a/spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/controller/ConfigPropertiesController.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/controller/ConfigPropertiesController.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/controller/ConfigPropertiesController.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/src/main/java/com/baeldung/spring/cloud/archaius/additionalsources/controller/ConfigPropertiesController.java diff --git a/spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/src/main/resources/application.properties b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/src/main/resources/application.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/src/main/resources/application.properties rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/src/main/resources/application.properties diff --git a/spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/src/main/resources/config.properties b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/src/main/resources/config.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/src/main/resources/config.properties rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/src/main/resources/config.properties diff --git a/spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/src/main/resources/other-config.properties b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/src/main/resources/other-config.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/src/main/resources/other-config.properties rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/src/main/resources/other-config.properties diff --git a/spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/ArchaiusAdditionalSourcesLiveTest.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/ArchaiusAdditionalSourcesLiveTest.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/ArchaiusAdditionalSourcesLiveTest.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/ArchaiusAdditionalSourcesLiveTest.java diff --git a/spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/SpringContextTest.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/SpringContextTest.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/SpringContextTest.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/src/test/java/com/baeldung/spring/cloud/archaius/additionalsources/SpringContextTest.java diff --git a/spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/src/test/resources/logback-test.xml b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/src/test/resources/logback-test.xml similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/src/test/resources/logback-test.xml rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/src/test/resources/logback-test.xml diff --git a/spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/pom.xml b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/pom.xml similarity index 86% rename from spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/pom.xml rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/pom.xml index 6c8ed96003..8b35ee845b 100644 --- a/spring-cloud-modules/spring-cloud-archaius/additional-sources-simple/pom.xml +++ b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/pom.xml @@ -3,9 +3,9 @@ xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - additional-sources-simple + spring-cloud-archaius-basic-config 1.0.0-SNAPSHOT - additional-sources-simple + spring-cloud-archaius-basic-config jar diff --git a/spring-cloud-modules/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/BasicArchaiusApplication.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/BasicArchaiusApplication.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/BasicArchaiusApplication.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/BasicArchaiusApplication.java diff --git a/spring-cloud-modules/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/controller/ConfigPropertiesController.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/controller/ConfigPropertiesController.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/controller/ConfigPropertiesController.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/main/java/com/baeldung/spring/cloud/archaius/basic/controller/ConfigPropertiesController.java diff --git a/spring-cloud-modules/spring-cloud-archaius/basic-config/src/main/resources/application.properties b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/main/resources/application.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/basic-config/src/main/resources/application.properties rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/main/resources/application.properties diff --git a/spring-cloud-modules/spring-cloud-archaius/basic-config/src/main/resources/config.properties b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/main/resources/config.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/basic-config/src/main/resources/config.properties rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/main/resources/config.properties diff --git a/spring-cloud-modules/spring-cloud-archaius/basic-config/src/main/resources/other.properties b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/main/resources/other.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/basic-config/src/main/resources/other.properties rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/main/resources/other.properties diff --git a/spring-cloud-modules/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/SpringContextTest.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-cloud-modules/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationIntegrationTest.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationIntegrationTest.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationIntegrationTest.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationIntegrationTest.java diff --git a/spring-cloud-modules/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationLiveTest.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationLiveTest.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationLiveTest.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/ArchaiusBasicConfigurationLiveTest.java diff --git a/spring-cloud-modules/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextTest.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextTest.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextTest.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/test/java/com/baeldung/spring/cloud/archaius/basic/SpringContextTest.java diff --git a/spring-cloud-modules/spring-cloud-archaius/basic-config/src/test/resources/config.properties b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/test/resources/config.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/basic-config/src/test/resources/config.properties rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/test/resources/config.properties diff --git a/spring-cloud-modules/spring-cloud-archaius/basic-config/src/test/resources/logback-test.xml b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/test/resources/logback-test.xml similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/basic-config/src/test/resources/logback-test.xml rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-basic-config/src/test/resources/logback-test.xml diff --git a/spring-cloud-modules/spring-cloud-archaius/dynamodb-config/pom.xml b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/pom.xml similarity index 93% rename from spring-cloud-modules/spring-cloud-archaius/dynamodb-config/pom.xml rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/pom.xml index 08c96fb1f6..6e25ace6a8 100644 --- a/spring-cloud-modules/spring-cloud-archaius/dynamodb-config/pom.xml +++ b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/pom.xml @@ -3,8 +3,8 @@ xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - dynamodb-config - dynamodb-config + spring-cloud-archaius-dynamodb-config + spring-cloud-archaius-dynamodb-config jar diff --git a/spring-cloud-modules/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/DynamoSourcesApplication.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/DynamoSourcesApplication.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/DynamoSourcesApplication.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/DynamoSourcesApplication.java diff --git a/spring-cloud-modules/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/ApplicationPropertiesConfigurations.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/ApplicationPropertiesConfigurations.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/ApplicationPropertiesConfigurations.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/ApplicationPropertiesConfigurations.java diff --git a/spring-cloud-modules/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/DynamoDbConfiguration.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/DynamoDbConfiguration.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/DynamoDbConfiguration.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/config/DynamoDbConfiguration.java diff --git a/spring-cloud-modules/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/controller/ConfigPropertiesController.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/controller/ConfigPropertiesController.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/controller/ConfigPropertiesController.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/controller/ConfigPropertiesController.java diff --git a/spring-cloud-modules/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusProperties.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusProperties.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusProperties.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusProperties.java diff --git a/spring-cloud-modules/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusPropertiesRepository.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusPropertiesRepository.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusPropertiesRepository.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/src/main/java/com/baeldung/spring/cloud/archaius/dynamosources/dynamodb/ArchaiusPropertiesRepository.java diff --git a/spring-cloud-modules/spring-cloud-archaius/dynamodb-config/src/main/resources/application.properties b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/src/main/resources/application.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/dynamodb-config/src/main/resources/application.properties rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/src/main/resources/application.properties diff --git a/spring-cloud-modules/spring-cloud-archaius/dynamodb-config/src/test/java/com/baeldung/spring/cloud/archaius/dynamosources/ArchaiusDynamoDbLiveTest.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/src/test/java/com/baeldung/spring/cloud/archaius/dynamosources/ArchaiusDynamoDbLiveTest.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/dynamodb-config/src/test/java/com/baeldung/spring/cloud/archaius/dynamosources/ArchaiusDynamoDbLiveTest.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/src/test/java/com/baeldung/spring/cloud/archaius/dynamosources/ArchaiusDynamoDbLiveTest.java diff --git a/spring-cloud-modules/spring-cloud-archaius/dynamodb-config/src/test/java/com/baeldung/spring/cloud/archaius/dynamosources/SpringContextLiveTest.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/src/test/java/com/baeldung/spring/cloud/archaius/dynamosources/SpringContextLiveTest.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/dynamodb-config/src/test/java/com/baeldung/spring/cloud/archaius/dynamosources/SpringContextLiveTest.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-dynamodb-config/src/test/java/com/baeldung/spring/cloud/archaius/dynamosources/SpringContextLiveTest.java diff --git a/spring-cloud-modules/spring-cloud-archaius/extra-configs/pom.xml b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/pom.xml similarity index 92% rename from spring-cloud-modules/spring-cloud-archaius/extra-configs/pom.xml rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/pom.xml index 4113bf5bca..f90570abc2 100644 --- a/spring-cloud-modules/spring-cloud-archaius/extra-configs/pom.xml +++ b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/pom.xml @@ -3,9 +3,9 @@ xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - extra-configs + spring-cloud-archaius-extra-configs 1.0.0-SNAPSHOT - extra-configs + spring-cloud-archaius-extra-configs jar diff --git a/spring-cloud-modules/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/ExtraConfigsApplication.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/ExtraConfigsApplication.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/ExtraConfigsApplication.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/ExtraConfigsApplication.java diff --git a/spring-cloud-modules/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/controllers/ConfigPropertiesController.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/controllers/ConfigPropertiesController.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/controllers/ConfigPropertiesController.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/src/main/java/com/baeldung/spring/cloud/archaius/extraconfigs/controllers/ConfigPropertiesController.java diff --git a/spring-cloud-modules/spring-cloud-archaius/extra-configs/src/main/resources/application.properties b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/src/main/resources/application.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/extra-configs/src/main/resources/application.properties rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/src/main/resources/application.properties diff --git a/spring-cloud-modules/spring-cloud-archaius/extra-configs/src/main/resources/other-config-dir/extra.properties b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/src/main/resources/other-config-dir/extra.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/extra-configs/src/main/resources/other-config-dir/extra.properties rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/src/main/resources/other-config-dir/extra.properties diff --git a/spring-cloud-modules/spring-cloud-archaius/extra-configs/src/main/resources/other.properties b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/src/main/resources/other.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/extra-configs/src/main/resources/other.properties rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/src/main/resources/other.properties diff --git a/spring-cloud-modules/spring-cloud-archaius/extra-configs/src/test/java/com/baeldung/SpringContextTest.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/extra-configs/src/test/java/com/baeldung/SpringContextTest.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-cloud-modules/spring-cloud-archaius/extra-configs/src/test/java/com/baeldung/spring/cloud/archaius/extraconfigs/ArchaiusExtraConfigsLiveTest.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/src/test/java/com/baeldung/spring/cloud/archaius/extraconfigs/ArchaiusExtraConfigsLiveTest.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/extra-configs/src/test/java/com/baeldung/spring/cloud/archaius/extraconfigs/ArchaiusExtraConfigsLiveTest.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/src/test/java/com/baeldung/spring/cloud/archaius/extraconfigs/ArchaiusExtraConfigsLiveTest.java diff --git a/spring-cloud-modules/spring-cloud-archaius/extra-configs/src/test/resources/logback-test.xml b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/src/test/resources/logback-test.xml similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/extra-configs/src/test/resources/logback-test.xml rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-extra-configs/src/test/resources/logback-test.xml diff --git a/spring-cloud-modules/spring-cloud-archaius/jdbc-config/pom.xml b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/pom.xml similarity index 90% rename from spring-cloud-modules/spring-cloud-archaius/jdbc-config/pom.xml rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/pom.xml index dcaf934849..7fb5747739 100644 --- a/spring-cloud-modules/spring-cloud-archaius/jdbc-config/pom.xml +++ b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/pom.xml @@ -3,8 +3,8 @@ xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - jdbc-config - jdbc-config + spring-cloud-archaius-jdbc-config + spring-cloud-archaius-jdbc-config jar diff --git a/spring-cloud-modules/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/JdbcSourcesApplication.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/JdbcSourcesApplication.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/JdbcSourcesApplication.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/JdbcSourcesApplication.java diff --git a/spring-cloud-modules/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/config/ApplicationPropertiesConfigurations.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/config/ApplicationPropertiesConfigurations.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/config/ApplicationPropertiesConfigurations.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/config/ApplicationPropertiesConfigurations.java diff --git a/spring-cloud-modules/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/controller/ConfigPropertiesController.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/controller/ConfigPropertiesController.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/controller/ConfigPropertiesController.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/controller/ConfigPropertiesController.java diff --git a/spring-cloud-modules/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/jdbc/Properties.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/jdbc/Properties.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/jdbc/Properties.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/src/main/java/com/baeldung/spring/cloud/archaius/jdbconfig/jdbc/Properties.java diff --git a/spring-cloud-modules/spring-cloud-archaius/jdbc-config/src/main/resources/application.properties b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/src/main/resources/application.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/jdbc-config/src/main/resources/application.properties rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/src/main/resources/application.properties diff --git a/spring-cloud-modules/spring-cloud-archaius/jdbc-config/src/main/resources/data.sql b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/src/main/resources/data.sql similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/jdbc-config/src/main/resources/data.sql rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/src/main/resources/data.sql diff --git a/spring-cloud-modules/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/ArchaiusJDBCSourceLiveTest.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/ArchaiusJDBCSourceLiveTest.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/ArchaiusJDBCSourceLiveTest.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/ArchaiusJDBCSourceLiveTest.java diff --git a/spring-cloud-modules/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/SpringContextTest.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/SpringContextTest.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/SpringContextTest.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/src/test/java/com/baeldung/spring/cloud/archaius/jdbconfig/SpringContextTest.java diff --git a/spring-cloud-modules/spring-cloud-archaius/jdbc-config/src/test/resources/logback-test.xml b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/src/test/resources/logback-test.xml similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/jdbc-config/src/test/resources/logback-test.xml rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-jdbc-config/src/test/resources/logback-test.xml diff --git a/spring-cloud-modules/spring-cloud-archaius/zookeeper-config/pom.xml b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-zookeeper-config/pom.xml similarity index 93% rename from spring-cloud-modules/spring-cloud-archaius/zookeeper-config/pom.xml rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-zookeeper-config/pom.xml index 7700a2219d..f7c93fd9bf 100644 --- a/spring-cloud-modules/spring-cloud-archaius/zookeeper-config/pom.xml +++ b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-zookeeper-config/pom.xml @@ -3,8 +3,8 @@ xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - zookeeper-config - zookeeper-config + spring-cloud-archaius-zookeeper-config + spring-cloud-archaius-zookeeper-config jar diff --git a/spring-cloud-modules/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ZookeeperConfigApplication.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ZookeeperConfigApplication.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ZookeeperConfigApplication.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ZookeeperConfigApplication.java diff --git a/spring-cloud-modules/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/config/ZookeeperConfigsInitializer.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/config/ZookeeperConfigsInitializer.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/config/ZookeeperConfigsInitializer.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/config/ZookeeperConfigsInitializer.java diff --git a/spring-cloud-modules/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/controller/ConfigPropertiesController.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/controller/ConfigPropertiesController.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/controller/ConfigPropertiesController.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-zookeeper-config/src/main/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/controller/ConfigPropertiesController.java diff --git a/spring-cloud-modules/spring-cloud-archaius/zookeeper-config/src/main/resources/application.properties b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-zookeeper-config/src/main/resources/application.properties similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/zookeeper-config/src/main/resources/application.properties rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-zookeeper-config/src/main/resources/application.properties diff --git a/spring-cloud-modules/spring-cloud-archaius/zookeeper-config/src/test/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ArchaiusZookeeperLiveTest.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-zookeeper-config/src/test/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ArchaiusZookeeperLiveTest.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/zookeeper-config/src/test/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ArchaiusZookeeperLiveTest.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-zookeeper-config/src/test/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/ArchaiusZookeeperLiveTest.java diff --git a/spring-cloud-modules/spring-cloud-archaius/zookeeper-config/src/test/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/SpringContextLiveTest.java b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-zookeeper-config/src/test/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/SpringContextLiveTest.java similarity index 100% rename from spring-cloud-modules/spring-cloud-archaius/zookeeper-config/src/test/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/SpringContextLiveTest.java rename to spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-zookeeper-config/src/test/java/com/baeldung/spring/cloud/archaius/zookeeperconfig/SpringContextLiveTest.java diff --git a/spring-cloud-modules/spring-cloud-dapr/pom.xml b/spring-cloud-modules/spring-cloud-dapr/pom.xml index 24b6c989bd..2bac0e8eaf 100644 --- a/spring-cloud-modules/spring-cloud-dapr/pom.xml +++ b/spring-cloud-modules/spring-cloud-dapr/pom.xml @@ -13,8 +13,8 @@ - gateway - greeting + spring-cloud-dapr-gateway + spring-cloud-dapr-greeting \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-dapr/gateway/pom.xml b/spring-cloud-modules/spring-cloud-dapr/spring-cloud-dapr-gateway/pom.xml similarity index 96% rename from spring-cloud-modules/spring-cloud-dapr/gateway/pom.xml rename to spring-cloud-modules/spring-cloud-dapr/spring-cloud-dapr-gateway/pom.xml index 6545c61002..7874edda4a 100644 --- a/spring-cloud-modules/spring-cloud-dapr/gateway/pom.xml +++ b/spring-cloud-modules/spring-cloud-dapr/spring-cloud-dapr-gateway/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.spring.cloud.spring-cloud-dapr - gateway + spring-cloud-dapr-gateway 1.0-SNAPSHOT diff --git a/spring-cloud-modules/spring-cloud-dapr/gateway/src/main/java/com/baeldung/gateway/GatewayApp.java b/spring-cloud-modules/spring-cloud-dapr/spring-cloud-dapr-gateway/src/main/java/com/baeldung/gateway/GatewayApp.java similarity index 100% rename from spring-cloud-modules/spring-cloud-dapr/gateway/src/main/java/com/baeldung/gateway/GatewayApp.java rename to spring-cloud-modules/spring-cloud-dapr/spring-cloud-dapr-gateway/src/main/java/com/baeldung/gateway/GatewayApp.java diff --git a/spring-cloud-modules/spring-cloud-dapr/gateway/src/main/resources/application-no-dapr.yml b/spring-cloud-modules/spring-cloud-dapr/spring-cloud-dapr-gateway/src/main/resources/application-no-dapr.yml similarity index 100% rename from spring-cloud-modules/spring-cloud-dapr/gateway/src/main/resources/application-no-dapr.yml rename to spring-cloud-modules/spring-cloud-dapr/spring-cloud-dapr-gateway/src/main/resources/application-no-dapr.yml diff --git a/spring-cloud-modules/spring-cloud-dapr/gateway/src/main/resources/application-with-dapr.yml b/spring-cloud-modules/spring-cloud-dapr/spring-cloud-dapr-gateway/src/main/resources/application-with-dapr.yml similarity index 100% rename from spring-cloud-modules/spring-cloud-dapr/gateway/src/main/resources/application-with-dapr.yml rename to spring-cloud-modules/spring-cloud-dapr/spring-cloud-dapr-gateway/src/main/resources/application-with-dapr.yml diff --git a/spring-cloud-modules/spring-cloud-dapr/greeting/pom.xml b/spring-cloud-modules/spring-cloud-dapr/spring-cloud-dapr-greeting/pom.xml similarity index 94% rename from spring-cloud-modules/spring-cloud-dapr/greeting/pom.xml rename to spring-cloud-modules/spring-cloud-dapr/spring-cloud-dapr-greeting/pom.xml index 22b4004cbf..24aa2f4dcf 100644 --- a/spring-cloud-modules/spring-cloud-dapr/greeting/pom.xml +++ b/spring-cloud-modules/spring-cloud-dapr/spring-cloud-dapr-greeting/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung.spring.cloud.spring-cloud-dapr - greeting + spring-cloud-dapr-greeting 1.0-SNAPSHOT diff --git a/spring-cloud-modules/spring-cloud-dapr/greeting/src/main/java/com/baeldung/hello/GreetingApp.java b/spring-cloud-modules/spring-cloud-dapr/spring-cloud-dapr-greeting/src/main/java/com/baeldung/hello/GreetingApp.java similarity index 100% rename from spring-cloud-modules/spring-cloud-dapr/greeting/src/main/java/com/baeldung/hello/GreetingApp.java rename to spring-cloud-modules/spring-cloud-dapr/spring-cloud-dapr-greeting/src/main/java/com/baeldung/hello/GreetingApp.java diff --git a/spring-cloud-modules/spring-cloud-dapr/greeting/src/main/java/com/baeldung/hello/GreetingController.java b/spring-cloud-modules/spring-cloud-dapr/spring-cloud-dapr-greeting/src/main/java/com/baeldung/hello/GreetingController.java similarity index 100% rename from spring-cloud-modules/spring-cloud-dapr/greeting/src/main/java/com/baeldung/hello/GreetingController.java rename to spring-cloud-modules/spring-cloud-dapr/spring-cloud-dapr-greeting/src/main/java/com/baeldung/hello/GreetingController.java diff --git a/spring-cloud-modules/spring-cloud-dapr/greeting/src/main/resources/application.yml b/spring-cloud-modules/spring-cloud-dapr/spring-cloud-dapr-greeting/src/main/resources/application.yml similarity index 100% rename from spring-cloud-modules/spring-cloud-dapr/greeting/src/main/resources/application.yml rename to spring-cloud-modules/spring-cloud-dapr/spring-cloud-dapr-greeting/src/main/resources/application.yml diff --git a/spring-cloud-modules/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/ipaddress/IpAddressApplication.java b/spring-cloud-modules/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/ipaddress/IpAddressApplication.java new file mode 100644 index 0000000000..472c331404 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/ipaddress/IpAddressApplication.java @@ -0,0 +1,38 @@ +package com.baeldung.springcloudgateway.ipaddress; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter; +import org.springframework.cloud.gateway.route.RouteLocator; +import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.PropertySource; + +@SpringBootApplication() +@PropertySource("classpath:ipaddress-application.properties") +public class IpAddressApplication { + public static void main(String[] args) { + SpringApplication.run(IpAddressApplication.class, args); + } + + @Bean + public RouteLocator myRoutes(RouteLocatorBuilder builder) { + return builder.routes() + .route("requestratelimiter_route", p -> p + .path("/example") + .filters(f -> f.requestRateLimiter(r -> r.setRateLimiter(redisRateLimiter()))) + .uri("http://example.org")) + .route("ipaddress_route", p -> p + .path("/example2") + .filters(f -> f.requestRateLimiter(r -> r.setRateLimiter(redisRateLimiter()) + .setDenyEmptyKey(false) + .setKeyResolver(new SimpleClientAddressResolver()))) + .uri("http://example.org")) + .build(); + } + + @Bean + public RedisRateLimiter redisRateLimiter() { + return new RedisRateLimiter(1, 1, 1); + } +} diff --git a/spring-cloud-modules/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/ipaddress/ProxiedClientAddressResolver.java b/spring-cloud-modules/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/ipaddress/ProxiedClientAddressResolver.java new file mode 100644 index 0000000000..25b1fbcf1f --- /dev/null +++ b/spring-cloud-modules/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/ipaddress/ProxiedClientAddressResolver.java @@ -0,0 +1,21 @@ +package com.baeldung.springcloudgateway.ipaddress; + +import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; +import org.springframework.cloud.gateway.support.ipresolver.XForwardedRemoteAddressResolver; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import java.net.InetSocketAddress; + +@Primary +@Component +public class ProxiedClientAddressResolver implements KeyResolver { + @Override + public Mono resolve(ServerWebExchange exchange) { + XForwardedRemoteAddressResolver resolver = XForwardedRemoteAddressResolver.maxTrustedIndex(1); + InetSocketAddress inetSocketAddress = resolver.resolve(exchange); + return Mono.just(inetSocketAddress.getAddress().getHostAddress()); + } +} diff --git a/spring-cloud-modules/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/ipaddress/SimpleClientAddressResolver.java b/spring-cloud-modules/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/ipaddress/SimpleClientAddressResolver.java new file mode 100644 index 0000000000..904fd4c193 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/ipaddress/SimpleClientAddressResolver.java @@ -0,0 +1,23 @@ +package com.baeldung.springcloudgateway.ipaddress; + +import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.Optional; + +@Component +public class SimpleClientAddressResolver implements KeyResolver { + @Override + public Mono resolve(ServerWebExchange exchange) { + return Optional.ofNullable(exchange.getRequest().getRemoteAddress()) + .map(InetSocketAddress::getAddress) + .map(InetAddress::getHostAddress) + .map(Mono::just) + .orElse(Mono.empty()); + } +} + diff --git a/spring-cloud-modules/spring-cloud-gateway/src/main/resources/ipaddress-application.properties b/spring-cloud-modules/spring-cloud-gateway/src/main/resources/ipaddress-application.properties new file mode 100644 index 0000000000..ebec52403a --- /dev/null +++ b/spring-cloud-modules/spring-cloud-gateway/src/main/resources/ipaddress-application.properties @@ -0,0 +1,6 @@ +server.port=8081 +spring.redis.database=0 +spring.redis.host=localhost +spring.redis.port=16379 +spring.redis.password=mypass +spring.redis.timeout=60000 diff --git a/spring-security-modules/pom.xml b/spring-security-modules/pom.xml index 1e0ae825e1..d6e30e8ab8 100644 --- a/spring-security-modules/pom.xml +++ b/spring-security-modules/pom.xml @@ -43,6 +43,7 @@ spring-security-web-rest-basic-auth spring-security-web-rest-custom spring-security-web-rest + spring-security-web-springdoc spring-security-web-sockets spring-security-web-thymeleaf spring-security-web-x509 diff --git a/spring-security-modules/spring-security-web-boot-1/pom.xml b/spring-security-modules/spring-security-web-boot-1/pom.xml index fa0fd567fe..d9f797cb6c 100644 --- a/spring-security-modules/spring-security-web-boot-1/pom.xml +++ b/spring-security-modules/spring-security-web-boot-1/pom.xml @@ -217,7 +217,8 @@ com.baeldung.roles.custom.Application - + 1.1.2 diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/resources/application.properties b/spring-security-modules/spring-security-web-boot-1/src/main/resources/application.properties index 3cf12afeb9..cc1e92d43a 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/resources/application.properties +++ b/spring-security-modules/spring-security-web-boot-1/src/main/resources/application.properties @@ -1 +1,2 @@ server.port=8082 +server.servlet.register-default-servlet=true diff --git a/spring-security-modules/spring-security-web-boot-1/src/test/java/com/baeldung/roles/web/ApplicationLiveTest.java b/spring-security-modules/spring-security-web-boot-1/src/test/java/com/baeldung/roles/web/ApplicationLiveTest.java index 56f87e8aee..ea848468b4 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/test/java/com/baeldung/roles/web/ApplicationLiveTest.java +++ b/spring-security-modules/spring-security-web-boot-1/src/test/java/com/baeldung/roles/web/ApplicationLiveTest.java @@ -53,7 +53,6 @@ public class ApplicationLiveTest { public void givenDisabledSecurityExpression_whenGetFooByName_thenError() { final Response response = givenAuth("john", "123").get("http://localhost:8082/foos?name=sample"); assertEquals(500, response.getStatusCode()); - assertTrue(response.asString().contains("method hasAuthority() not allowed")); } private RequestSpecification givenAuth(String username, String password) { diff --git a/spring-security-modules/spring-security-web-springdoc/README.md b/spring-security-modules/spring-security-web-springdoc/README.md new file mode 100644 index 0000000000..2f1ec59f6e --- /dev/null +++ b/spring-security-modules/spring-security-web-springdoc/README.md @@ -0,0 +1,12 @@ +## Spring Security Web Springdoc + +This module contains articles about Springdoc with Spring Security + +### Relevant Articles: + +### Running This Project: + +To run the projects use the commands: +- `mvn spring-boot:run -Dstart-class=com.baeldung.basicauth.SpringBootSpringdocBasicAuth` +- `mvn spring-boot:run -Dstart-class=com.baeldung.formlogin.SpringBootSpringdocFormLogin` + diff --git a/spring-security-modules/spring-security-web-springdoc/pom.xml b/spring-security-modules/spring-security-web-springdoc/pom.xml new file mode 100644 index 0000000000..03e938f1c8 --- /dev/null +++ b/spring-security-modules/spring-security-web-springdoc/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + spring-security-web-springdoc + 0.1-SNAPSHOT + spring-security-web-springdoc + jar + Spring Security with Springdoc tutorial + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + org.springdoc + springdoc-openapi-ui + ${springdoc.version} + + + org.springdoc + springdoc-openapi-security + ${springdoc.version} + + + com.google.guava + guava + ${guava.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + + + 1.6.13 + + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/basicauth/Foo.java b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/basicauth/Foo.java new file mode 100644 index 0000000000..ab0f010e2c --- /dev/null +++ b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/basicauth/Foo.java @@ -0,0 +1,60 @@ +package com.baeldung.basicauth; + +import java.io.Serializable; + +public class Foo implements Serializable { + + private static final long serialVersionUID = -5422285893276747592L; + + private long id; + private String name; + + public Foo(final String name) { + super(); + this.name = name; + } + + 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; + } + + @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) { + return other.name == null; + } else return name.equals(other.name); + } + + @Override + public String toString() { + return "Foo [name=" + name + "]"; + } + +} diff --git a/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/basicauth/FooController.java b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/basicauth/FooController.java new file mode 100644 index 0000000000..9ca2f9a6cc --- /dev/null +++ b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/basicauth/FooController.java @@ -0,0 +1,39 @@ +package com.baeldung.basicauth; + +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; + +import com.google.common.collect.Lists; + +@RestController +@OpenAPIDefinition(info = @Info(title = "Foos API", version = "v1")) +@SecurityRequirement(name = "basicAuth") +@RequestMapping(value = "foos", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) +public class FooController { + + private static final int STRING_LENGTH = 6; + + @GetMapping(value = "/{id}") + public Foo findById(@PathVariable("id") final Long id) { + return new Foo(randomAlphabetic(STRING_LENGTH)); + } + + @GetMapping + public List findAll() { + return Lists.newArrayList(new Foo(randomAlphabetic(STRING_LENGTH)), new Foo(randomAlphabetic(STRING_LENGTH)), new Foo(randomAlphabetic(STRING_LENGTH))); + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public Foo create(@RequestBody final Foo foo) { + return foo; + } +} diff --git a/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/basicauth/SpringBootSpringdocBasicAuth.java b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/basicauth/SpringBootSpringdocBasicAuth.java new file mode 100644 index 0000000000..0875c5d176 --- /dev/null +++ b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/basicauth/SpringBootSpringdocBasicAuth.java @@ -0,0 +1,13 @@ +package com.baeldung.basicauth; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootSpringdocBasicAuth { + + public static void main(String[] args) { + SpringApplication.run(SpringBootSpringdocBasicAuth.class, args); + } + +} diff --git a/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/basicauth/config/PasswordEncoderConfiguration.java b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/basicauth/config/PasswordEncoderConfiguration.java new file mode 100644 index 0000000000..4da6b5438b --- /dev/null +++ b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/basicauth/config/PasswordEncoderConfiguration.java @@ -0,0 +1,15 @@ +package com.baeldung.basicauth.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class PasswordEncoderConfiguration { + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/basicauth/config/SecurityConfiguration.java b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/basicauth/config/SecurityConfiguration.java new file mode 100644 index 0000000000..a419162828 --- /dev/null +++ b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/basicauth/config/SecurityConfiguration.java @@ -0,0 +1,38 @@ +package com.baeldung.basicauth.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +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.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; + +@Configuration +@EnableWebSecurity +public class SecurityConfiguration { + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/v3/api-docs/**", + "/swagger-ui/**", + "/swagger-ui.html").permitAll() + .anyRequest().authenticated() + .and() + .httpBasic(); + return http.build(); + } + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth, PasswordEncoder passwordEncoder) throws Exception { + auth.inMemoryAuthentication() + .withUser("user") + .password(passwordEncoder.encode("password")) + .roles("USER"); + } + +} diff --git a/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/basicauth/config/SpringdocConfig.java b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/basicauth/config/SpringdocConfig.java new file mode 100644 index 0000000000..57d3d8bd02 --- /dev/null +++ b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/basicauth/config/SpringdocConfig.java @@ -0,0 +1,12 @@ +package com.baeldung.basicauth.config; + +import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; +import io.swagger.v3.oas.annotations.security.SecurityScheme; +import org.springframework.context.annotation.Configuration; + +@Configuration +@SecurityScheme( + type = SecuritySchemeType.HTTP, + name = "basicAuth", + scheme = "basic") +public class SpringdocConfig {} diff --git a/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/SpringBootSpringdocFormLogin.java b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/SpringBootSpringdocFormLogin.java new file mode 100644 index 0000000000..5c4c262fa7 --- /dev/null +++ b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/SpringBootSpringdocFormLogin.java @@ -0,0 +1,13 @@ +package com.baeldung.formlogin; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootSpringdocFormLogin { + + public static void main(String[] args) { + SpringApplication.run(SpringBootSpringdocFormLogin.class, args); + } + +} diff --git a/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/config/PasswordEncoderConfiguration.java b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/config/PasswordEncoderConfiguration.java new file mode 100644 index 0000000000..e3f9e71bd6 --- /dev/null +++ b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/config/PasswordEncoderConfiguration.java @@ -0,0 +1,15 @@ +package com.baeldung.formlogin.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class PasswordEncoderConfiguration { + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/config/SecurityConfiguration.java b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/config/SecurityConfiguration.java new file mode 100644 index 0000000000..2b849031ce --- /dev/null +++ b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/config/SecurityConfiguration.java @@ -0,0 +1,40 @@ +package com.baeldung.formlogin.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +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.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; + +@Configuration +@EnableWebSecurity +public class SecurityConfiguration { + + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/v3/api-docs/**", + "/swagger-ui/**", + "/swagger-ui.html").permitAll() + .anyRequest().authenticated() + .and() + .formLogin() + .defaultSuccessUrl("/foos"); + return http.build(); + } + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth, PasswordEncoder passwordEncoder) throws Exception { + auth.inMemoryAuthentication() + .withUser("user") + .password(passwordEncoder.encode("password")) + .roles("USER"); + } + +} diff --git a/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/controller/FooController.java b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/controller/FooController.java new file mode 100644 index 0000000000..1d09789067 --- /dev/null +++ b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/controller/FooController.java @@ -0,0 +1,37 @@ +package com.baeldung.formlogin.controller; + +import com.baeldung.formlogin.model.Foo; +import com.google.common.collect.Lists; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.info.Info; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; + +@RestController +@RequestMapping(value = "foos", produces = MediaType.APPLICATION_JSON_VALUE) +@OpenAPIDefinition(info = @Info(title = "Foos API", version = "v1")) +public class FooController { + + private static final int STRING_LENGTH = 6; + + @GetMapping(value = "/{id}") + public Foo findById(@PathVariable("id") final Long id) { + return new Foo(randomAlphabetic(STRING_LENGTH)); + } + + @GetMapping + public List findAll() { + return Lists.newArrayList(new Foo(randomAlphabetic(STRING_LENGTH)), new Foo(randomAlphabetic(STRING_LENGTH)), new Foo(randomAlphabetic(STRING_LENGTH))); + } + + @PostMapping + @ResponseStatus(HttpStatus.CREATED) + public Foo create(@RequestBody final Foo foo) { + return foo; + } +} diff --git a/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/controller/LogoutController.java b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/controller/LogoutController.java new file mode 100644 index 0000000000..ab1c635de0 --- /dev/null +++ b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/controller/LogoutController.java @@ -0,0 +1,17 @@ +package com.baeldung.formlogin.controller; + +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import org.springframework.web.bind.annotation.*; + +@RestController +@OpenAPIDefinition(info = @Info(title = "logout-endpoint")) +public class LogoutController { + + @PostMapping("logout") + @Operation(description = "End authenticated user session") + public void logout() { + throw new UnsupportedOperationException(); + } +} diff --git a/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/model/Foo.java b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/model/Foo.java new file mode 100644 index 0000000000..5133c215b3 --- /dev/null +++ b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/model/Foo.java @@ -0,0 +1,62 @@ +package com.baeldung.formlogin.model; + +import java.io.Serializable; + +public class Foo implements Serializable { + + private static final long serialVersionUID = -5422285893276747592L; + + private long id; + private String name; + + public Foo(final String name) { + this.name = name; + } + + public Foo() { + } + + 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; + } + + @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) { + return other.name == null; + } else return name.equals(other.name); + } + + @Override + public String toString() { + return "Foo [name=" + name + "]"; + } + +} diff --git a/spring-security-modules/spring-security-web-springdoc/src/main/resources/application.properties b/spring-security-modules/spring-security-web-springdoc/src/main/resources/application.properties new file mode 100644 index 0000000000..7157c0f5b9 --- /dev/null +++ b/spring-security-modules/spring-security-web-springdoc/src/main/resources/application.properties @@ -0,0 +1 @@ +springdoc.show-login-endpoint=true diff --git a/spring-security-modules/spring-security-web-springdoc/src/test/java/com/baeldung/basicauth/OpenAPIIntegrationTest.java b/spring-security-modules/spring-security-web-springdoc/src/test/java/com/baeldung/basicauth/OpenAPIIntegrationTest.java new file mode 100644 index 0000000000..3e622059c1 --- /dev/null +++ b/spring-security-modules/spring-security-web-springdoc/src/test/java/com/baeldung/basicauth/OpenAPIIntegrationTest.java @@ -0,0 +1,64 @@ +package com.baeldung.basicauth; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +class OpenAPIIntegrationTest { + + @LocalServerPort + private int port; + + @Autowired + private TestRestTemplate restTemplate; + + @Test + void whenInvokeSwagger_thenRenderIndexPage() { + String response = this.restTemplate.getForObject("http://localhost:" + port + "/swagger-ui/index.html", String.class); + + assertNotNull(response); + assertTrue(response.contains("Swagger UI")); + assertTrue(response.contains("
")); + } + + @Test + void whenInvokeOpenApi_thenCheckHeaders() { + ResponseEntity response = this.restTemplate.getForEntity("http://localhost:" + port + "/v3/api-docs", String.class); + + assertNotNull(response); + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertNotNull(response.getHeaders().get("Content-Type")); + assertEquals(1, response.getHeaders().get("Content-Type").size()); + assertEquals("application/json", response.getHeaders().get("Content-Type").get(0)); + } + + @Test + void whenInvokeOpenApi_thenVerifyOpenApiDoc() { + ResponseEntity response = this.restTemplate.getForEntity("http://localhost:" + port + "/v3/api-docs", String.class); + + assertNotNull(response); + assertNotNull(response.getBody()); + assertTrue(response.getBody().contains("\"openapi\":")); + assertTrue(response.getBody().contains("Foos API")); + assertTrue(response.getBody().contains("\"post\"")); + } + + @Test + void whenInvokeOpenApi_thenCheckSecurityConfig() { + ResponseEntity response = this.restTemplate.getForEntity("http://localhost:" + port + "/v3/api-docs", String.class); + + assertNotNull(response); + assertNotNull(response.getBody()); + assertTrue(response.getBody().contains("\"securitySchemes\"")); + assertTrue(response.getBody().contains("\"type\":\"http\"")); + assertTrue(response.getBody().contains("\"scheme\":\"basic\"")); + } +} diff --git a/spring-security-modules/spring-security-web-springdoc/src/test/java/com/baeldung/formlogin/OpenAPIIntegrationTest.java b/spring-security-modules/spring-security-web-springdoc/src/test/java/com/baeldung/formlogin/OpenAPIIntegrationTest.java new file mode 100644 index 0000000000..5d942f2126 --- /dev/null +++ b/spring-security-modules/spring-security-web-springdoc/src/test/java/com/baeldung/formlogin/OpenAPIIntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.formlogin; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import static org.junit.jupiter.api.Assertions.*; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +class OpenAPIIntegrationTest { + + @LocalServerPort + private int port; + + @Autowired + private TestRestTemplate restTemplate; + + @Test + void whenInvokeSwagger_thenRenderIndexPage() { + String response = this.restTemplate.getForObject("http://localhost:" + port + "/swagger-ui/index.html", String.class); + + assertNotNull(response); + assertTrue(response.contains("Swagger UI")); + assertTrue(response.contains("
")); + } + + @Test + void whenInvokeOpenApi_thenCheckHeaders() { + ResponseEntity response = this.restTemplate.getForEntity("http://localhost:" + port + "/v3/api-docs", String.class); + + assertNotNull(response); + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertNotNull(response.getHeaders().get("Content-Type")); + assertEquals(1, response.getHeaders().get("Content-Type").size()); + assertEquals("application/json", response.getHeaders().get("Content-Type").get(0)); + } + + @Test + void whenInvokeOpenApi_thenVerifyOpenApiDoc() { + ResponseEntity response = this.restTemplate.getForEntity("http://localhost:" + port + "/v3/api-docs", String.class); + + assertNotNull(response); + assertNotNull(response.getBody()); + assertTrue(response.getBody().contains("\"openapi\":")); + assertTrue(response.getBody().contains("Foos API")); + assertTrue(response.getBody().contains("\"post\"")); + } +} diff --git a/testing-modules/assertion-libraries/src/main/java/com/baeldung/assertj/extracting/Address.java b/testing-modules/assertion-libraries/src/main/java/com/baeldung/assertj/extracting/Address.java new file mode 100644 index 0000000000..aa6ee85351 --- /dev/null +++ b/testing-modules/assertion-libraries/src/main/java/com/baeldung/assertj/extracting/Address.java @@ -0,0 +1,25 @@ +package com.baeldung.assertj.extracting; + +class Address { + private String street; + private String city; + private ZipCode zipCode; + + Address(String street, String city, ZipCode zipCode) { + this.street = street; + this.city = city; + this.zipCode = zipCode; + } + + public String getStreet() { + return street; + } + + public String getCity() { + return city; + } + + public ZipCode getZipCode() { + return zipCode; + } +} diff --git a/testing-modules/assertion-libraries/src/main/java/com/baeldung/assertj/extracting/Person.java b/testing-modules/assertion-libraries/src/main/java/com/baeldung/assertj/extracting/Person.java new file mode 100644 index 0000000000..b8a987cf09 --- /dev/null +++ b/testing-modules/assertion-libraries/src/main/java/com/baeldung/assertj/extracting/Person.java @@ -0,0 +1,25 @@ +package com.baeldung.assertj.extracting; + +class Person { + private String firstName; + private String lastName; + private Address address; + + Person(String firstName, String lastName, Address address) { + this.firstName = firstName; + this.lastName = lastName; + this.address = address; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public Address getAddress() { + return address; + } +} diff --git a/testing-modules/assertion-libraries/src/main/java/com/baeldung/assertj/extracting/ZipCode.java b/testing-modules/assertion-libraries/src/main/java/com/baeldung/assertj/extracting/ZipCode.java new file mode 100644 index 0000000000..1523ef7144 --- /dev/null +++ b/testing-modules/assertion-libraries/src/main/java/com/baeldung/assertj/extracting/ZipCode.java @@ -0,0 +1,13 @@ +package com.baeldung.assertj.extracting; + +class ZipCode { + private long zipcode; + + ZipCode(long zipcode) { + this.zipcode = zipcode; + } + + public long getZipcode() { + return zipcode; + } +} diff --git a/testing-modules/assertion-libraries/src/test/java/com/baeldung/assertj/extracting/AssertJExtractingUnitTest.java b/testing-modules/assertion-libraries/src/test/java/com/baeldung/assertj/extracting/AssertJExtractingUnitTest.java new file mode 100644 index 0000000000..aae4f8a041 --- /dev/null +++ b/testing-modules/assertion-libraries/src/test/java/com/baeldung/assertj/extracting/AssertJExtractingUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.assertj.extracting; + +import org.assertj.core.api.InstanceOfAssertFactories; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.as; +import static org.assertj.core.api.Assertions.assertThat; + +class AssertJExtractingUnitTest { + static final List
RESTRICTED_ADDRESSES = new ArrayList<>(); + + @Test + void whenUsingRegularAssertionFlow_thenCorrect() { + + // Given + Person person = new Person("aName", "aLastName", new Address("aStreet", "aCity", new ZipCode(90210))); + + // Then + Address address = person.getAddress(); + assertThat(address).isNotNull() + .isNotIn(RESTRICTED_ADDRESSES); + ZipCode zipCode = address.getZipCode(); + assertThat(zipCode).isNotNull(); + assertThat(zipCode.getZipcode()).isBetween(1000L, 100_000L); + } + + @Test + void whenUsingExtractingAssertionFlow_thenCorrect() { + + // Given + Person person = new Person("aName", "aLastName", new Address("aStreet", "aCity", new ZipCode(90210))); + + // Then + assertThat(person) + .extracting(Person::getAddress) + .isNotNull() + .isNotIn(RESTRICTED_ADDRESSES) + .extracting(Address::getZipCode) + .isNotNull() + .extracting(ZipCode::getZipcode, as(InstanceOfAssertFactories.LONG)) + .isBetween(1_000L, 100_000L); + } +} diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java index df3561d646..d611cd9e45 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.app.rest; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.AdditionalMatchers.or; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; @@ -10,18 +11,18 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.exceptions.misusing.InvalidUseOfMatchersException; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import com.baeldung.app.api.Flower; import com.baeldung.domain.service.FlowerService; -@RunWith(MockitoJUnitRunner.class) -public class FlowerControllerUnitTest { +@ExtendWith(MockitoExtension.class) +class FlowerControllerUnitTest { @InjectMocks private FlowerController flowerController; @@ -30,7 +31,7 @@ public class FlowerControllerUnitTest { private FlowerService flowerService; @Test - public void givenPoppyFlower_whenUsingDoReturn_thenCorrect() { + void givenPoppyFlower_whenUsingDoReturn_thenCorrect() { doReturn("Flower").when(flowerService).analyze("poppy"); String response = flowerController.isAFlower("poppy"); @@ -38,25 +39,27 @@ public class FlowerControllerUnitTest { } @Test - public void givenAnyString_whenUsingArgumentMatcher_thenCorrect() { + void givenAnyString_whenUsingArgumentMatcher_thenCorrect() { when(flowerService.analyze(anyString())).thenReturn("Flower"); String response = flowerController.isAFlower("violetta"); assertThat(response).isEqualTo("Flower"); } - @Test(expected = InvalidUseOfMatchersException.class) - public void whenIncorrectMatchers_thenThrowsError() { - when(flowerService.isABigFlower("poppy", anyInt())).thenReturn(true); + @Test + void whenIncorrectMatchers_thenThrowsError() { + assertThrows(InvalidUseOfMatchersException.class, () -> { + when(flowerService.isABigFlower("poppy", anyInt())).thenReturn(true); + }); Flower flower = new Flower("poppy", 15); Boolean response = flowerController.isABigFlower(flower); - assertThat(response).isTrue(); + assertThat(response).isFalse(); } @Test - public void whenCorrectMatchers_thenCorrect() { + void whenCorrectMatchers_thenCorrect() { when(flowerService.isABigFlower(eq("poppy"), anyInt())).thenReturn(true); Flower flower = new Flower("poppy", 15); @@ -65,23 +68,25 @@ public class FlowerControllerUnitTest { assertThat(response).isTrue(); } - @Test(expected = InvalidUseOfMatchersException.class) - public void whenUsingMatchersAsReturnValue_thenThrowsError() { + @Test + void whenUsingMatchersAsReturnValue_thenThrowsError() { flowerController.isAFlower("poppy"); String orMatcher = or(eq("poppy"), endsWith("y")); - verify(flowerService).analyze(orMatcher); + assertThrows(InvalidUseOfMatchersException.class, () -> { + verify(flowerService).analyze(orMatcher); + }); } @Test - public void whenUsingMatchersAsOngoingStubbing_thenCorrect1() { + void whenUsingMatchersAsOngoingStubbing_thenCorrect1() { flowerController.isAFlower("poppy"); verify(flowerService).analyze(or(eq("poppy"), endsWith("y"))); } @Test - public void whenUsingMatchersAsOngoingStubbing_thenCorrect2() { + void whenUsingMatchersAsOngoingStubbing_thenCorrect2() { flowerController.isAFlower("lily"); verify(flowerService).analyze(or(eq("poppy"), endsWith("y"))); diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java index 1bfbeecfec..84b5bf241e 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java @@ -5,52 +5,52 @@ import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import com.baeldung.app.api.MessageDTO; import com.baeldung.domain.model.Message; import com.baeldung.domain.service.MessageService; import com.baeldung.domain.util.MessageMatcher; -@RunWith(MockitoJUnitRunner.class) -public class MessageControllerUnitTest { +@ExtendWith(MockitoExtension.class) +class MessageControllerUnitTest { - @InjectMocks - private MessageController messageController; - - @Mock - private MessageService messageService; + @InjectMocks + private MessageController messageController; - @Test - public void givenMsg_whenVerifyUsingAnyMatcher_thenOk() { - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setFrom("me"); - messageDTO.setTo("you"); - messageDTO.setText("Hello, you!"); + @Mock + private MessageService messageService; - messageController.createMessage(messageDTO); + @Test + void givenMsg_whenVerifyUsingAnyMatcher_thenOk() { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setFrom("me"); + messageDTO.setTo("you"); + messageDTO.setText("Hello, you!"); - verify(messageService, times(1)).deliverMessage(any(Message.class)); - } + messageController.createMessage(messageDTO); - @Test - public void givenMsg_whenVerifyUsingMessageMatcher_thenOk() { - MessageDTO messageDTO = new MessageDTO(); - messageDTO.setFrom("me"); - messageDTO.setTo("you"); - messageDTO.setText("Hello, you!"); + verify(messageService, times(1)).deliverMessage(any(Message.class)); + } - messageController.createMessage(messageDTO); + @Test + void givenMsg_whenVerifyUsingMessageMatcher_thenOk() { + MessageDTO messageDTO = new MessageDTO(); + messageDTO.setFrom("me"); + messageDTO.setTo("you"); + messageDTO.setText("Hello, you!"); - Message message = new Message(); - message.setFrom("me"); - message.setTo("you"); - message.setText("Hello, you!"); + messageController.createMessage(messageDTO); - verify(messageService, times(1)).deliverMessage(argThat(new MessageMatcher(message))); - } + Message message = new Message(); + message.setFrom("me"); + message.setTo("you"); + message.setText("Hello, you!"); + + verify(messageService, times(1)).deliverMessage(argThat(new MessageMatcher(message))); + } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java index 8a350e5d9f..cc38d617b7 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/junit5/mockito/UserServiceUnitTest.java @@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -13,7 +14,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.stubbing.Answer; @@ -115,7 +115,7 @@ class UserServiceUnitTest { void givenUserWithExistingName_whenSaveUser_thenGiveUsernameAlreadyExistsError() { // Given user = new User("jerry", 12); - Mockito.reset(userRepository); + reset(userRepository); when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(true); // When diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockFinalsUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockFinalsUnitTest.java index 24ab67049f..a4b2bd03b4 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockFinalsUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockFinalsUnitTest.java @@ -4,12 +4,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class MockFinalsUnitTest { +class MockFinalsUnitTest { @Test - public void whenMockFinalMethodMockWorks() { + void whenMockFinalMethodMockWorks() { MyList myList = new MyList(); diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java index bd68afac75..acfd87e047 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationUnitTest.java @@ -1,23 +1,27 @@ package com.baeldung.mockito; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) -public class MockitoAnnotationUnitTest { +@ExtendWith(MockitoExtension.class) +class MockitoAnnotationUnitTest { @Mock private List mockedList; @@ -36,61 +40,61 @@ public class MockitoAnnotationUnitTest { // tests @Test - public void whenNotUseMockAnnotation_thenCorrect() { - final List mockList = Mockito.mock(List.class); + void whenNotUseMockAnnotation_thenCorrect() { + final List mockList = mock(List.class); mockList.add("one"); - Mockito.verify(mockList).add("one"); + verify(mockList).add("one"); assertEquals(0, mockList.size()); - Mockito.when(mockList.size()).thenReturn(100); + when(mockList.size()).thenReturn(100); assertEquals(100, mockList.size()); } @Test - public void whenUseMockAnnotation_thenMockIsInjected() { + void whenUseMockAnnotation_thenMockIsInjected() { mockedList.add("one"); - Mockito.verify(mockedList).add("one"); + verify(mockedList).add("one"); assertEquals(0, mockedList.size()); - Mockito.when(mockedList.size()).thenReturn(100); + when(mockedList.size()).thenReturn(100); assertEquals(100, mockedList.size()); } @Test - public void whenNotUseSpyAnnotation_thenCorrect() { - final List spyList = Mockito.spy(new ArrayList()); + void whenNotUseSpyAnnotation_thenCorrect() { + final List spyList = spy(new ArrayList()); spyList.add("one"); spyList.add("two"); - Mockito.verify(spyList).add("one"); - Mockito.verify(spyList).add("two"); + verify(spyList).add("one"); + verify(spyList).add("two"); assertEquals(2, spyList.size()); - Mockito.doReturn(100).when(spyList).size(); + doReturn(100).when(spyList).size(); assertEquals(100, spyList.size()); } @Test - public void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() { + void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() { spiedList.add("one"); spiedList.add("two"); - Mockito.verify(spiedList).add("one"); - Mockito.verify(spiedList).add("two"); + verify(spiedList).add("one"); + verify(spiedList).add("two"); assertEquals(2, spiedList.size()); - Mockito.doReturn(100).when(spiedList).size(); + doReturn(100).when(spiedList).size(); assertEquals(100, spiedList.size()); } @Test - public void whenNotUseCaptorAnnotation_thenCorrect() { - final List mockList = Mockito.mock(List.class); + void whenNotUseCaptorAnnotation_thenCorrect() { + final List mockList = mock(List.class); final ArgumentCaptor arg = ArgumentCaptor.forClass(String.class); mockList.add("one"); - Mockito.verify(mockList).add(arg.capture()); + verify(mockList).add(arg.capture()); assertEquals("one", arg.getValue()); } @@ -100,9 +104,9 @@ public class MockitoAnnotationUnitTest { ArgumentCaptor argCaptor; @Test - public void whenUseCaptorAnnotation_thenTheSame() { + void whenUseCaptorAnnotation_thenTheSame() { mockedList.add("one"); - Mockito.verify(mockedList).add(argCaptor.capture()); + verify(mockedList).add(argCaptor.capture()); assertEquals("one", argCaptor.getValue()); } @@ -114,8 +118,8 @@ public class MockitoAnnotationUnitTest { private MyDictionary dic = new MyDictionary(); @Test - public void whenUseInjectMocksAnnotation_thenCorrect() { - Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning"); + void whenUseInjectMocksAnnotation_thenCorrect() { + when(wordMap.get("aWord")).thenReturn("aMeaning"); assertEquals("aMeaning", dic.getMeaning("aWord")); } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java index 88a9410101..512f538a58 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest.java @@ -6,16 +6,18 @@ import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; + import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; + public class MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest { @Rule public MockitoRule initRule = MockitoJUnit.rule(); - + @Mock private List mockedList; @@ -23,6 +25,6 @@ public class MockitoAnnotationsInitWithMockitoJUnitRuleUnitTest { public void whenUsingMockitoJUnitRule_thenMocksInitialized() { when(mockedList.size()).thenReturn(41); - assertThat(mockedList.size()).isEqualTo(41); + assertThat(mockedList).hasSize(41); } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsInjectIntoSpyUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsInjectIntoSpyUnitTest.java index 9d3a00f8b9..89a253c855 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsInjectIntoSpyUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsInjectIntoSpyUnitTest.java @@ -1,22 +1,28 @@ package com.baeldung.mockito; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; -import org.mockito.*; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.openMocks; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.util.Map; -import static org.junit.Assert.assertEquals; -@RunWith(MockitoJUnitRunner.class) -public class MockitoAnnotationsInjectIntoSpyUnitTest { +@ExtendWith(MockitoExtension.class) +class MockitoAnnotationsInjectIntoSpyUnitTest { - @Before + @BeforeEach public void init() { - MockitoAnnotations.openMocks(this); - spyDic = Mockito.spy(new MyDictionary(wordMap)); + openMocks(this); + spyDic = spy(new MyDictionary(wordMap)); } @Mock @@ -28,8 +34,8 @@ public class MockitoAnnotationsInjectIntoSpyUnitTest { private MyDictionary spyDic; @Test - public void whenUseInjectMocksAnnotation_thenCorrect() { - Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning"); + void whenUseInjectMocksAnnotation_thenCorrect() { + when(wordMap.get("aWord")).thenReturn("aMeaning"); assertEquals("aMeaning", spyDic.getMeaning("aWord")); } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsUninitializedUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsUninitializedUnitTest.java index ed50732183..10b0aa6626 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsUninitializedUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoAnnotationsUninitializedUnitTest.java @@ -1,18 +1,23 @@ package com.baeldung.mockito; -import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; import org.mockito.Mock; -import org.mockito.Mockito; import java.util.List; -public class MockitoAnnotationsUninitializedUnitTest { +class MockitoAnnotationsUninitializedUnitTest { @Mock List mockedList; - @Test(expected = NullPointerException.class) - public void whenMockitoAnnotationsUninitialized_thenNPEThrown() { - Mockito.when(mockedList.size()).thenReturn(1); + @Test + void whenMockitoAnnotationsUninitialized_thenNPEThrown() { + assertThrows(NullPointerException.class, () -> { + when(mockedList.size()).thenReturn(1); + }); } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoExceptionUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoExceptionUnitTest.java index 7ed4fbdf37..843edd8d0a 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoExceptionUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoExceptionUnitTest.java @@ -1,57 +1,71 @@ package com.baeldung.mockito; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import org.junit.Test; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; -public class MockitoExceptionUnitTest { +@ExtendWith(MockitoExtension.class) +class MockitoExceptionUnitTest { - @Test(expected = NullPointerException.class) - public void whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() { + @Test + void whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() { MyDictionary dictMock = mock(MyDictionary.class); when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class); + assertThrows(NullPointerException.class, () -> { + dictMock.getMeaning("word"); + }); - dictMock.getMeaning("word"); } - @Test(expected = IllegalStateException.class) - public void whenConfigVoidRetunMethodToThrowEx_thenExIsThrown() { + @Test + void whenConfigVoidRetunMethodToThrowEx_thenExIsThrown() { MyDictionary dictMock = mock(MyDictionary.class); doThrow(IllegalStateException.class).when(dictMock) .add(anyString(), anyString()); + assertThrows(IllegalStateException.class, () -> { + dictMock.add("word", "meaning"); + }); - dictMock.add("word", "meaning"); } - @Test(expected = NullPointerException.class) - public void whenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() { + @Test + void whenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() { MyDictionary dictMock = mock(MyDictionary.class); when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred")); + assertThrows(NullPointerException.class, () -> { + dictMock.getMeaning("word"); + }); - dictMock.getMeaning("word"); } - @Test(expected = IllegalStateException.class) - public void whenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() { + @Test + void whenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() { MyDictionary dictMock = mock(MyDictionary.class); doThrow(new IllegalStateException("Error occurred")).when(dictMock) .add(anyString(), anyString()); + assertThrows(IllegalStateException.class, () -> { + dictMock.add("word", "meaning"); + }); - dictMock.add("word", "meaning"); } // ===== - @Test(expected = NullPointerException.class) - public void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() { + @Test + void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() { MyDictionary dict = new MyDictionary(); MyDictionary spy = Mockito.spy(dict); - when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class); - spy.getMeaning("word"); + assertThrows(NullPointerException.class, () -> { + spy.getMeaning("word"); + }); } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoMockUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoMockUnitTest.java index 6b2bae16c3..6e9167f0d0 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoMockUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoMockUnitTest.java @@ -10,16 +10,16 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.MockSettings; import org.mockito.exceptions.verification.TooFewActualInvocations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -public class MockitoMockUnitTest { +class MockitoMockUnitTest { @Test - public void whenUsingSimpleMock_thenCorrect() { + void whenUsingSimpleMock_thenCorrect() { MyList listMock = mock(MyList.class); when(listMock.add(anyString())).thenReturn(false); boolean added = listMock.add(randomAlphabetic(6)); @@ -29,7 +29,7 @@ public class MockitoMockUnitTest { } @Test - public void whenUsingMockWithName_thenCorrect() { + void whenUsingMockWithName_thenCorrect() { MyList listMock = mock(MyList.class, "myMock"); when(listMock.add(anyString())).thenReturn(false); listMock.add(randomAlphabetic(6)); @@ -47,7 +47,7 @@ public class MockitoMockUnitTest { } @Test - public void whenUsingMockWithAnswer_thenCorrect() { + void whenUsingMockWithAnswer_thenCorrect() { MyList listMock = mock(MyList.class, new CustomAnswer()); boolean added = listMock.add(randomAlphabetic(6)); @@ -56,7 +56,7 @@ public class MockitoMockUnitTest { } @Test - public void whenUsingMockWithSettings_thenCorrect() { + void whenUsingMockWithSettings_thenCorrect() { MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer()); MyList listMock = mock(MyList.class, customSettings); boolean added = listMock.add(randomAlphabetic(6)); diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoVerifyExamplesUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoVerifyExamplesUnitTest.java index c3c5758950..a236fc7cfc 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoVerifyExamplesUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoVerifyExamplesUnitTest.java @@ -1,9 +1,11 @@ package com.baeldung.mockito; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.atMost; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -13,69 +15,71 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; -import org.mockito.Mockito; import org.mockito.exceptions.verification.NoInteractionsWanted; import com.google.common.collect.Lists; -public class MockitoVerifyExamplesUnitTest { +class MockitoVerifyExamplesUnitTest { // tests @Test - public final void givenInteractionWithMockOccurred_whenVerifyingInteraction_thenCorrect() { + final void givenInteractionWithMockOccurred_whenVerifyingInteraction_thenCorrect() { final List mockedList = mock(MyList.class); mockedList.size(); verify(mockedList).size(); } @Test - public final void givenOneInteractionWithMockOccurred_whenVerifyingNumberOfInteractions_thenCorrect() { + final void givenOneInteractionWithMockOccurred_whenVerifyingNumberOfInteractions_thenCorrect() { final List mockedList = mock(MyList.class); mockedList.size(); verify(mockedList, times(1)).size(); } @Test - public final void givenNoInteractionWithMockOccurred_whenVerifyingInteractions_thenCorrect() { + final void givenNoInteractionWithMockOccurred_whenVerifyingInteractions_thenCorrect() { final List mockedList = mock(MyList.class); verifyNoInteractions(mockedList); } @Test - public final void givenNoInteractionWithMethodOfMockOccurred_whenVerifyingInteractions_thenCorrect() { + final void givenNoInteractionWithMethodOfMockOccurred_whenVerifyingInteractions_thenCorrect() { final List mockedList = mock(MyList.class); verify(mockedList, times(0)).size(); } - @Test(expected = NoInteractionsWanted.class) - public final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() { + @Test + final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() { final List mockedList = mock(MyList.class); mockedList.size(); mockedList.clear(); verify(mockedList).size(); - verifyNoMoreInteractions(mockedList); + assertThrows(NoInteractionsWanted.class, () -> { + verifyNoMoreInteractions(mockedList); + }); + } @Test - public final void whenVerifyingOrderOfInteractions_thenCorrect() { + final void whenVerifyingOrderOfInteractions_thenCorrect() { final List mockedList = mock(MyList.class); mockedList.size(); mockedList.add("a parameter"); mockedList.clear(); - final InOrder inOrder = Mockito.inOrder(mockedList); + final InOrder inOrder = inOrder(mockedList); inOrder.verify(mockedList).size(); inOrder.verify(mockedList).add("a parameter"); inOrder.verify(mockedList).clear(); } @Test - public final void whenVerifyingAnInteractionHasNotOccurred_thenCorrect() { + final void whenVerifyingAnInteractionHasNotOccurred_thenCorrect() { final List mockedList = mock(MyList.class); mockedList.size(); @@ -83,7 +87,7 @@ public class MockitoVerifyExamplesUnitTest { } @Test - public final void whenVerifyingAnInteractionHasOccurredAtLeastOnce_thenCorrect() { + final void whenVerifyingAnInteractionHasOccurredAtLeastOnce_thenCorrect() { final List mockedList = mock(MyList.class); mockedList.clear(); mockedList.clear(); @@ -96,7 +100,7 @@ public class MockitoVerifyExamplesUnitTest { // with arguments @Test - public final void whenVerifyingAnInteractionWithExactArgument_thenCorrect() { + final void whenVerifyingAnInteractionWithExactArgument_thenCorrect() { final List mockedList = mock(MyList.class); mockedList.add("test"); @@ -104,7 +108,7 @@ public class MockitoVerifyExamplesUnitTest { } @Test - public final void whenVerifyingAnInteractionWithAnyArgument_thenCorrect() { + final void whenVerifyingAnInteractionWithAnyArgument_thenCorrect() { final List mockedList = mock(MyList.class); mockedList.add("test"); @@ -112,7 +116,7 @@ public class MockitoVerifyExamplesUnitTest { } @Test - public final void whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() { + final void whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() { final List mockedList = mock(MyList.class); mockedList.addAll(Lists.newArrayList("someElement")); diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoWhenThenExamplesUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoWhenThenExamplesUnitTest.java index d110fff00f..c570629ccd 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoWhenThenExamplesUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/MockitoWhenThenExamplesUnitTest.java @@ -2,21 +2,24 @@ package com.baeldung.mockito; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; -import org.junit.Test; -import org.mockito.Mockito; +import org.junit.jupiter.api.Test; -public class MockitoWhenThenExamplesUnitTest { + +class MockitoWhenThenExamplesUnitTest { @Test - public final void whenMockReturnBehaviorIsConfigured_thenBehaviorIsVerified() { - final MyList listMock = Mockito.mock(MyList.class); + final void whenMockReturnBehaviorIsConfigured_thenBehaviorIsVerified() { + final MyList listMock = mock(MyList.class); when(listMock.add(anyString())).thenReturn(false); final boolean added = listMock.add(randomAlphabetic(6)); @@ -24,67 +27,79 @@ public class MockitoWhenThenExamplesUnitTest { } @Test - public final void whenMockReturnBehaviorIsConfigured2_thenBehaviorIsVerified() { - final MyList listMock = Mockito.mock(MyList.class); + final void whenMockReturnBehaviorIsConfigured2_thenBehaviorIsVerified() { + final MyList listMock = mock(MyList.class); doReturn(false).when(listMock).add(anyString()); final boolean added = listMock.add(randomAlphabetic(6)); assertThat(added).isFalse(); } - @Test(expected = IllegalStateException.class) - public final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() { - final MyList listMock = Mockito.mock(MyList.class); + @Test + final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() { + final MyList listMock = mock(MyList.class); when(listMock.add(anyString())).thenThrow(IllegalStateException.class); - listMock.add(randomAlphabetic(6)); + assertThrows(IllegalStateException.class, () -> { + listMock.add(randomAlphabetic(6)); + }); + } @Test - public final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() { - final MyList listMock = Mockito.mock(MyList.class); + final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() { + final MyList listMock = mock(MyList.class); when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class); listMock.add(randomAlphabetic(6)); } - @Test(expected = NullPointerException.class) - public final void whenMethodHasNoReturnType_whenConfiguringBehaviorOfMethod_thenPossible() { - final MyList listMock = Mockito.mock(MyList.class); + @Test + final void whenMethodHasNoReturnType_whenConfiguringBehaviorOfMethod_thenPossible() { + final MyList listMock = mock(MyList.class); doThrow(NullPointerException.class).when(listMock).clear(); - listMock.clear(); + assertThrows(NullPointerException.class, () -> { + listMock.clear(); + }); + } - @Test(expected = IllegalStateException.class) - public final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() { - final MyList listMock = Mockito.mock(MyList.class); + @Test + final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() { + final MyList listMock = mock(MyList.class); when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class); - listMock.add(randomAlphabetic(6)); - listMock.add(randomAlphabetic(6)); + assertThrows(IllegalStateException.class, () -> { + listMock.add(randomAlphabetic(6)); + listMock.add(randomAlphabetic(6)); + }); + } - @Test(expected = NullPointerException.class) - public final void givenSpy_whenConfiguringBehaviorOfSpy_thenCorrectlyConfigured() { + @Test + final void givenSpy_whenConfiguringBehaviorOfSpy_thenCorrectlyConfigured() { final MyList instance = new MyList(); - final MyList spy = Mockito.spy(instance); + final MyList spy = spy(instance); doThrow(NullPointerException.class).when(spy).size(); - spy.size(); + assertThrows(NullPointerException.class, () -> { + spy.size(); + }); + } @Test - public final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() { - final MyList listMock = Mockito.mock(MyList.class); + final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() { + final MyList listMock = mock(MyList.class); when(listMock.size()).thenCallRealMethod(); assertThat(listMock).hasSize(1); } @Test - public final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenRealMethodIsCalled() { - final MyList listMock = Mockito.mock(MyList.class); + final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenRealMethodIsCalled() { + final MyList listMock = mock(MyList.class); doAnswer(invocation -> "Always the same").when(listMock).get(anyInt()); final String element = listMock.get(1); diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java index c757a8bfb9..36c26659a6 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java @@ -3,18 +3,20 @@ package com.baeldung.mockito.argumentcaptor; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) -public class EmailServiceUnitTest { +@ExtendWith(MockitoExtension.class) +class EmailServiceUnitTest { @Mock DeliveryPlatform platform; @@ -29,34 +31,34 @@ public class EmailServiceUnitTest { ArgumentCaptor credentialsCaptor; @Test - public void whenDoesNotSupportHtml_expectTextOnlyEmailFormat() { + void whenDoesNotSupportHtml_expectTextOnlyEmailFormat() { String to = "info@baeldung.com"; String subject = "Using ArgumentCaptor"; String body = "Hey, let'use ArgumentCaptor"; emailService.send(to, subject, body, false); - Mockito.verify(platform).deliver(emailCaptor.capture()); + verify(platform).deliver(emailCaptor.capture()); Email emailCaptorValue = emailCaptor.getValue(); assertThat(emailCaptorValue.getFormat()).isEqualTo(Format.TEXT_ONLY); } @Test - public void whenDoesSupportHtml_expectHTMLEmailFormat() { + void whenDoesSupportHtml_expectHTMLEmailFormat() { String to = "info@baeldung.com"; String subject = "Using ArgumentCaptor"; String body = "Hey, let'use ArgumentCaptor"; emailService.send(to, subject, body, true); - Mockito.verify(platform).deliver(emailCaptor.capture()); + verify(platform).deliver(emailCaptor.capture()); Email value = emailCaptor.getValue(); assertThat(value.getFormat()).isEqualTo(Format.HTML); } @Test - public void whenServiceRunning_expectUpResponse() { - Mockito.when(platform.getServiceStatus()).thenReturn("OK"); + void whenServiceRunning_expectUpResponse() { + when(platform.getServiceStatus()).thenReturn("OK"); ServiceStatus serviceStatus = emailService.checkServiceStatus(); @@ -64,8 +66,8 @@ public class EmailServiceUnitTest { } @Test - public void whenServiceNotRunning_expectDownResponse() { - Mockito.when(platform.getServiceStatus()).thenReturn("Error"); + void whenServiceNotRunning_expectDownResponse() { + when(platform.getServiceStatus()).thenReturn("Error"); ServiceStatus serviceStatus = emailService.checkServiceStatus(); @@ -73,26 +75,26 @@ public class EmailServiceUnitTest { } @Test - public void whenUsingArgumentMatcherForValidCredentials_expectTrue() { + void whenUsingArgumentMatcherForValidCredentials_expectTrue() { Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); - Mockito.when(platform.authenticate(Mockito.eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED); + when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED); assertTrue(emailService.authenticatedSuccessfully(credentials)); } @Test - public void whenUsingArgumentCaptorForValidCredentials_expectTrue() { + void whenUsingArgumentCaptorForValidCredentials_expectTrue() { Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); - Mockito.when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED); + when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED); assertTrue(emailService.authenticatedSuccessfully(credentials)); assertThat(credentialsCaptor.getValue()).isEqualTo(credentials); } @Test - public void whenNotAuthenticated_expectFalse() { + void whenNotAuthenticated_expectFalse() { Credentials credentials = new Credentials("baeldung", "incorrect_password", "incorrect_key"); - Mockito.when(platform.authenticate(Mockito.eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED); + when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED); assertFalse(emailService.authenticatedSuccessfully(credentials)); } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockedstatic/MockedStaticUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockedstatic/MockedStaticUnitTest.java index a212e6e3eb..309f066a87 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockedstatic/MockedStaticUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/mockedstatic/MockedStaticUnitTest.java @@ -2,9 +2,9 @@ package com.baeldung.mockito.mockedstatic; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; -import org.mockito.Mockito; import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.mockStatic; import java.util.Arrays; @@ -14,7 +14,7 @@ class MockedStaticUnitTest { void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() { assertThat(StaticUtils.name()).isEqualTo("Baeldung"); - try (MockedStatic utilities = Mockito.mockStatic(StaticUtils.class)) { + try (MockedStatic utilities = mockStatic(StaticUtils.class)) { utilities.when(StaticUtils::name).thenReturn("Eugen"); assertThat(StaticUtils.name()).isEqualTo("Eugen"); } @@ -26,7 +26,7 @@ class MockedStaticUnitTest { void givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() { assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5); - try (MockedStatic utilities = Mockito.mockStatic(StaticUtils.class)) { + try (MockedStatic utilities = mockStatic(StaticUtils.class)) { utilities.when(() -> StaticUtils.range(2, 6)) .thenReturn(Arrays.asList(10, 11, 12)); diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoMisusingMockOrSpyUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoMisusingMockOrSpyUnitTest.java index b3f470427a..e1023c5e57 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoMisusingMockOrSpyUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoMisusingMockOrSpyUnitTest.java @@ -2,29 +2,30 @@ package com.baeldung.mockito.spy; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; import java.util.ArrayList; import java.util.List; -import org.junit.Test; -import org.mockito.Mockito; +import org.junit.jupiter.api.Test; import org.mockito.exceptions.misusing.NotAMockException; -public class MockitoMisusingMockOrSpyUnitTest { +class MockitoMisusingMockOrSpyUnitTest { @Test - public void givenNotASpy_whenDoReturn_thenThrowNotAMock() { + void givenNotASpy_whenDoReturn_thenThrowNotAMock() { List list = new ArrayList(); - assertThatThrownBy(() -> Mockito.doReturn(100).when(list).size()) + assertThatThrownBy(() -> doReturn(100).when(list).size()) .isInstanceOf(NotAMockException.class) .hasMessageContaining("Argument passed to when() is not a mock!"); } @Test - public void givenASpy_whenDoReturn_thenNoError() { - final List spyList = Mockito.spy(new ArrayList<>()); + void givenASpy_whenDoReturn_thenNoError() { + final List spyList = spy(new ArrayList<>()); - assertThatNoException().isThrownBy(() -> Mockito.doReturn(100).when(spyList).size()); + assertThatNoException().isThrownBy(() -> doReturn(100).when(spyList).size()); } } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoSpyUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoSpyUnitTest.java index 28ca0c327b..caef0c3b4b 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoSpyUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/spy/MockitoSpyUnitTest.java @@ -1,30 +1,33 @@ package com.baeldung.mockito.spy; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; import java.util.ArrayList; import java.util.List; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class MockitoSpyUnitTest { @Test - public void whenSpyingOnList_thenCorrect() { + void whenSpyingOnList_thenCorrect() { final List list = new ArrayList(); - final List spyList = Mockito.spy(list); + final List spyList = spy(list); spyList.add("one"); spyList.add("two"); - Mockito.verify(spyList).add("one"); - Mockito.verify(spyList).add("two"); + verify(spyList).add("one"); + verify(spyList).add("two"); assertThat(spyList).hasSize(2); } @@ -33,43 +36,43 @@ public class MockitoSpyUnitTest { private List aSpyList = new ArrayList(); @Test - public void whenUsingTheSpyAnnotation_thenObjectIsSpied() { + void whenUsingTheSpyAnnotation_thenObjectIsSpied() { aSpyList.add("one"); aSpyList.add("two"); - Mockito.verify(aSpyList).add("one"); - Mockito.verify(aSpyList).add("two"); + verify(aSpyList).add("one"); + verify(aSpyList).add("two"); assertThat(aSpyList).hasSize(2); } @Test - public void whenStubASpy_thenStubbed() { + void whenStubASpy_thenStubbed() { final List list = new ArrayList(); - final List spyList = Mockito.spy(list); + final List spyList = spy(list); assertEquals(0, spyList.size()); - Mockito.doReturn(100).when(spyList).size(); + doReturn(100).when(spyList).size(); assertThat(spyList).hasSize(100); } @Test - public void whenCreateMock_thenCreated() { - final List mockedList = Mockito.mock(ArrayList.class); + void whenCreateMock_thenCreated() { + final List mockedList = mock(ArrayList.class); mockedList.add("one"); - Mockito.verify(mockedList).add("one"); + verify(mockedList).add("one"); assertThat(mockedList).hasSize(0); } @Test - public void whenCreateSpy_thenCreate() { - final List spyList = Mockito.spy(new ArrayList<>()); + void whenCreateSpy_thenCreate() { + final List spyList = spy(new ArrayList<>()); spyList.add("one"); - Mockito.verify(spyList).add("one"); + verify(spyList).add("one"); assertThat(spyList).hasSize(1); } diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java index dddfaa4c37..9b8a713a15 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/voidmethods/MockitoVoidMethodsUnitTest.java @@ -1,6 +1,8 @@ package com.baeldung.mockito.voidmethods; -import static org.junit.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.ArgumentMatchers.isNull; @@ -12,34 +14,36 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import com.baeldung.mockito.MyList; -@RunWith(MockitoJUnitRunner.class) -public class MockitoVoidMethodsUnitTest { +@ExtendWith(MockitoExtension.class) +class MockitoVoidMethodsUnitTest { @Test - public void whenAddCalledVerified() { + void whenAddCalledVerified() { MyList myList = mock(MyList.class); myList.add(0, ""); verify(myList, times(1)).add(0, ""); } - @Test(expected = Exception.class) - public void givenNull_addThrows() { + @Test + void givenNull_addThrows() { MyList myList = mock(MyList.class); - doThrow().when(myList).add(isA(Integer.class), isNull()); + assertThrows(Exception.class, () -> { + doThrow().when(myList).add(isA(Integer.class), isNull()); + }); myList.add(0, null); } @Test - public void whenAddCalledValueCaptured() { + void whenAddCalledValueCaptured() { MyList myList = mock(MyList.class); ArgumentCaptor valueCapture = ArgumentCaptor.forClass(String.class); doNothing().when(myList).add(any(Integer.class), valueCapture.capture()); @@ -49,7 +53,7 @@ public class MockitoVoidMethodsUnitTest { } @Test - public void whenAddCalledAnswered() { + void whenAddCalledAnswered() { MyList myList = mock(MyList.class); doAnswer(invocation -> { Object arg0 = invocation.getArgument(0); @@ -64,7 +68,7 @@ public class MockitoVoidMethodsUnitTest { } @Test - public void whenAddCalledRealMethodCalled() { + void whenAddCalledRealMethodCalled() { MyList myList = mock(MyList.class); doCallRealMethod().when(myList).add(any(Integer.class), any(String.class)); myList.add(1, "real");