diff --git a/.gitignore b/.gitignore index 7fe2778755..0e71421ee7 100644 --- a/.gitignore +++ b/.gitignore @@ -63,4 +63,6 @@ jmeter/src/main/resources/*-JMeter.csv **/tmp **/out-tsc **/nbproject/ -**/nb-configuration.xml \ No newline at end of file +**/nb-configuration.xml +core-scala/.cache-main +core-scala/.cache-tests diff --git a/spring-custom-aop/.gitignore b/algorithms-genetic/.gitignore similarity index 77% rename from spring-custom-aop/.gitignore rename to algorithms-genetic/.gitignore index 60be5b80aa..30b2b7442c 100644 --- a/spring-custom-aop/.gitignore +++ b/algorithms-genetic/.gitignore @@ -1,4 +1,4 @@ /target/ .settings/ .classpath -.project +.project \ No newline at end of file diff --git a/algorithms-genetic/README.md b/algorithms-genetic/README.md new file mode 100644 index 0000000000..0f68918fff --- /dev/null +++ b/algorithms-genetic/README.md @@ -0,0 +1,4 @@ +## Relevant articles: + +- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics) +- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization) \ No newline at end of file diff --git a/algorithms-genetic/pom.xml b/algorithms-genetic/pom.xml new file mode 100644 index 0000000000..2a10a81980 --- /dev/null +++ b/algorithms-genetic/pom.xml @@ -0,0 +1,64 @@ + + 4.0.0 + com.baeldung + algorithms-genetic + 0.0.1-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + commons-codec + commons-codec + ${commons-codec.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + io.jenetics + jenetics + ${io.jenetics.version} + + + org.assertj + assertj-core + ${org.assertj.core.version} + test + + + + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + + + + + + 1.16.12 + 3.6.1 + 3.7.0 + 3.9.0 + 1.11 + + + \ No newline at end of file diff --git a/algorithms/roundUpToHundred/.gitignore b/algorithms-genetic/roundUpToHundred/.gitignore similarity index 100% rename from algorithms/roundUpToHundred/.gitignore rename to algorithms-genetic/roundUpToHundred/.gitignore diff --git a/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundred.java b/algorithms-genetic/roundUpToHundred/src/com/java/src/RoundUpToHundred.java similarity index 95% rename from algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundred.java rename to algorithms-genetic/roundUpToHundred/src/com/java/src/RoundUpToHundred.java index f5024c227d..6c02a340d3 100644 --- a/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundred.java +++ b/algorithms-genetic/roundUpToHundred/src/com/java/src/RoundUpToHundred.java @@ -1,20 +1,20 @@ -package com.java.src; - -import java.util.Scanner; - -public class RoundUpToHundred { - - public static void main(String[] args) { - Scanner scanner = new Scanner(System.in); - double input = scanner.nextDouble(); - scanner.close(); - - RoundUpToHundred.round(input); - } - - static long round(double input) { - long i = (long) Math.ceil(input); - return ((i + 99) / 100) * 100; - }; - -} +package com.java.src; + +import java.util.Scanner; + +public class RoundUpToHundred { + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + double input = scanner.nextDouble(); + scanner.close(); + + RoundUpToHundred.round(input); + } + + static long round(double input) { + long i = (long) Math.ceil(input); + return ((i + 99) / 100) * 100; + }; + +} diff --git a/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java b/algorithms-genetic/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java similarity index 97% rename from algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java rename to algorithms-genetic/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java index f35a9a249f..cb541ad49c 100644 --- a/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java +++ b/algorithms-genetic/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java @@ -1,14 +1,14 @@ -package com.java.src; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class RoundUpToHundredTest { - @Test - public void givenInput_whenRound_thenRoundUpToTheNearestHundred() { - assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99)); - assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2)); - assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400)); - } -} +package com.java.src; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class RoundUpToHundredTest { + @Test + public void givenInput_whenRound_thenRoundUpToTheNearestHundred() { + assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99)); + assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2)); + assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400)); + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/RunAlgorithm.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/RunAlgorithm.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/RunAlgorithm.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/City.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/annealing/City.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/City.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/annealing/City.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/SimulatedAnnealing.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/annealing/SimulatedAnnealing.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/SimulatedAnnealing.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/annealing/SimulatedAnnealing.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/Travel.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/annealing/Travel.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/annealing/Travel.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/annealing/Travel.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/Ant.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/ant_colony/Ant.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/Ant.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/ant_colony/Ant.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/AntColonyOptimization.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/ant_colony/AntColonyOptimization.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/ant_colony/AntColonyOptimization.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/ant_colony/AntColonyOptimization.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/binary/Individual.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/binary/Population.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/binary/Population.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/binary/Population.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/binary/Population.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/binary/SimpleGeneticAlgorithm.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Dijkstra.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/dijkstra/Dijkstra.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Dijkstra.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/dijkstra/Dijkstra.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Graph.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/dijkstra/Graph.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Graph.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/dijkstra/Graph.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Node.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/dijkstra/Node.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/dijkstra/Node.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/dijkstra/Node.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/Knapsack.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/Knapsack.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/Knapsack.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/Knapsack.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackFF.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackFF.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackFF.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackFF.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackItem.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackItem.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackItem.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/KnapsackItem.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SimpleGeneticAlgorithm.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/SimpleGeneticAlgorithm.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SimpleGeneticAlgorithm.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/SimpleGeneticAlgorithm.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenProblem.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenProblem.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenProblem.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenProblem.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenRecord.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenRecord.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenRecord.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/SpringsteenRecord.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SubsetSum.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/SubsetSum.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/SubsetSum.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/SubsetSum.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/TravelingSalesman.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/TravelingSalesman.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/ga/jenetics/TravelingSalesman.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/ga/jenetics/TravelingSalesman.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/slope_one/InputData.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/slope_one/InputData.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/slope_one/InputData.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/slope_one/InputData.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/slope_one/Item.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/slope_one/Item.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/slope_one/Item.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/slope_one/Item.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/slope_one/SlopeOne.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/slope_one/User.java b/algorithms-genetic/src/main/java/com/baeldung/algorithms/slope_one/User.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/slope_one/User.java rename to algorithms-genetic/src/main/java/com/baeldung/algorithms/slope_one/User.java diff --git a/activejdbc/src/main/resources/logback.xml b/algorithms-genetic/src/main/resources/logback.xml similarity index 100% rename from activejdbc/src/main/resources/logback.xml rename to algorithms-genetic/src/main/resources/logback.xml diff --git a/algorithms/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java b/algorithms-genetic/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java rename to algorithms-genetic/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java b/algorithms-genetic/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java rename to algorithms-genetic/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java b/algorithms-genetic/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java rename to algorithms-genetic/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java b/algorithms-genetic/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java rename to algorithms-genetic/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java diff --git a/algorithms-miscellaneous-1/.gitignore b/algorithms-miscellaneous-1/.gitignore new file mode 100644 index 0000000000..30b2b7442c --- /dev/null +++ b/algorithms-miscellaneous-1/.gitignore @@ -0,0 +1,4 @@ +/target/ +.settings/ +.classpath +.project \ No newline at end of file diff --git a/algorithms-miscellaneous-1/README.md b/algorithms-miscellaneous-1/README.md new file mode 100644 index 0000000000..9efb2233bf --- /dev/null +++ b/algorithms-miscellaneous-1/README.md @@ -0,0 +1,12 @@ +## Relevant articles: + +- [Validating Input With Finite Automata in Java](http://www.baeldung.com/java-finite-automata) +- [Example of Hill Climbing Algorithm](http://www.baeldung.com/java-hill-climbing-algorithm) +- [Monte Carlo Tree Search for Tic-Tac-Toe Game](http://www.baeldung.com/java-monte-carlo-tree-search) +- [Binary Search Algorithm in Java](http://www.baeldung.com/java-binary-search) +- [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm) +- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance) +- [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element) +- [Multi-Swarm Optimization Algorithm in Java](http://www.baeldung.com/java-multi-swarm-algorithm) +- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms) +- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters) \ No newline at end of file diff --git a/algorithms-miscellaneous-1/pom.xml b/algorithms-miscellaneous-1/pom.xml new file mode 100644 index 0000000000..16749d452e --- /dev/null +++ b/algorithms-miscellaneous-1/pom.xml @@ -0,0 +1,78 @@ + + 4.0.0 + com.baeldung + algorithms-miscellaneous-1 + 0.0.1-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + commons-codec + commons-codec + ${commons-codec.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + org.assertj + assertj-core + ${org.assertj.core.version} + test + + + + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + + + + + + + + org.codehaus.mojo + cobertura-maven-plugin + 2.7 + + + + com/baeldung/algorithms/dijkstra/* + + + com/baeldung/algorithms/dijkstra/* + + + + + + + + + 1.16.12 + 3.6.1 + 3.9.0 + 1.11 + + + \ No newline at end of file diff --git a/algorithms-miscellaneous-1/roundUpToHundred/.gitignore b/algorithms-miscellaneous-1/roundUpToHundred/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/algorithms-miscellaneous-1/roundUpToHundred/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/algorithms-miscellaneous-1/roundUpToHundred/src/com/java/src/RoundUpToHundred.java b/algorithms-miscellaneous-1/roundUpToHundred/src/com/java/src/RoundUpToHundred.java new file mode 100644 index 0000000000..6c02a340d3 --- /dev/null +++ b/algorithms-miscellaneous-1/roundUpToHundred/src/com/java/src/RoundUpToHundred.java @@ -0,0 +1,20 @@ +package com.java.src; + +import java.util.Scanner; + +public class RoundUpToHundred { + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + double input = scanner.nextDouble(); + scanner.close(); + + RoundUpToHundred.round(input); + } + + static long round(double input) { + long i = (long) Math.ceil(input); + return ((i + 99) / 100) * 100; + }; + +} diff --git a/algorithms-miscellaneous-1/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java b/algorithms-miscellaneous-1/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java new file mode 100644 index 0000000000..cb541ad49c --- /dev/null +++ b/algorithms-miscellaneous-1/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java @@ -0,0 +1,14 @@ +package com.java.src; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class RoundUpToHundredTest { + @Test + public void givenInput_whenRound_thenRoundUpToTheNearestHundred() { + assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99)); + assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2)); + assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400)); + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/automata/FiniteStateMachine.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/automata/FiniteStateMachine.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/automata/FiniteStateMachine.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/automata/FiniteStateMachine.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/automata/RtFiniteStateMachine.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/automata/RtFiniteStateMachine.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/automata/RtFiniteStateMachine.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/automata/RtFiniteStateMachine.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/automata/RtState.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/automata/RtState.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/automata/RtState.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/automata/RtState.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/automata/RtTransition.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/automata/RtTransition.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/automata/RtTransition.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/automata/RtTransition.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/automata/State.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/automata/State.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/automata/State.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/automata/State.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/automata/Transition.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/automata/Transition.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/automata/Transition.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/automata/Transition.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/binarysearch/BinarySearch.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/binarysearch/BinarySearch.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/binarysearch/BinarySearch.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/binarysearch/BinarySearch.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/HillClimbing.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/hillclimbing/HillClimbing.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/HillClimbing.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/hillclimbing/HillClimbing.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/State.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/hillclimbing/State.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/hillclimbing/State.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/hillclimbing/State.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/kthlargest/FindKthLargest.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/kthlargest/FindKthLargest.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/kthlargest/FindKthLargest.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/kthlargest/FindKthLargest.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/MonteCarloTreeSearch.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/mcts/montecarlo/MonteCarloTreeSearch.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/MonteCarloTreeSearch.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/mcts/montecarlo/MonteCarloTreeSearch.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/UCT.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/mcts/montecarlo/UCT.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/UCT.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/mcts/montecarlo/UCT.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Position.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Position.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Position.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Position.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Tree.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/mcts/tree/Tree.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Tree.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/mcts/tree/Tree.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/MiddleElementLookup.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/middleelementlookup/MiddleElementLookup.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/MiddleElementLookup.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/middleelementlookup/MiddleElementLookup.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/Node.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/middleelementlookup/Node.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/Node.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/middleelementlookup/Node.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/minimax/GameOfBones.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/minimax/GameOfBones.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/minimax/GameOfBones.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/minimax/GameOfBones.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/minimax/MiniMax.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/minimax/MiniMax.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/minimax/MiniMax.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/minimax/MiniMax.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/minimax/Node.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/minimax/Node.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/minimax/Node.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/minimax/Node.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/minimax/Tree.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/minimax/Tree.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/minimax/Tree.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/minimax/Tree.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/multiswarm/Constants.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/multiswarm/Constants.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/multiswarm/Constants.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/multiswarm/Constants.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/multiswarm/FitnessFunction.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/multiswarm/FitnessFunction.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/multiswarm/FitnessFunction.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/multiswarm/FitnessFunction.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/multiswarm/Multiswarm.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/multiswarm/Multiswarm.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/multiswarm/Multiswarm.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/multiswarm/Multiswarm.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/multiswarm/Particle.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/multiswarm/Particle.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/multiswarm/Particle.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/multiswarm/Particle.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/multiswarm/Swarm.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/multiswarm/Swarm.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/multiswarm/Swarm.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/multiswarm/Swarm.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/string/search/StringSearchAlgorithms.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/search/StringSearchAlgorithms.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/string/search/StringSearchAlgorithms.java rename to algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/search/StringSearchAlgorithms.java diff --git a/algorithms/src/main/resources/logback.xml b/algorithms-miscellaneous-1/src/main/resources/logback.xml similarity index 100% rename from algorithms/src/main/resources/logback.xml rename to algorithms-miscellaneous-1/src/main/resources/logback.xml diff --git a/algorithms/src/main/resources/maze/maze1.txt b/algorithms-miscellaneous-1/src/main/resources/maze/maze1.txt similarity index 92% rename from algorithms/src/main/resources/maze/maze1.txt rename to algorithms-miscellaneous-1/src/main/resources/maze/maze1.txt index 0a6309d25b..8b48c325d2 100644 --- a/algorithms/src/main/resources/maze/maze1.txt +++ b/algorithms-miscellaneous-1/src/main/resources/maze/maze1.txt @@ -1,12 +1,12 @@ -S ######## -# # -# ### ## # -# # # # -# # # # # -# ## ##### -# # # -# # # # # -##### #### -# # E -# # # # +S ######## +# # +# ### ## # +# # # # +# # # # # +# ## ##### +# # # +# # # # # +##### #### +# # E +# # # # ########## \ No newline at end of file diff --git a/algorithms/src/main/resources/maze/maze2.txt b/algorithms-miscellaneous-1/src/main/resources/maze/maze2.txt similarity index 96% rename from algorithms/src/main/resources/maze/maze2.txt rename to algorithms-miscellaneous-1/src/main/resources/maze/maze2.txt index 22e6d0382a..df5b6bc66b 100644 --- a/algorithms/src/main/resources/maze/maze2.txt +++ b/algorithms-miscellaneous-1/src/main/resources/maze/maze2.txt @@ -1,22 +1,22 @@ -S ########################## -# # # # -# # #### ############### # -# # # # # # -# # #### # # ############### -# # # # # # # -# # # #### ### ########### # -# # # # # # -# ################## # -######### # # # # # -# # #### # ####### # # -# # ### ### # # # # # -# # ## # ##### # # -##### ####### # # # # # -# # ## ## #### # # -# ##### ####### # # -# # ############ -####### ######### # # -# # ######## # -# ####### ###### ## # E -# # # ## # +S ########################## +# # # # +# # #### ############### # +# # # # # # +# # #### # # ############### +# # # # # # # +# # # #### ### ########### # +# # # # # # +# ################## # +######### # # # # # +# # #### # ####### # # +# # ### ### # # # # # +# # ## # ##### # # +##### ####### # # # # # +# # ## ## #### # # +# ##### ####### # # +# # ############ +####### ######### # # +# # ######## # +# ####### ###### ## # E +# # # ## # ############################ \ No newline at end of file diff --git a/algorithms/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java rename to algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java rename to algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java rename to algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java rename to algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java rename to algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/kthlargest/FindKthLargestUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/kthlargest/FindKthLargestUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/kthlargest/FindKthLargestUnitTest.java rename to algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/kthlargest/FindKthLargestUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java rename to algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java rename to algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java rename to algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/multiswarm/LolFitnessFunction.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/multiswarm/LolFitnessFunction.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/multiswarm/LolFitnessFunction.java rename to algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/multiswarm/LolFitnessFunction.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/multiswarm/MultiswarmUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/multiswarm/MultiswarmUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/multiswarm/MultiswarmUnitTest.java rename to algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/multiswarm/MultiswarmUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java rename to algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/support/MayFailRule.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/support/MayFailRule.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/support/MayFailRule.java rename to algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/support/MayFailRule.java diff --git a/algorithms-miscellaneous-2/.gitignore b/algorithms-miscellaneous-2/.gitignore new file mode 100644 index 0000000000..30b2b7442c --- /dev/null +++ b/algorithms-miscellaneous-2/.gitignore @@ -0,0 +1,4 @@ +/target/ +.settings/ +.classpath +.project \ No newline at end of file diff --git a/algorithms/README.md b/algorithms-miscellaneous-2/README.md similarity index 54% rename from algorithms/README.md rename to algorithms-miscellaneous-2/README.md index b9a37a7bf2..2634fd6b56 100644 --- a/algorithms/README.md +++ b/algorithms-miscellaneous-2/README.md @@ -2,20 +2,8 @@ - [Dijkstra Algorithm in Java](http://www.baeldung.com/java-dijkstra) - [Introduction to Cobertura](http://www.baeldung.com/cobertura) -- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization) -- [Validating Input With Finite Automata in Java](http://www.baeldung.com/java-finite-automata) -- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics) -- [Example of Hill Climbing Algorithm](http://www.baeldung.com/java-hill-climbing-algorithm) -- [Monte Carlo Tree Search for Tic-Tac-Toe Game](http://www.baeldung.com/java-monte-carlo-tree-search) -- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms) - [Test a Linked List for Cyclicity](http://www.baeldung.com/java-linked-list-cyclicity) -- [Binary Search Algorithm in Java](http://www.baeldung.com/java-binary-search) -- [Bubble Sort in Java](http://www.baeldung.com/java-bubble-sort) - [Introduction to JGraphT](http://www.baeldung.com/jgrapht) -- [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm) -- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance) -- [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element) -- [Multi-Swarm Optimization Algorithm in Java](http://www.baeldung.com/java-multi-swarm-algorithm) - [A Maze Solver in Java](http://www.baeldung.com/java-solve-maze) - [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku) - [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words) @@ -27,10 +15,6 @@ - [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap) - [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points) - [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines) -- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters) - [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred) -- [Merge Sort in Java](https://www.baeldung.com/java-merge-sort) - [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage) -- [Quicksort Algorithm Implementation in Java](https://www.baeldung.com/java-quicksort) -- [Insertion Sort in Java](https://www.baeldung.com/java-insertion-sort) - [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings) diff --git a/algorithms/pom.xml b/algorithms-miscellaneous-2/pom.xml similarity index 89% rename from algorithms/pom.xml rename to algorithms-miscellaneous-2/pom.xml index db4a1c2eff..eeae544612 100644 --- a/algorithms/pom.xml +++ b/algorithms-miscellaneous-2/pom.xml @@ -1,96 +1,90 @@ - - 4.0.0 - com.baeldung - algorithms - 0.0.1-SNAPSHOT - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.apache.commons - commons-math3 - ${commons-math3.version} - - - commons-codec - commons-codec - ${commons-codec.version} - - - org.projectlombok - lombok - ${lombok.version} - provided - - - io.jenetics - jenetics - ${io.jenetics.version} - - - org.jgrapht - jgrapht-core - ${org.jgrapht.core.version} - - - pl.allegro.finance - tradukisto - ${tradukisto.version} - - - org.assertj - assertj-core - ${org.assertj.core.version} - test - - - - - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - - - - - - - - org.codehaus.mojo - cobertura-maven-plugin - 2.7 - - - - com/baeldung/algorithms/dijkstra/* - - - com/baeldung/algorithms/dijkstra/* - - - - - - - - - 1.16.12 - 3.6.1 - 1.0.1 - 3.7.0 - 1.0.1 - 3.9.0 - 1.11 - - + + 4.0.0 + com.baeldung + algorithms-miscellaneous-2 + 0.0.1-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + commons-codec + commons-codec + ${commons-codec.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + org.jgrapht + jgrapht-core + ${org.jgrapht.core.version} + + + pl.allegro.finance + tradukisto + ${tradukisto.version} + + + org.assertj + assertj-core + ${org.assertj.core.version} + test + + + + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + + + + + + + + org.codehaus.mojo + cobertura-maven-plugin + 2.7 + + + + com/baeldung/algorithms/dijkstra/* + + + com/baeldung/algorithms/dijkstra/* + + + + + + + + + 1.16.12 + 3.6.1 + 1.0.1 + 1.0.1 + 3.9.0 + 1.11 + + \ No newline at end of file diff --git a/algorithms-miscellaneous-2/roundUpToHundred/.gitignore b/algorithms-miscellaneous-2/roundUpToHundred/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/algorithms-miscellaneous-2/roundUpToHundred/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/algorithms-miscellaneous-2/roundUpToHundred/src/com/java/src/RoundUpToHundred.java b/algorithms-miscellaneous-2/roundUpToHundred/src/com/java/src/RoundUpToHundred.java new file mode 100644 index 0000000000..6c02a340d3 --- /dev/null +++ b/algorithms-miscellaneous-2/roundUpToHundred/src/com/java/src/RoundUpToHundred.java @@ -0,0 +1,20 @@ +package com.java.src; + +import java.util.Scanner; + +public class RoundUpToHundred { + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + double input = scanner.nextDouble(); + scanner.close(); + + RoundUpToHundred.round(input); + } + + static long round(double input) { + long i = (long) Math.ceil(input); + return ((i + 99) / 100) * 100; + }; + +} diff --git a/algorithms-miscellaneous-2/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java b/algorithms-miscellaneous-2/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java new file mode 100644 index 0000000000..cb541ad49c --- /dev/null +++ b/algorithms-miscellaneous-2/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java @@ -0,0 +1,14 @@ +package com.java.src; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class RoundUpToHundredTest { + @Test + public void givenInput_whenRound_thenRoundUpToTheNearestHundred() { + assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99)); + assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2)); + assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400)); + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceBase.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceBase.java similarity index 95% rename from algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceBase.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceBase.java index ec66621928..4df1de9994 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceBase.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceBase.java @@ -1,15 +1,15 @@ -package com.baeldung.algorithms.editdistance; - -import java.util.Arrays; - -public class EditDistanceBase { - - static int costOfSubstitution(char a, char b) { - return a == b ? 0 : 1; - } - - static int min(int... numbers) { - return Arrays.stream(numbers) - .min().orElse(Integer.MAX_VALUE); - } -} +package com.baeldung.algorithms.editdistance; + +import java.util.Arrays; + +public class EditDistanceBase { + + static int costOfSubstitution(char a, char b) { + return a == b ? 0 : 1; + } + + static int min(int... numbers) { + return Arrays.stream(numbers) + .min().orElse(Integer.MAX_VALUE); + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceDynamicProgramming.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceDynamicProgramming.java similarity index 96% rename from algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceDynamicProgramming.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceDynamicProgramming.java index 1f8824c4f4..10ce43bf5f 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceDynamicProgramming.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceDynamicProgramming.java @@ -1,26 +1,26 @@ -package com.baeldung.algorithms.editdistance; - -public class EditDistanceDynamicProgramming extends EditDistanceBase { - - static int calculate(String x, String y) { - int[][] dp = new int[x.length() + 1][y.length() + 1]; - - for (int i = 0; i <= x.length(); i++) { - for (int j = 0; j <= y.length(); j++) { - if (i == 0) - dp[i][j] = j; - - else if (j == 0) - dp[i][j] = i; - - else { - dp[i][j] = min(dp[i - 1][j - 1] - + costOfSubstitution(x.charAt(i - 1), y.charAt(j - 1)), - dp[i - 1][j] + 1, dp[i][j - 1] + 1); - } - } - } - - return dp[x.length()][y.length()]; - } -} +package com.baeldung.algorithms.editdistance; + +public class EditDistanceDynamicProgramming extends EditDistanceBase { + + static int calculate(String x, String y) { + int[][] dp = new int[x.length() + 1][y.length() + 1]; + + for (int i = 0; i <= x.length(); i++) { + for (int j = 0; j <= y.length(); j++) { + if (i == 0) + dp[i][j] = j; + + else if (j == 0) + dp[i][j] = i; + + else { + dp[i][j] = min(dp[i - 1][j - 1] + + costOfSubstitution(x.charAt(i - 1), y.charAt(j - 1)), + dp[i - 1][j] + 1, dp[i][j - 1] + 1); + } + } + } + + return dp[x.length()][y.length()]; + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceRecursive.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceRecursive.java similarity index 96% rename from algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceRecursive.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceRecursive.java index 8ed48dc554..fc907c45f8 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceRecursive.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/editdistance/EditDistanceRecursive.java @@ -1,21 +1,21 @@ -package com.baeldung.algorithms.editdistance; - -public class EditDistanceRecursive extends EditDistanceBase { - - static int calculate(String x, String y) { - - if (x.isEmpty()) { - return y.length(); - } - - if (y.isEmpty()) { - return x.length(); - } - - int substitution = calculate(x.substring(1), y.substring(1)) + costOfSubstitution(x.charAt(0), y.charAt(0)); - int insertion = calculate(x, y.substring(1)) + 1; - int deletion = calculate(x.substring(1), y) + 1; - - return min(substitution, insertion, deletion); - } -} +package com.baeldung.algorithms.editdistance; + +public class EditDistanceRecursive extends EditDistanceBase { + + static int calculate(String x, String y) { + + if (x.isEmpty()) { + return y.length(); + } + + if (y.isEmpty()) { + return x.length(); + } + + int substitution = calculate(x.substring(1), y.substring(1)) + costOfSubstitution(x.charAt(0), y.charAt(0)); + int insertion = calculate(x, y.substring(1)) + 1; + int deletion = calculate(x.substring(1), y) + 1; + + return min(substitution, insertion, deletion); + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForce.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForce.java similarity index 96% rename from algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForce.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForce.java index 1df425ad2e..907bd9042d 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForce.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForce.java @@ -1,38 +1,38 @@ -package com.baeldung.algorithms.linkedlist; - -public class CycleDetectionBruteForce { - - public static CycleDetectionResult detectCycle(Node head) { - if (head == null) { - return new CycleDetectionResult<>(false, null); - } - - Node it1 = head; - int nodesTraversedByOuter = 0; - while (it1 != null && it1.next != null) { - it1 = it1.next; - nodesTraversedByOuter++; - - int x = nodesTraversedByOuter; - Node it2 = head; - int noOfTimesCurrentNodeVisited = 0; - - while (x > 0) { - it2 = it2.next; - - if (it2 == it1) { - noOfTimesCurrentNodeVisited++; - } - - if (noOfTimesCurrentNodeVisited == 2) { - return new CycleDetectionResult<>(true, it1); - } - - x--; - } - } - - return new CycleDetectionResult<>(false, null); - } - -} +package com.baeldung.algorithms.linkedlist; + +public class CycleDetectionBruteForce { + + public static CycleDetectionResult detectCycle(Node head) { + if (head == null) { + return new CycleDetectionResult<>(false, null); + } + + Node it1 = head; + int nodesTraversedByOuter = 0; + while (it1 != null && it1.next != null) { + it1 = it1.next; + nodesTraversedByOuter++; + + int x = nodesTraversedByOuter; + Node it2 = head; + int noOfTimesCurrentNodeVisited = 0; + + while (x > 0) { + it2 = it2.next; + + if (it2 == it1) { + noOfTimesCurrentNodeVisited++; + } + + if (noOfTimesCurrentNodeVisited == 2) { + return new CycleDetectionResult<>(true, it1); + } + + x--; + } + } + + return new CycleDetectionResult<>(false, null); + } + +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIterators.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIterators.java similarity index 96% rename from algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIterators.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIterators.java index ab088de44a..2817f6f783 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIterators.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIterators.java @@ -1,25 +1,25 @@ -package com.baeldung.algorithms.linkedlist; - -public class CycleDetectionByFastAndSlowIterators { - - public static CycleDetectionResult detectCycle(Node head) { - if (head == null) { - return new CycleDetectionResult<>(false, null); - } - - Node slow = head; - Node fast = head; - - while (fast != null && fast.next != null) { - slow = slow.next; - fast = fast.next.next; - - if (slow == fast) { - return new CycleDetectionResult<>(true, fast); - } - } - - return new CycleDetectionResult<>(false, null); - } - -} +package com.baeldung.algorithms.linkedlist; + +public class CycleDetectionByFastAndSlowIterators { + + public static CycleDetectionResult detectCycle(Node head) { + if (head == null) { + return new CycleDetectionResult<>(false, null); + } + + Node slow = head; + Node fast = head; + + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + + if (slow == fast) { + return new CycleDetectionResult<>(true, fast); + } + } + + return new CycleDetectionResult<>(false, null); + } + +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashing.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashing.java similarity index 96% rename from algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashing.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashing.java index 90d5ecd711..fba4cad2e6 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashing.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashing.java @@ -1,27 +1,27 @@ -package com.baeldung.algorithms.linkedlist; - -import java.util.HashSet; -import java.util.Set; - -public class CycleDetectionByHashing { - - public static CycleDetectionResult detectCycle(Node head) { - if (head == null) { - return new CycleDetectionResult<>(false, null); - } - - Set> set = new HashSet<>(); - Node node = head; - - while (node != null) { - if (set.contains(node)) { - return new CycleDetectionResult<>(true, node); - } - set.add(node); - node = node.next; - } - - return new CycleDetectionResult<>(false, null); - } - -} +package com.baeldung.algorithms.linkedlist; + +import java.util.HashSet; +import java.util.Set; + +public class CycleDetectionByHashing { + + public static CycleDetectionResult detectCycle(Node head) { + if (head == null) { + return new CycleDetectionResult<>(false, null); + } + + Set> set = new HashSet<>(); + Node node = head; + + while (node != null) { + if (set.contains(node)) { + return new CycleDetectionResult<>(true, node); + } + set.add(node); + node = node.next; + } + + return new CycleDetectionResult<>(false, null); + } + +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionResult.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionResult.java similarity index 96% rename from algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionResult.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionResult.java index e7556311b3..4e258ec2ef 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionResult.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleDetectionResult.java @@ -1,12 +1,12 @@ -package com.baeldung.algorithms.linkedlist; - -public class CycleDetectionResult { - boolean cycleExists; - Node node; - - public CycleDetectionResult(boolean cycleExists, Node node) { - super(); - this.cycleExists = cycleExists; - this.node = node; - } -} +package com.baeldung.algorithms.linkedlist; + +public class CycleDetectionResult { + boolean cycleExists; + Node node; + + public CycleDetectionResult(boolean cycleExists, Node node) { + super(); + this.cycleExists = cycleExists; + this.node = node; + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForce.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForce.java similarity index 96% rename from algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForce.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForce.java index a2bfaee9a1..216ebcdde3 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForce.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForce.java @@ -1,56 +1,56 @@ -package com.baeldung.algorithms.linkedlist; - -public class CycleRemovalBruteForce { - - public static boolean detectAndRemoveCycle(Node head) { - CycleDetectionResult result = CycleDetectionByFastAndSlowIterators.detectCycle(head); - - if (result.cycleExists) { - removeCycle(result.node, head); - } - - return result.cycleExists; - } - - /** - * @param loopNodeParam - reference to the node where Flyods cycle - * finding algorithm ends, i.e. the fast and the slow iterators - * meet. - * @param head - reference to the head of the list - */ - private static void removeCycle(Node loopNodeParam, Node head) { - Node it = head; - - while (it != null) { - if (isNodeReachableFromLoopNode(it, loopNodeParam)) { - Node loopStart = it; - findEndNodeAndBreakCycle(loopStart); - break; - } - it = it.next; - } - } - - private static boolean isNodeReachableFromLoopNode(Node it, Node loopNodeParam) { - Node loopNode = loopNodeParam; - - do { - if (it == loopNode) { - return true; - } - loopNode = loopNode.next; - } while (loopNode.next != loopNodeParam); - - return false; - } - - private static void findEndNodeAndBreakCycle(Node loopStartParam) { - Node loopStart = loopStartParam; - - while (loopStart.next != loopStartParam) { - loopStart = loopStart.next; - } - - loopStart.next = null; - } -} +package com.baeldung.algorithms.linkedlist; + +public class CycleRemovalBruteForce { + + public static boolean detectAndRemoveCycle(Node head) { + CycleDetectionResult result = CycleDetectionByFastAndSlowIterators.detectCycle(head); + + if (result.cycleExists) { + removeCycle(result.node, head); + } + + return result.cycleExists; + } + + /** + * @param loopNodeParam - reference to the node where Flyods cycle + * finding algorithm ends, i.e. the fast and the slow iterators + * meet. + * @param head - reference to the head of the list + */ + private static void removeCycle(Node loopNodeParam, Node head) { + Node it = head; + + while (it != null) { + if (isNodeReachableFromLoopNode(it, loopNodeParam)) { + Node loopStart = it; + findEndNodeAndBreakCycle(loopStart); + break; + } + it = it.next; + } + } + + private static boolean isNodeReachableFromLoopNode(Node it, Node loopNodeParam) { + Node loopNode = loopNodeParam; + + do { + if (it == loopNode) { + return true; + } + loopNode = loopNode.next; + } while (loopNode.next != loopNodeParam); + + return false; + } + + private static void findEndNodeAndBreakCycle(Node loopStartParam) { + Node loopStart = loopStartParam; + + while (loopStart.next != loopStartParam) { + loopStart = loopStart.next; + } + + loopStart.next = null; + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodes.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodes.java similarity index 96% rename from algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodes.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodes.java index d8db37fc4c..f961feb97d 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodes.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodes.java @@ -1,44 +1,44 @@ -package com.baeldung.algorithms.linkedlist; - -public class CycleRemovalByCountingLoopNodes { - - public static boolean detectAndRemoveCycle(Node head) { - CycleDetectionResult result = CycleDetectionByFastAndSlowIterators.detectCycle(head); - - if (result.cycleExists) { - removeCycle(result.node, head); - } - - return result.cycleExists; - } - - private static void removeCycle(Node loopNodeParam, Node head) { - int cycleLength = calculateCycleLength(loopNodeParam); - Node cycleLengthAdvancedIterator = head; - Node it = head; - - for (int i = 0; i < cycleLength; i++) { - cycleLengthAdvancedIterator = cycleLengthAdvancedIterator.next; - } - - while (it.next != cycleLengthAdvancedIterator.next) { - it = it.next; - cycleLengthAdvancedIterator = cycleLengthAdvancedIterator.next; - } - - cycleLengthAdvancedIterator.next = null; - } - - private static int calculateCycleLength(Node loopNodeParam) { - Node loopNode = loopNodeParam; - int length = 1; - - while (loopNode.next != loopNodeParam) { - length++; - loopNode = loopNode.next; - } - - return length; - } - -} +package com.baeldung.algorithms.linkedlist; + +public class CycleRemovalByCountingLoopNodes { + + public static boolean detectAndRemoveCycle(Node head) { + CycleDetectionResult result = CycleDetectionByFastAndSlowIterators.detectCycle(head); + + if (result.cycleExists) { + removeCycle(result.node, head); + } + + return result.cycleExists; + } + + private static void removeCycle(Node loopNodeParam, Node head) { + int cycleLength = calculateCycleLength(loopNodeParam); + Node cycleLengthAdvancedIterator = head; + Node it = head; + + for (int i = 0; i < cycleLength; i++) { + cycleLengthAdvancedIterator = cycleLengthAdvancedIterator.next; + } + + while (it.next != cycleLengthAdvancedIterator.next) { + it = it.next; + cycleLengthAdvancedIterator = cycleLengthAdvancedIterator.next; + } + + cycleLengthAdvancedIterator.next = null; + } + + private static int calculateCycleLength(Node loopNodeParam) { + Node loopNode = loopNodeParam; + int length = 1; + + while (loopNode.next != loopNodeParam) { + length++; + loopNode = loopNode.next; + } + + return length; + } + +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodes.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodes.java similarity index 96% rename from algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodes.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodes.java index b979f7f677..1e41c832db 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodes.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodes.java @@ -1,27 +1,27 @@ -package com.baeldung.algorithms.linkedlist; - -public class CycleRemovalWithoutCountingLoopNodes { - - public static boolean detectAndRemoveCycle(Node head) { - CycleDetectionResult result = CycleDetectionByFastAndSlowIterators.detectCycle(head); - - if (result.cycleExists) { - removeCycle(result.node, head); - } - - return result.cycleExists; - } - - private static void removeCycle(Node meetingPointParam, Node head) { - Node loopNode = meetingPointParam; - Node it = head; - - while (loopNode.next != it.next) { - it = it.next; - loopNode = loopNode.next; - } - - loopNode.next = null; - } - -} +package com.baeldung.algorithms.linkedlist; + +public class CycleRemovalWithoutCountingLoopNodes { + + public static boolean detectAndRemoveCycle(Node head) { + CycleDetectionResult result = CycleDetectionByFastAndSlowIterators.detectCycle(head); + + if (result.cycleExists) { + removeCycle(result.node, head); + } + + return result.cycleExists; + } + + private static void removeCycle(Node meetingPointParam, Node head) { + Node loopNode = meetingPointParam; + Node it = head; + + while (loopNode.next != it.next) { + it = it.next; + loopNode = loopNode.next; + } + + loopNode.next = null; + } + +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/Node.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/Node.java similarity index 95% rename from algorithms/src/main/java/com/baeldung/algorithms/linkedlist/Node.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/Node.java index 4add22c77d..9573bcd981 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/linkedlist/Node.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/linkedlist/Node.java @@ -1,38 +1,38 @@ -package com.baeldung.algorithms.linkedlist; - -public class Node { - T data; - Node next; - - public static Node createNewNode(T data, Node next) { - Node node = new Node(); - node.data = data; - node.next = next; - return node; - } - - public static void traverseList(Node root) { - if (root == null) { - return; - } - - Node node = root; - while (node != null) { - System.out.println(node.data); - node = node.next; - } - } - - public static Node getTail(Node root) { - if (root == null) { - return null; - } - - Node node = root; - while (node.next != null) { - node = node.next; - } - return node; - } - +package com.baeldung.algorithms.linkedlist; + +public class Node { + T data; + Node next; + + public static Node createNewNode(T data, Node next) { + Node node = new Node(); + node.data = data; + node.next = next; + return node; + } + + public static void traverseList(Node root) { + if (root == null) { + return; + } + + Node node = root; + while (node != null) { + System.out.println(node.data); + node = node.next; + } + } + + public static Node getTail(Node root) { + if (root == null) { + return null; + } + + Node node = root; + while (node.next != null) { + node = node.next; + } + return node; + } + } \ No newline at end of file diff --git a/algorithms/src/main/java/com/baeldung/algorithms/maze/solver/BFSMazeSolver.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/BFSMazeSolver.java similarity index 96% rename from algorithms/src/main/java/com/baeldung/algorithms/maze/solver/BFSMazeSolver.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/BFSMazeSolver.java index 08972251b8..0e3101925c 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/maze/solver/BFSMazeSolver.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/BFSMazeSolver.java @@ -1,52 +1,52 @@ -package com.baeldung.algorithms.maze.solver; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -public class BFSMazeSolver { - private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; - - public List solve(Maze maze) { - LinkedList nextToVisit = new LinkedList<>(); - Coordinate start = maze.getEntry(); - nextToVisit.add(start); - - while (!nextToVisit.isEmpty()) { - Coordinate cur = nextToVisit.remove(); - - if (!maze.isValidLocation(cur.getX(), cur.getY()) || maze.isExplored(cur.getX(), cur.getY())) { - continue; - } - - if (maze.isWall(cur.getX(), cur.getY())) { - maze.setVisited(cur.getX(), cur.getY(), true); - continue; - } - - if (maze.isExit(cur.getX(), cur.getY())) { - return backtrackPath(cur); - } - - for (int[] direction : DIRECTIONS) { - Coordinate coordinate = new Coordinate(cur.getX() + direction[0], cur.getY() + direction[1], cur); - nextToVisit.add(coordinate); - maze.setVisited(cur.getX(), cur.getY(), true); - } - } - return Collections.emptyList(); - } - - private List backtrackPath(Coordinate cur) { - List path = new ArrayList<>(); - Coordinate iter = cur; - - while (iter != null) { - path.add(iter); - iter = iter.parent; - } - - return path; - } -} +package com.baeldung.algorithms.maze.solver; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +public class BFSMazeSolver { + private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; + + public List solve(Maze maze) { + LinkedList nextToVisit = new LinkedList<>(); + Coordinate start = maze.getEntry(); + nextToVisit.add(start); + + while (!nextToVisit.isEmpty()) { + Coordinate cur = nextToVisit.remove(); + + if (!maze.isValidLocation(cur.getX(), cur.getY()) || maze.isExplored(cur.getX(), cur.getY())) { + continue; + } + + if (maze.isWall(cur.getX(), cur.getY())) { + maze.setVisited(cur.getX(), cur.getY(), true); + continue; + } + + if (maze.isExit(cur.getX(), cur.getY())) { + return backtrackPath(cur); + } + + for (int[] direction : DIRECTIONS) { + Coordinate coordinate = new Coordinate(cur.getX() + direction[0], cur.getY() + direction[1], cur); + nextToVisit.add(coordinate); + maze.setVisited(cur.getX(), cur.getY(), true); + } + } + return Collections.emptyList(); + } + + private List backtrackPath(Coordinate cur) { + List path = new ArrayList<>(); + Coordinate iter = cur; + + while (iter != null) { + path.add(iter); + iter = iter.parent; + } + + return path; + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/maze/solver/Coordinate.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/Coordinate.java similarity index 94% rename from algorithms/src/main/java/com/baeldung/algorithms/maze/solver/Coordinate.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/Coordinate.java index 09b2ced5e6..8202c89076 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/maze/solver/Coordinate.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/Coordinate.java @@ -1,31 +1,31 @@ -package com.baeldung.algorithms.maze.solver; - -public class Coordinate { - int x; - int y; - Coordinate parent; - - public Coordinate(int x, int y) { - this.x = x; - this.y = y; - this.parent = null; - } - - public Coordinate(int x, int y, Coordinate parent) { - this.x = x; - this.y = y; - this.parent = parent; - } - - int getX() { - return x; - } - - int getY() { - return y; - } - - Coordinate getParent() { - return parent; - } -} +package com.baeldung.algorithms.maze.solver; + +public class Coordinate { + int x; + int y; + Coordinate parent; + + public Coordinate(int x, int y) { + this.x = x; + this.y = y; + this.parent = null; + } + + public Coordinate(int x, int y, Coordinate parent) { + this.x = x; + this.y = y; + this.parent = parent; + } + + int getX() { + return x; + } + + int getY() { + return y; + } + + Coordinate getParent() { + return parent; + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/maze/solver/DFSMazeSolver.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/DFSMazeSolver.java similarity index 96% rename from algorithms/src/main/java/com/baeldung/algorithms/maze/solver/DFSMazeSolver.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/DFSMazeSolver.java index f9640066b9..ee821631db 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/maze/solver/DFSMazeSolver.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/DFSMazeSolver.java @@ -1,48 +1,48 @@ -package com.baeldung.algorithms.maze.solver; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -public class DFSMazeSolver { - private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; - - public List solve(Maze maze) { - List path = new ArrayList<>(); - if (explore(maze, maze.getEntry() - .getX(), - maze.getEntry() - .getY(), - path)) { - return path; - } - return Collections.emptyList(); - } - - private boolean explore(Maze maze, int row, int col, List path) { - if (!maze.isValidLocation(row, col) || maze.isWall(row, col) || maze.isExplored(row, col)) { - return false; - } - - path.add(new Coordinate(row, col)); - maze.setVisited(row, col, true); - - if (maze.isExit(row, col)) { - return true; - } - - for (int[] direction : DIRECTIONS) { - Coordinate coordinate = getNextCoordinate(row, col, direction[0], direction[1]); - if (explore(maze, coordinate.getX(), coordinate.getY(), path)) { - return true; - } - } - - path.remove(path.size() - 1); - return false; - } - - private Coordinate getNextCoordinate(int row, int col, int i, int j) { - return new Coordinate(row + i, col + j); - } -} +package com.baeldung.algorithms.maze.solver; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class DFSMazeSolver { + private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; + + public List solve(Maze maze) { + List path = new ArrayList<>(); + if (explore(maze, maze.getEntry() + .getX(), + maze.getEntry() + .getY(), + path)) { + return path; + } + return Collections.emptyList(); + } + + private boolean explore(Maze maze, int row, int col, List path) { + if (!maze.isValidLocation(row, col) || maze.isWall(row, col) || maze.isExplored(row, col)) { + return false; + } + + path.add(new Coordinate(row, col)); + maze.setVisited(row, col, true); + + if (maze.isExit(row, col)) { + return true; + } + + for (int[] direction : DIRECTIONS) { + Coordinate coordinate = getNextCoordinate(row, col, direction[0], direction[1]); + if (explore(maze, coordinate.getX(), coordinate.getY(), path)) { + return true; + } + } + + path.remove(path.size() - 1); + return false; + } + + private Coordinate getNextCoordinate(int row, int col, int i, int j) { + return new Coordinate(row + i, col + j); + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/maze/solver/Maze.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/Maze.java similarity index 96% rename from algorithms/src/main/java/com/baeldung/algorithms/maze/solver/Maze.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/Maze.java index 8aaa44d9b1..d0a0ed65d9 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/maze/solver/Maze.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/Maze.java @@ -1,141 +1,141 @@ -package com.baeldung.algorithms.maze.solver; - -import java.io.File; -import java.io.FileNotFoundException; -import java.util.Arrays; -import java.util.List; -import java.util.Scanner; - -public class Maze { - private static final int ROAD = 0; - private static final int WALL = 1; - private static final int START = 2; - private static final int EXIT = 3; - private static final int PATH = 4; - - private int[][] maze; - private boolean[][] visited; - private Coordinate start; - private Coordinate end; - - public Maze(File maze) throws FileNotFoundException { - String fileText = ""; - try (Scanner input = new Scanner(maze)) { - while (input.hasNextLine()) { - fileText += input.nextLine() + "\n"; - } - } - initializeMaze(fileText); - } - - private void initializeMaze(String text) { - if (text == null || (text = text.trim()).length() == 0) { - throw new IllegalArgumentException("empty lines data"); - } - - String[] lines = text.split("[\r]?\n"); - maze = new int[lines.length][lines[0].length()]; - visited = new boolean[lines.length][lines[0].length()]; - - for (int row = 0; row < getHeight(); row++) { - if (lines[row].length() != getWidth()) { - throw new IllegalArgumentException("line " + (row + 1) + " wrong length (was " + lines[row].length() + " but should be " + getWidth() + ")"); - } - - for (int col = 0; col < getWidth(); col++) { - if (lines[row].charAt(col) == '#') - maze[row][col] = WALL; - else if (lines[row].charAt(col) == 'S') { - maze[row][col] = START; - start = new Coordinate(row, col); - } else if (lines[row].charAt(col) == 'E') { - maze[row][col] = EXIT; - end = new Coordinate(row, col); - } else - maze[row][col] = ROAD; - } - } - } - - public int getHeight() { - return maze.length; - } - - public int getWidth() { - return maze[0].length; - } - - public Coordinate getEntry() { - return start; - } - - public Coordinate getExit() { - return end; - } - - public boolean isExit(int x, int y) { - return x == end.getX() && y == end.getY(); - } - - public boolean isStart(int x, int y) { - return x == start.getX() && y == start.getY(); - } - - public boolean isExplored(int row, int col) { - return visited[row][col]; - } - - public boolean isWall(int row, int col) { - return maze[row][col] == WALL; - } - - public void setVisited(int row, int col, boolean value) { - visited[row][col] = value; - } - - public boolean isValidLocation(int row, int col) { - if (row < 0 || row >= getHeight() || col < 0 || col >= getWidth()) { - return false; - } - return true; - } - - public void printPath(List path) { - int[][] tempMaze = Arrays.stream(maze) - .map(int[]::clone) - .toArray(int[][]::new); - for (Coordinate coordinate : path) { - if (isStart(coordinate.getX(), coordinate.getY()) || isExit(coordinate.getX(), coordinate.getY())) { - continue; - } - tempMaze[coordinate.getX()][coordinate.getY()] = PATH; - } - System.out.println(toString(tempMaze)); - } - - public String toString(int[][] maze) { - StringBuilder result = new StringBuilder(getWidth() * (getHeight() + 1)); - for (int row = 0; row < getHeight(); row++) { - for (int col = 0; col < getWidth(); col++) { - if (maze[row][col] == ROAD) { - result.append(' '); - } else if (maze[row][col] == WALL) { - result.append('#'); - } else if (maze[row][col] == START) { - result.append('S'); - } else if (maze[row][col] == EXIT) { - result.append('E'); - } else { - result.append('.'); - } - } - result.append('\n'); - } - return result.toString(); - } - - public void reset() { - for (int i = 0; i < visited.length; i++) - Arrays.fill(visited[i], false); - } -} +package com.baeldung.algorithms.maze.solver; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.Arrays; +import java.util.List; +import java.util.Scanner; + +public class Maze { + private static final int ROAD = 0; + private static final int WALL = 1; + private static final int START = 2; + private static final int EXIT = 3; + private static final int PATH = 4; + + private int[][] maze; + private boolean[][] visited; + private Coordinate start; + private Coordinate end; + + public Maze(File maze) throws FileNotFoundException { + String fileText = ""; + try (Scanner input = new Scanner(maze)) { + while (input.hasNextLine()) { + fileText += input.nextLine() + "\n"; + } + } + initializeMaze(fileText); + } + + private void initializeMaze(String text) { + if (text == null || (text = text.trim()).length() == 0) { + throw new IllegalArgumentException("empty lines data"); + } + + String[] lines = text.split("[\r]?\n"); + maze = new int[lines.length][lines[0].length()]; + visited = new boolean[lines.length][lines[0].length()]; + + for (int row = 0; row < getHeight(); row++) { + if (lines[row].length() != getWidth()) { + throw new IllegalArgumentException("line " + (row + 1) + " wrong length (was " + lines[row].length() + " but should be " + getWidth() + ")"); + } + + for (int col = 0; col < getWidth(); col++) { + if (lines[row].charAt(col) == '#') + maze[row][col] = WALL; + else if (lines[row].charAt(col) == 'S') { + maze[row][col] = START; + start = new Coordinate(row, col); + } else if (lines[row].charAt(col) == 'E') { + maze[row][col] = EXIT; + end = new Coordinate(row, col); + } else + maze[row][col] = ROAD; + } + } + } + + public int getHeight() { + return maze.length; + } + + public int getWidth() { + return maze[0].length; + } + + public Coordinate getEntry() { + return start; + } + + public Coordinate getExit() { + return end; + } + + public boolean isExit(int x, int y) { + return x == end.getX() && y == end.getY(); + } + + public boolean isStart(int x, int y) { + return x == start.getX() && y == start.getY(); + } + + public boolean isExplored(int row, int col) { + return visited[row][col]; + } + + public boolean isWall(int row, int col) { + return maze[row][col] == WALL; + } + + public void setVisited(int row, int col, boolean value) { + visited[row][col] = value; + } + + public boolean isValidLocation(int row, int col) { + if (row < 0 || row >= getHeight() || col < 0 || col >= getWidth()) { + return false; + } + return true; + } + + public void printPath(List path) { + int[][] tempMaze = Arrays.stream(maze) + .map(int[]::clone) + .toArray(int[][]::new); + for (Coordinate coordinate : path) { + if (isStart(coordinate.getX(), coordinate.getY()) || isExit(coordinate.getX(), coordinate.getY())) { + continue; + } + tempMaze[coordinate.getX()][coordinate.getY()] = PATH; + } + System.out.println(toString(tempMaze)); + } + + public String toString(int[][] maze) { + StringBuilder result = new StringBuilder(getWidth() * (getHeight() + 1)); + for (int row = 0; row < getHeight(); row++) { + for (int col = 0; col < getWidth(); col++) { + if (maze[row][col] == ROAD) { + result.append(' '); + } else if (maze[row][col] == WALL) { + result.append('#'); + } else if (maze[row][col] == START) { + result.append('S'); + } else if (maze[row][col] == EXIT) { + result.append('E'); + } else { + result.append('.'); + } + } + result.append('\n'); + } + return result.toString(); + } + + public void reset() { + for (int i = 0; i < visited.length; i++) + Arrays.fill(visited[i], false); + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/maze/solver/MazeDriver.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/MazeDriver.java similarity index 96% rename from algorithms/src/main/java/com/baeldung/algorithms/maze/solver/MazeDriver.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/MazeDriver.java index 60263deba3..a47c3c8581 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/maze/solver/MazeDriver.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/maze/solver/MazeDriver.java @@ -1,34 +1,34 @@ -package com.baeldung.algorithms.maze.solver; - -import java.io.File; -import java.util.List; - -public class MazeDriver { - public static void main(String[] args) throws Exception { - File maze1 = new File("src/main/resources/maze/maze1.txt"); - File maze2 = new File("src/main/resources/maze/maze2.txt"); - - execute(maze1); - execute(maze2); - } - - private static void execute(File file) throws Exception { - Maze maze = new Maze(file); - dfs(maze); - bfs(maze); - } - - private static void bfs(Maze maze) { - BFSMazeSolver bfs = new BFSMazeSolver(); - List path = bfs.solve(maze); - maze.printPath(path); - maze.reset(); - } - - private static void dfs(Maze maze) { - DFSMazeSolver dfs = new DFSMazeSolver(); - List path = dfs.solve(maze); - maze.printPath(path); - maze.reset(); - } -} +package com.baeldung.algorithms.maze.solver; + +import java.io.File; +import java.util.List; + +public class MazeDriver { + public static void main(String[] args) throws Exception { + File maze1 = new File("src/main/resources/maze/maze1.txt"); + File maze2 = new File("src/main/resources/maze/maze2.txt"); + + execute(maze1); + execute(maze2); + } + + private static void execute(File file) throws Exception { + Maze maze = new Maze(file); + dfs(maze); + bfs(maze); + } + + private static void bfs(Maze maze) { + BFSMazeSolver bfs = new BFSMazeSolver(); + List path = bfs.solve(maze); + maze.printPath(path); + maze.reset(); + } + + private static void dfs(Maze maze) { + DFSMazeSolver dfs = new DFSMazeSolver(); + List path = dfs.solve(maze); + maze.printPath(path); + maze.reset(); + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mercator/EllipticalMercator.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/mercator/EllipticalMercator.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/mercator/EllipticalMercator.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/mercator/EllipticalMercator.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mercator/Mercator.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/mercator/Mercator.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/mercator/Mercator.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/mercator/Mercator.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mercator/SphericalMercator.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/mercator/SphericalMercator.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/mercator/SphericalMercator.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/mercator/SphericalMercator.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/numberwordconverter/NumberWordConverter.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/numberwordconverter/NumberWordConverter.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/numberwordconverter/NumberWordConverter.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/numberwordconverter/NumberWordConverter.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Point.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Point.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Point.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Point.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/romannumerals/RomanArabicConverter.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/romannumerals/RomanArabicConverter.java similarity index 96% rename from algorithms/src/main/java/com/baeldung/algorithms/romannumerals/RomanArabicConverter.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/romannumerals/RomanArabicConverter.java index ab0922ecf4..acd275e609 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/romannumerals/RomanArabicConverter.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/romannumerals/RomanArabicConverter.java @@ -1,52 +1,52 @@ -package com.baeldung.algorithms.romannumerals; - -import java.util.List; - -class RomanArabicConverter { - - public static int romanToArabic(String input) { - String romanNumeral = input.toUpperCase(); - int result = 0; - - List romanNumerals = RomanNumeral.getReverseSortedValues(); - - int i = 0; - - while ((romanNumeral.length() > 0) && (i < romanNumerals.size())) { - RomanNumeral symbol = romanNumerals.get(i); - if (romanNumeral.startsWith(symbol.name())) { - result += symbol.getValue(); - romanNumeral = romanNumeral.substring(symbol.name().length()); - } else { - i++; - } - } - if (romanNumeral.length() > 0) { - throw new IllegalArgumentException(input + " cannot be converted to a Roman Numeral"); - } - - return result; - } - - public static String arabicToRoman(int number) { - if ((number <= 0) || (number > 4000)) { - throw new IllegalArgumentException(number + " is not in range (0,4000]"); - } - - List romanNumerals = RomanNumeral.getReverseSortedValues(); - - int i = 0; - StringBuilder sb = new StringBuilder(); - - while (number > 0 && i < romanNumerals.size()) { - RomanNumeral currentSymbol = romanNumerals.get(i); - if (currentSymbol.getValue() <= number) { - sb.append(currentSymbol.name()); - number -= currentSymbol.getValue(); - } else { - i++; - } - } - return sb.toString(); - } -} +package com.baeldung.algorithms.romannumerals; + +import java.util.List; + +class RomanArabicConverter { + + public static int romanToArabic(String input) { + String romanNumeral = input.toUpperCase(); + int result = 0; + + List romanNumerals = RomanNumeral.getReverseSortedValues(); + + int i = 0; + + while ((romanNumeral.length() > 0) && (i < romanNumerals.size())) { + RomanNumeral symbol = romanNumerals.get(i); + if (romanNumeral.startsWith(symbol.name())) { + result += symbol.getValue(); + romanNumeral = romanNumeral.substring(symbol.name().length()); + } else { + i++; + } + } + if (romanNumeral.length() > 0) { + throw new IllegalArgumentException(input + " cannot be converted to a Roman Numeral"); + } + + return result; + } + + public static String arabicToRoman(int number) { + if ((number <= 0) || (number > 4000)) { + throw new IllegalArgumentException(number + " is not in range (0,4000]"); + } + + List romanNumerals = RomanNumeral.getReverseSortedValues(); + + int i = 0; + StringBuilder sb = new StringBuilder(); + + while (number > 0 && i < romanNumerals.size()) { + RomanNumeral currentSymbol = romanNumerals.get(i); + if (currentSymbol.getValue() <= number) { + sb.append(currentSymbol.name()); + number -= currentSymbol.getValue(); + } else { + i++; + } + } + return sb.toString(); + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/romannumerals/RomanNumeral.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/romannumerals/RomanNumeral.java similarity index 96% rename from algorithms/src/main/java/com/baeldung/algorithms/romannumerals/RomanNumeral.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/romannumerals/RomanNumeral.java index 219f0b5090..2ee5bb6d75 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/romannumerals/RomanNumeral.java +++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/romannumerals/RomanNumeral.java @@ -1,26 +1,26 @@ -package com.baeldung.algorithms.romannumerals; - -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; -import java.util.stream.Collectors; - -enum RomanNumeral { - I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000); - - private int value; - - RomanNumeral(int value) { - this.value = value; - } - - public int getValue() { - return value; - } - - public static List getReverseSortedValues() { - return Arrays.stream(values()) - .sorted(Comparator.comparing((RomanNumeral e) -> e.value).reversed()) - .collect(Collectors.toList()); - } -} +package com.baeldung.algorithms.romannumerals; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +enum RomanNumeral { + I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000); + + private int value; + + RomanNumeral(int value) { + this.value = value; + } + + public int getValue() { + return value; + } + + public static List getReverseSortedValues() { + return Arrays.stream(values()) + .sorted(Comparator.comparing((RomanNumeral e) -> e.value).reversed()) + .collect(Collectors.toList()); + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/sudoku/BacktrackingAlgorithm.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/BacktrackingAlgorithm.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/sudoku/BacktrackingAlgorithm.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/BacktrackingAlgorithm.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/sudoku/ColumnNode.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/ColumnNode.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/sudoku/ColumnNode.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/ColumnNode.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/sudoku/DancingLinks.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/DancingLinks.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/sudoku/DancingLinks.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/DancingLinks.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/sudoku/DancingLinksAlgorithm.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/DancingLinksAlgorithm.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/sudoku/DancingLinksAlgorithm.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/DancingLinksAlgorithm.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/sudoku/DancingNode.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/DancingNode.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/sudoku/DancingNode.java rename to algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/sudoku/DancingNode.java diff --git a/apache-cayenne/src/main/resources/logback.xml b/algorithms-miscellaneous-2/src/main/resources/logback.xml similarity index 100% rename from apache-cayenne/src/main/resources/logback.xml rename to algorithms-miscellaneous-2/src/main/resources/logback.xml diff --git a/algorithms-miscellaneous-2/src/main/resources/maze/maze1.txt b/algorithms-miscellaneous-2/src/main/resources/maze/maze1.txt new file mode 100644 index 0000000000..8b48c325d2 --- /dev/null +++ b/algorithms-miscellaneous-2/src/main/resources/maze/maze1.txt @@ -0,0 +1,12 @@ +S ######## +# # +# ### ## # +# # # # +# # # # # +# ## ##### +# # # +# # # # # +##### #### +# # E +# # # # +########## \ No newline at end of file diff --git a/algorithms-miscellaneous-2/src/main/resources/maze/maze2.txt b/algorithms-miscellaneous-2/src/main/resources/maze/maze2.txt new file mode 100644 index 0000000000..df5b6bc66b --- /dev/null +++ b/algorithms-miscellaneous-2/src/main/resources/maze/maze2.txt @@ -0,0 +1,22 @@ +S ########################## +# # # # +# # #### ############### # +# # # # # # +# # #### # # ############### +# # # # # # # +# # # #### ### ########### # +# # # # # # +# ################## # +######### # # # # # +# # #### # ####### # # +# # ### ### # # # # # +# # ## # ##### # # +##### ####### # # # # # +# # ## ## #### # # +# ##### ####### # # +# # ############ +####### ######### # # +# # ######## # +# ####### ###### ## # E +# # # ## # +############################ \ No newline at end of file diff --git a/algorithms/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceDataProvider.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceDataProvider.java similarity index 96% rename from algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceDataProvider.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceDataProvider.java index 89bd871616..d11da61191 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceDataProvider.java +++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceDataProvider.java @@ -1,21 +1,21 @@ -package com.baeldung.algorithms.editdistance; - -import org.junit.runners.Parameterized.Parameters; - -import java.util.Arrays; -import java.util.Collection; - -public class EditDistanceDataProvider { - - @Parameters - public static Collection getLists() { - return Arrays.asList(new Object[][] { - { "", "", 0 }, - { "ago", "", 3 }, - { "", "do", 2 }, - { "abc", "adc", 1 }, - { "peek", "pesek", 1 }, - { "sunday", "saturday", 3 } - }); - } -} +package com.baeldung.algorithms.editdistance; + +import org.junit.runners.Parameterized.Parameters; + +import java.util.Arrays; +import java.util.Collection; + +public class EditDistanceDataProvider { + + @Parameters + public static Collection getLists() { + return Arrays.asList(new Object[][] { + { "", "", 0 }, + { "ago", "", 3 }, + { "", "do", 2 }, + { "abc", "adc", 1 }, + { "peek", "pesek", 1 }, + { "sunday", "saturday", 3 } + }); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java similarity index 96% rename from algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java index 0df4715b80..3dd63e86ab 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java +++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java @@ -1,32 +1,32 @@ -package com.baeldung.algorithms.editdistance; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -import static org.junit.Assert.assertEquals; - -@RunWith(Parameterized.class) -public class EditDistanceUnitTest extends EditDistanceDataProvider { - - private String x; - private String y; - private int result; - - public EditDistanceUnitTest(String a, String b, int res) { - super(); - x = a; - y = b; - result = res; - } - - @Test - public void testEditDistance_RecursiveImplementation() { - assertEquals(result, EditDistanceRecursive.calculate(x, y)); - } - - @Test - public void testEditDistance_givenDynamicProgrammingImplementation() { - assertEquals(result, EditDistanceDynamicProgramming.calculate(x, y)); - } -} +package com.baeldung.algorithms.editdistance; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import static org.junit.Assert.assertEquals; + +@RunWith(Parameterized.class) +public class EditDistanceUnitTest extends EditDistanceDataProvider { + + private String x; + private String y; + private int result; + + public EditDistanceUnitTest(String a, String b, int res) { + super(); + x = a; + y = b; + result = res; + } + + @Test + public void testEditDistance_RecursiveImplementation() { + assertEquals(result, EditDistanceRecursive.calculate(x, y)); + } + + @Test + public void testEditDistance_givenDynamicProgrammingImplementation() { + assertEquals(result, EditDistanceDynamicProgramming.calculate(x, y)); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java similarity index 96% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java index af2430ec55..33889fbec6 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java +++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java @@ -1,23 +1,23 @@ -package com.baeldung.algorithms.linkedlist; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(value = Parameterized.class) -public class CycleDetectionBruteForceUnitTest extends CycleDetectionTestBase { - boolean cycleExists; - Node head; - - public CycleDetectionBruteForceUnitTest(Node head, boolean cycleExists) { - super(); - this.cycleExists = cycleExists; - this.head = head; - } - - @Test - public void givenList_detectLoop() { - Assert.assertEquals(cycleExists, CycleDetectionBruteForce.detectCycle(head).cycleExists); - } -} +package com.baeldung.algorithms.linkedlist; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(value = Parameterized.class) +public class CycleDetectionBruteForceUnitTest extends CycleDetectionTestBase { + boolean cycleExists; + Node head; + + public CycleDetectionBruteForceUnitTest(Node head, boolean cycleExists) { + super(); + this.cycleExists = cycleExists; + this.head = head; + } + + @Test + public void givenList_detectLoop() { + Assert.assertEquals(cycleExists, CycleDetectionBruteForce.detectCycle(head).cycleExists); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java similarity index 96% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java index ce31c84067..1496840771 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java +++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java @@ -1,23 +1,23 @@ -package com.baeldung.algorithms.linkedlist; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(value = Parameterized.class) -public class CycleDetectionByFastAndSlowIteratorsUnitTest extends CycleDetectionTestBase { - boolean cycleExists; - Node head; - - public CycleDetectionByFastAndSlowIteratorsUnitTest(Node head, boolean cycleExists) { - super(); - this.cycleExists = cycleExists; - this.head = head; - } - - @Test - public void givenList_detectLoop() { - Assert.assertEquals(cycleExists, CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); - } -} +package com.baeldung.algorithms.linkedlist; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(value = Parameterized.class) +public class CycleDetectionByFastAndSlowIteratorsUnitTest extends CycleDetectionTestBase { + boolean cycleExists; + Node head; + + public CycleDetectionByFastAndSlowIteratorsUnitTest(Node head, boolean cycleExists) { + super(); + this.cycleExists = cycleExists; + this.head = head; + } + + @Test + public void givenList_detectLoop() { + Assert.assertEquals(cycleExists, CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java similarity index 96% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java index 4451c3d3c9..136f55f834 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java +++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java @@ -1,23 +1,23 @@ -package com.baeldung.algorithms.linkedlist; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(value = Parameterized.class) -public class CycleDetectionByHashingUnitTest extends CycleDetectionTestBase { - boolean cycleExists; - Node head; - - public CycleDetectionByHashingUnitTest(Node head, boolean cycleExists) { - super(); - this.cycleExists = cycleExists; - this.head = head; - } - - @Test - public void givenList_detectLoop() { - Assert.assertEquals(cycleExists, CycleDetectionByHashing.detectCycle(head).cycleExists); - } -} +package com.baeldung.algorithms.linkedlist; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(value = Parameterized.class) +public class CycleDetectionByHashingUnitTest extends CycleDetectionTestBase { + boolean cycleExists; + Node head; + + public CycleDetectionByHashingUnitTest(Node head, boolean cycleExists) { + super(); + this.cycleExists = cycleExists; + this.head = head; + } + + @Test + public void givenList_detectLoop() { + Assert.assertEquals(cycleExists, CycleDetectionByHashing.detectCycle(head).cycleExists); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionTestBase.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionTestBase.java similarity index 96% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionTestBase.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionTestBase.java index 51906de8e5..1c6f56b20d 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionTestBase.java +++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionTestBase.java @@ -1,62 +1,62 @@ -package com.baeldung.algorithms.linkedlist; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -public class CycleDetectionTestBase { - - @Parameters - public static Collection getLists() { - return Arrays.asList(new Object[][] { - { createList(), false }, - { createListWithLoop(), true }, - { createListWithFullCycle(), true }, - { createListWithSingleNodeInCycle(), true } - }); - } - - public static Node createList() { - Node root = Node.createNewNode(10, null); - - for (int i = 9; i >= 1; --i) { - Node current = Node.createNewNode(i, root); - root = current; - } - - return root; - } - - public static Node createListWithLoop() { - Node node = createList(); - createLoop(node); - return node; - } - - public static Node createListWithFullCycle() { - Node head = createList(); - Node tail = Node.getTail(head); - tail.next = head; - return head; - } - - public static Node createListWithSingleNodeInCycle() { - Node head = createList(); - Node tail = Node.getTail(head); - tail.next = tail; - return head; - } - - public static void createLoop(Node root) { - Node tail = Node.getTail(root); - - Node middle = root; - for (int i = 1; i <= 4; i++) { - middle = middle.next; - } - - tail.next = middle; - } - -} +package com.baeldung.algorithms.linkedlist; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.runners.Parameterized.Parameters; + +public class CycleDetectionTestBase { + + @Parameters + public static Collection getLists() { + return Arrays.asList(new Object[][] { + { createList(), false }, + { createListWithLoop(), true }, + { createListWithFullCycle(), true }, + { createListWithSingleNodeInCycle(), true } + }); + } + + public static Node createList() { + Node root = Node.createNewNode(10, null); + + for (int i = 9; i >= 1; --i) { + Node current = Node.createNewNode(i, root); + root = current; + } + + return root; + } + + public static Node createListWithLoop() { + Node node = createList(); + createLoop(node); + return node; + } + + public static Node createListWithFullCycle() { + Node head = createList(); + Node tail = Node.getTail(head); + tail.next = head; + return head; + } + + public static Node createListWithSingleNodeInCycle() { + Node head = createList(); + Node tail = Node.getTail(head); + tail.next = tail; + return head; + } + + public static void createLoop(Node root) { + Node tail = Node.getTail(root); + + Node middle = root; + for (int i = 1; i <= 4; i++) { + middle = middle.next; + } + + tail.next = middle; + } + +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java similarity index 97% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java index f69e3c35ba..36f08d2b76 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java +++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java @@ -1,24 +1,24 @@ -package com.baeldung.algorithms.linkedlist; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(value = Parameterized.class) -public class CycleRemovalBruteForceUnitTest extends CycleDetectionTestBase { - boolean cycleExists; - Node head; - - public CycleRemovalBruteForceUnitTest(Node head, boolean cycleExists) { - super(); - this.cycleExists = cycleExists; - this.head = head; - } - - @Test - public void givenList_ifLoopExists_thenDetectAndRemoveLoop() { - Assert.assertEquals(cycleExists, CycleRemovalBruteForce.detectAndRemoveCycle(head)); - Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); - } -} +package com.baeldung.algorithms.linkedlist; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(value = Parameterized.class) +public class CycleRemovalBruteForceUnitTest extends CycleDetectionTestBase { + boolean cycleExists; + Node head; + + public CycleRemovalBruteForceUnitTest(Node head, boolean cycleExists) { + super(); + this.cycleExists = cycleExists; + this.head = head; + } + + @Test + public void givenList_ifLoopExists_thenDetectAndRemoveLoop() { + Assert.assertEquals(cycleExists, CycleRemovalBruteForce.detectAndRemoveCycle(head)); + Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java similarity index 97% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java index c17aa6eeab..cc7589c53d 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java +++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java @@ -1,24 +1,24 @@ -package com.baeldung.algorithms.linkedlist; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(value = Parameterized.class) -public class CycleRemovalByCountingLoopNodesUnitTest extends CycleDetectionTestBase { - boolean cycleExists; - Node head; - - public CycleRemovalByCountingLoopNodesUnitTest(Node head, boolean cycleExists) { - super(); - this.cycleExists = cycleExists; - this.head = head; - } - - @Test - public void givenList_ifLoopExists_thenDetectAndRemoveLoop() { - Assert.assertEquals(cycleExists, CycleRemovalByCountingLoopNodes.detectAndRemoveCycle(head)); - Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); - } -} +package com.baeldung.algorithms.linkedlist; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(value = Parameterized.class) +public class CycleRemovalByCountingLoopNodesUnitTest extends CycleDetectionTestBase { + boolean cycleExists; + Node head; + + public CycleRemovalByCountingLoopNodesUnitTest(Node head, boolean cycleExists) { + super(); + this.cycleExists = cycleExists; + this.head = head; + } + + @Test + public void givenList_ifLoopExists_thenDetectAndRemoveLoop() { + Assert.assertEquals(cycleExists, CycleRemovalByCountingLoopNodes.detectAndRemoveCycle(head)); + Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); + } +} diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java similarity index 97% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java index 06ff840a59..350e63dcc3 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java +++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java @@ -1,24 +1,24 @@ -package com.baeldung.algorithms.linkedlist; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(value = Parameterized.class) -public class CycleRemovalWithoutCountingLoopNodesUnitTest extends CycleDetectionTestBase { - boolean cycleExists; - Node head; - - public CycleRemovalWithoutCountingLoopNodesUnitTest(Node head, boolean cycleExists) { - super(); - this.cycleExists = cycleExists; - this.head = head; - } - - @Test - public void givenList_ifLoopExists_thenDetectAndRemoveLoop() { - Assert.assertEquals(cycleExists, CycleRemovalWithoutCountingLoopNodes.detectAndRemoveCycle(head)); - Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); - } +package com.baeldung.algorithms.linkedlist; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(value = Parameterized.class) +public class CycleRemovalWithoutCountingLoopNodesUnitTest extends CycleDetectionTestBase { + boolean cycleExists; + Node head; + + public CycleRemovalWithoutCountingLoopNodesUnitTest(Node head, boolean cycleExists) { + super(); + this.cycleExists = cycleExists; + this.head = head; + } + + @Test + public void givenList_ifLoopExists_thenDetectAndRemoveLoop() { + Assert.assertEquals(cycleExists, CycleRemovalWithoutCountingLoopNodes.detectAndRemoveCycle(head)); + Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); + } } \ No newline at end of file diff --git a/algorithms/src/test/java/com/baeldung/algorithms/mercator/EllipticalMercatorUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/mercator/EllipticalMercatorUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/mercator/EllipticalMercatorUnitTest.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/mercator/EllipticalMercatorUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/mercator/SphericalMercatorUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/mercator/SphericalMercatorUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/mercator/SphericalMercatorUnitTest.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/mercator/SphericalMercatorUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java similarity index 95% rename from algorithms/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java index b289ec6bc9..9043cfe9cc 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java +++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java @@ -1,29 +1,29 @@ -package com.baeldung.algorithms.romannumerals; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.Test; - -public class RomanArabicConverterUnitTest { - - @Test - public void given2018Roman_WhenConvertingToArabic_ThenReturn2018() { - - String roman2018 = "MMXVIII"; - - int result = RomanArabicConverter.romanToArabic(roman2018); - - assertThat(result).isEqualTo(2018); - } - - @Test - public void given1999Arabic_WhenConvertingToRoman_ThenReturnMCMXCIX() { - - int arabic1999 = 1999; - - String result = RomanArabicConverter.arabicToRoman(arabic1999); - - assertThat(result).isEqualTo("MCMXCIX"); - } - -} +package com.baeldung.algorithms.romannumerals; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class RomanArabicConverterUnitTest { + + @Test + public void given2018Roman_WhenConvertingToArabic_ThenReturn2018() { + + String roman2018 = "MMXVIII"; + + int result = RomanArabicConverter.romanToArabic(roman2018); + + assertThat(result).isEqualTo(2018); + } + + @Test + public void given1999Arabic_WhenConvertingToRoman_ThenReturnMCMXCIX() { + + int arabic1999 = 1999; + + String result = RomanArabicConverter.arabicToRoman(arabic1999); + + assertThat(result).isEqualTo("MCMXCIX"); + } + +} diff --git a/algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java rename to algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java diff --git a/algorithms-sorting/.gitignore b/algorithms-sorting/.gitignore new file mode 100644 index 0000000000..30b2b7442c --- /dev/null +++ b/algorithms-sorting/.gitignore @@ -0,0 +1,4 @@ +/target/ +.settings/ +.classpath +.project \ No newline at end of file diff --git a/algorithms-sorting/README.md b/algorithms-sorting/README.md new file mode 100644 index 0000000000..f88b93e25e --- /dev/null +++ b/algorithms-sorting/README.md @@ -0,0 +1,7 @@ +## Relevant articles: + +- [Bubble Sort in Java](http://www.baeldung.com/java-bubble-sort) +- [Merge Sort in Java](https://www.baeldung.com/java-merge-sort) +- [Quicksort Algorithm Implementation in Java](https://www.baeldung.com/java-quicksort) +- [Insertion Sort in Java](https://www.baeldung.com/java-insertion-sort) + diff --git a/algorithms-sorting/pom.xml b/algorithms-sorting/pom.xml new file mode 100644 index 0000000000..60ae37f2a4 --- /dev/null +++ b/algorithms-sorting/pom.xml @@ -0,0 +1,58 @@ + + 4.0.0 + com.baeldung + algorithms-sorting + 0.0.1-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + commons-codec + commons-codec + ${commons-codec.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + org.assertj + assertj-core + ${org.assertj.core.version} + test + + + + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + + + + + + 1.16.12 + 3.6.1 + 3.9.0 + 1.11 + + + \ No newline at end of file diff --git a/algorithms-sorting/roundUpToHundred/.gitignore b/algorithms-sorting/roundUpToHundred/.gitignore new file mode 100644 index 0000000000..ae3c172604 --- /dev/null +++ b/algorithms-sorting/roundUpToHundred/.gitignore @@ -0,0 +1 @@ +/bin/ diff --git a/algorithms-sorting/roundUpToHundred/src/com/java/src/RoundUpToHundred.java b/algorithms-sorting/roundUpToHundred/src/com/java/src/RoundUpToHundred.java new file mode 100644 index 0000000000..6c02a340d3 --- /dev/null +++ b/algorithms-sorting/roundUpToHundred/src/com/java/src/RoundUpToHundred.java @@ -0,0 +1,20 @@ +package com.java.src; + +import java.util.Scanner; + +public class RoundUpToHundred { + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + double input = scanner.nextDouble(); + scanner.close(); + + RoundUpToHundred.round(input); + } + + static long round(double input) { + long i = (long) Math.ceil(input); + return ((i + 99) / 100) * 100; + }; + +} diff --git a/algorithms-sorting/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java b/algorithms-sorting/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java new file mode 100644 index 0000000000..cb541ad49c --- /dev/null +++ b/algorithms-sorting/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java @@ -0,0 +1,14 @@ +package com.java.src; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class RoundUpToHundredTest { + @Test + public void givenInput_whenRound_thenRoundUpToTheNearestHundred() { + assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99)); + assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2)); + assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400)); + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/bubblesort/BubbleSort.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/bubblesort/BubbleSort.java similarity index 96% rename from algorithms/src/main/java/com/baeldung/algorithms/bubblesort/BubbleSort.java rename to algorithms-sorting/src/main/java/com/baeldung/algorithms/bubblesort/BubbleSort.java index 275cb7f3a2..2528032676 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/bubblesort/BubbleSort.java +++ b/algorithms-sorting/src/main/java/com/baeldung/algorithms/bubblesort/BubbleSort.java @@ -1,40 +1,40 @@ -package com.baeldung.algorithms.bubblesort; - -import java.util.stream.IntStream; - -public class BubbleSort { - - void bubbleSort(Integer[] arr) { - int n = arr.length; - IntStream.range(0, n - 1) - .flatMap(i -> IntStream.range(1, n - i)) - .forEach(j -> { - if (arr[j - 1] > arr[j]) { - int temp = arr[j]; - arr[j] = arr[j - 1]; - arr[j - 1] = temp; - } - }); - } - - void optimizedBubbleSort(Integer[] arr) { - int i = 0, n = arr.length; - - boolean swapNeeded = true; - while (i < n - 1 && swapNeeded) { - swapNeeded = false; - for (int j = 1; j < n - i; j++) { - if (arr[j - 1] > arr[j]) { - - int temp = arr[j - 1]; - arr[j - 1] = arr[j]; - arr[j] = temp; - swapNeeded = true; - } - } - if (!swapNeeded) - break; - i++; - } - } -} +package com.baeldung.algorithms.bubblesort; + +import java.util.stream.IntStream; + +public class BubbleSort { + + void bubbleSort(Integer[] arr) { + int n = arr.length; + IntStream.range(0, n - 1) + .flatMap(i -> IntStream.range(1, n - i)) + .forEach(j -> { + if (arr[j - 1] > arr[j]) { + int temp = arr[j]; + arr[j] = arr[j - 1]; + arr[j - 1] = temp; + } + }); + } + + void optimizedBubbleSort(Integer[] arr) { + int i = 0, n = arr.length; + + boolean swapNeeded = true; + while (i < n - 1 && swapNeeded) { + swapNeeded = false; + for (int j = 1; j < n - i; j++) { + if (arr[j - 1] > arr[j]) { + + int temp = arr[j - 1]; + arr[j - 1] = arr[j]; + arr[j] = temp; + swapNeeded = true; + } + } + if (!swapNeeded) + break; + i++; + } + } +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/heapsort/Heap.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/heapsort/Heap.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/heapsort/Heap.java rename to algorithms-sorting/src/main/java/com/baeldung/algorithms/heapsort/Heap.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/insertionsort/InsertionSort.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/insertionsort/InsertionSort.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/insertionsort/InsertionSort.java rename to algorithms-sorting/src/main/java/com/baeldung/algorithms/insertionsort/InsertionSort.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java rename to algorithms-sorting/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/quicksort/QuickSort.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/quicksort/QuickSort.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/quicksort/QuickSort.java rename to algorithms-sorting/src/main/java/com/baeldung/algorithms/quicksort/QuickSort.java diff --git a/algorithms/src/main/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSort.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSort.java similarity index 100% rename from algorithms/src/main/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSort.java rename to algorithms-sorting/src/main/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSort.java diff --git a/hbase/src/main/resources/logback.xml b/algorithms-sorting/src/main/resources/logback.xml similarity index 100% rename from hbase/src/main/resources/logback.xml rename to algorithms-sorting/src/main/resources/logback.xml diff --git a/algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java b/algorithms-sorting/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java similarity index 97% rename from algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java rename to algorithms-sorting/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java index c3260a18dd..210ee2378a 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java +++ b/algorithms-sorting/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java @@ -1,26 +1,26 @@ -package com.baeldung.algorithms.bubblesort; - -import static org.junit.jupiter.api.Assertions.assertArrayEquals; - -import org.junit.jupiter.api.Test; - -public class BubbleSortUnitTest { - - @Test - public void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() { - Integer[] array = { 2, 1, 4, 6, 3, 5 }; - Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 }; - BubbleSort bubbleSort = new BubbleSort(); - bubbleSort.bubbleSort(array); - assertArrayEquals(array, sortedArray); - } - - @Test - public void givenIntegerArray_whenSortedWithOptimizedBubbleSort_thenGetSortedArray() { - Integer[] array = { 2, 1, 4, 6, 3, 5 }; - Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 }; - BubbleSort bubbleSort = new BubbleSort(); - bubbleSort.optimizedBubbleSort(array); - assertArrayEquals(array, sortedArray); - } +package com.baeldung.algorithms.bubblesort; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +import org.junit.jupiter.api.Test; + +public class BubbleSortUnitTest { + + @Test + public void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() { + Integer[] array = { 2, 1, 4, 6, 3, 5 }; + Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 }; + BubbleSort bubbleSort = new BubbleSort(); + bubbleSort.bubbleSort(array); + assertArrayEquals(array, sortedArray); + } + + @Test + public void givenIntegerArray_whenSortedWithOptimizedBubbleSort_thenGetSortedArray() { + Integer[] array = { 2, 1, 4, 6, 3, 5 }; + Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 }; + BubbleSort bubbleSort = new BubbleSort(); + bubbleSort.optimizedBubbleSort(array); + assertArrayEquals(array, sortedArray); + } } \ No newline at end of file diff --git a/algorithms/src/test/java/com/baeldung/algorithms/heapsort/HeapUnitTest.java b/algorithms-sorting/src/test/java/com/baeldung/algorithms/heapsort/HeapUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/heapsort/HeapUnitTest.java rename to algorithms-sorting/src/test/java/com/baeldung/algorithms/heapsort/HeapUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/insertionsort/InsertionSortUnitTest.java b/algorithms-sorting/src/test/java/com/baeldung/algorithms/insertionsort/InsertionSortUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/insertionsort/InsertionSortUnitTest.java rename to algorithms-sorting/src/test/java/com/baeldung/algorithms/insertionsort/InsertionSortUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java b/algorithms-sorting/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java rename to algorithms-sorting/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/quicksort/QuickSortUnitTest.java b/algorithms-sorting/src/test/java/com/baeldung/algorithms/quicksort/QuickSortUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/quicksort/QuickSortUnitTest.java rename to algorithms-sorting/src/test/java/com/baeldung/algorithms/quicksort/QuickSortUnitTest.java diff --git a/algorithms/src/test/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSortUnitTest.java b/algorithms-sorting/src/test/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSortUnitTest.java similarity index 100% rename from algorithms/src/test/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSortUnitTest.java rename to algorithms-sorting/src/test/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSortUnitTest.java diff --git a/algorithms/.gitignore b/algorithms/.gitignore deleted file mode 100644 index b83d22266a..0000000000 --- a/algorithms/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target/ diff --git a/core-java-10/src/main/java/com/baeldung/graal/CountUppercase.java b/core-java-10/src/main/java/com/baeldung/graal/CountUppercase.java new file mode 100644 index 0000000000..4cad9cb965 --- /dev/null +++ b/core-java-10/src/main/java/com/baeldung/graal/CountUppercase.java @@ -0,0 +1,25 @@ +package com.baeldung.graal; + +public class CountUppercase { + static final int ITERATIONS = Math.max(Integer.getInteger("iterations", 1), 1); + + public static void main(String[] args) { + String sentence = String.join(" ", args); + for (int iter = 0; iter < ITERATIONS; iter++) { + if (ITERATIONS != 1) System.out.println("-- iteration " + (iter + 1) + " --"); + long total = 0, start = System.currentTimeMillis(), last = start; + for (int i = 1; i < 10_000_000; i++) { + total += sentence + .chars() + .filter(Character::isUpperCase) + .count(); + if (i % 1_000_000 == 0) { + long now = System.currentTimeMillis(); + System.out.printf("%d (%d ms)%n", i / 1_000_000, now - last); + last = now; + } + } + System.out.printf("total: %d (%d ms)%n", total, System.currentTimeMillis() - start); + } + } +} diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/semaphores/SemaphoresManualTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/semaphores/SemaphoresManualTest.java index 8d64bb6809..cf3bdeda5b 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/semaphores/SemaphoresManualTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/semaphores/SemaphoresManualTest.java @@ -4,6 +4,7 @@ import org.junit.Test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; import static org.junit.Assert.assertEquals; @@ -15,26 +16,28 @@ public class SemaphoresManualTest { // ========= login queue ====== @Test - public void givenLoginQueue_whenReachLimit_thenBlocked() { + public void givenLoginQueue_whenReachLimit_thenBlocked() throws InterruptedException { final int slots = 10; final ExecutorService executorService = Executors.newFixedThreadPool(slots); final LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots); IntStream.range(0, slots) .forEach(user -> executorService.execute(loginQueue::tryLogin)); executorService.shutdown(); + executorService.awaitTermination(10, TimeUnit.SECONDS); assertEquals(0, loginQueue.availableSlots()); assertFalse(loginQueue.tryLogin()); } @Test - public void givenLoginQueue_whenLogout_thenSlotsAvailable() { + public void givenLoginQueue_whenLogout_thenSlotsAvailable() throws InterruptedException { final int slots = 10; final ExecutorService executorService = Executors.newFixedThreadPool(slots); final LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots); IntStream.range(0, slots) .forEach(user -> executorService.execute(loginQueue::tryLogin)); executorService.shutdown(); + executorService.awaitTermination(10, TimeUnit.SECONDS); assertEquals(0, loginQueue.availableSlots()); loginQueue.logout(); @@ -45,13 +48,14 @@ public class SemaphoresManualTest { // ========= delay queue ======= @Test - public void givenDelayQueue_whenReachLimit_thenBlocked() { + public void givenDelayQueue_whenReachLimit_thenBlocked() throws InterruptedException { final int slots = 50; final ExecutorService executorService = Executors.newFixedThreadPool(slots); final DelayQueueUsingTimedSemaphore delayQueue = new DelayQueueUsingTimedSemaphore(1, slots); IntStream.range(0, slots) .forEach(user -> executorService.execute(delayQueue::tryAdd)); executorService.shutdown(); + executorService.awaitTermination(10, TimeUnit.SECONDS); assertEquals(0, delayQueue.availableSlots()); assertFalse(delayQueue.tryAdd()); @@ -65,6 +69,7 @@ public class SemaphoresManualTest { IntStream.range(0, slots) .forEach(user -> executorService.execute(delayQueue::tryAdd)); executorService.shutdown(); + executorService.awaitTermination(10, TimeUnit.SECONDS); assertEquals(0, delayQueue.availableSlots()); Thread.sleep(1000); diff --git a/core-java/src/main/java/com/baeldung/ssl/example/SimpleClient.java b/core-java/src/main/java/com/baeldung/ssl/example/SimpleClient.java new file mode 100644 index 0000000000..c641a58a78 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/ssl/example/SimpleClient.java @@ -0,0 +1,29 @@ +package com.baeldung.ssl.example; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.Socket; + +import javax.net.SocketFactory; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; + +public class SimpleClient { + static void startClient(String host, int port) throws IOException { + SocketFactory factory = SSLSocketFactory.getDefault(); + try (Socket connection = factory.createSocket(host, port)) { + ((SSLSocket) connection).setEnabledCipherSuites( + new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"}); + ((SSLSocket) connection).setEnabledProtocols( + new String[] { "TLSv1.2"}); + BufferedReader input = new BufferedReader( + new InputStreamReader(connection.getInputStream())); + System.out.println(input.readLine()); + } + } + + public static void main(String[] args) throws IOException { + startClient("localhost", 1234); + } +} diff --git a/core-java/src/main/java/com/baeldung/ssl/example/SimpleServer.java b/core-java/src/main/java/com/baeldung/ssl/example/SimpleServer.java new file mode 100644 index 0000000000..3bbabdfbb8 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/ssl/example/SimpleServer.java @@ -0,0 +1,34 @@ +package com.baeldung.ssl.example; + +import java.io.IOException; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.Date; + +import javax.net.ServerSocketFactory; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLServerSocketFactory; + +public class SimpleServer { + static void startServer(int port) throws IOException { + ServerSocketFactory factory = SSLServerSocketFactory.getDefault(); + try (ServerSocket listener = factory.createServerSocket(port)) { + ((SSLServerSocket) listener).setNeedClientAuth(true); + ((SSLServerSocket) listener).setEnabledCipherSuites( + new String[] { "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"}); + ((SSLServerSocket) listener).setEnabledProtocols( + new String[] { "TLSv1.2"}); + while (true) { + try (Socket socket = listener.accept()) { + PrintWriter out = new PrintWriter(socket.getOutputStream(), true); + out.println(new Date().toString()); + } + } + } + } + + public static void main(String[] args) throws IOException { + startServer(1234); + } +} diff --git a/core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java b/core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java index 286dffb56a..ab962fc150 100644 --- a/core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java +++ b/core-java/src/test/java/com/baeldung/nth/root/calculator/NthRootCalculatorUnitTest.java @@ -7,14 +7,12 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.junit.MockitoJUnitRunner; -@RunWith(MockitoJUnitRunner.class) public class NthRootCalculatorUnitTest { - @InjectMocks - private NthRootCalculator nthRootCalculator; + private NthRootCalculator nthRootCalculator = new NthRootCalculator(); @Test - public void giventThatTheBaseIs125_andTheExpIs3_whenCalculateIsCalled_thenTheResultIsTheCorrectOne() { + public void whenBaseIs125AndNIs3_thenNthRootIs5() { Double result = nthRootCalculator.calculate(125.0, 3.0); assertEquals(result, (Double) 5.0d); } diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 9906b59a93..ab9e96c2e1 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -40,3 +40,5 @@ - [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class) - [Concatenate Strings in Kotlin](https://www.baeldung.com/kotlin-concatenate-strings) - [Kotlin return, break, continue Keywords](https://www.baeldung.com/kotlin-return-break-continue) +- [Mapping of Data Objects in Kotlin](https://www.baeldung.com/kotlin-data-objects-mapping) +- [Initializing Arrays in Kotlin](https://www.baeldung.com/kotlin-initialize-array) diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datamapping/User.kt b/core-kotlin/src/main/kotlin/com/baeldung/datamapping/User.kt new file mode 100644 index 0000000000..38c88b7c37 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/datamapping/User.kt @@ -0,0 +1,10 @@ +package com.baeldung.datamapping + +data class User( + val firstName: String, + val lastName: String, + val street: String, + val houseNumber: String, + val phone: String, + val age: Int, + val password: String) \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datamapping/UserExtensions.kt b/core-kotlin/src/main/kotlin/com/baeldung/datamapping/UserExtensions.kt new file mode 100644 index 0000000000..1f3d7f3b47 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/datamapping/UserExtensions.kt @@ -0,0 +1,22 @@ +package com.baeldung.datamapping + +import kotlin.reflect.full.memberProperties + +fun User.toUserView() = UserView( + name = "$firstName $lastName", + address = "$street $houseNumber", + telephone = phone, + age = age +) + +fun User.toUserViewReflection() = with(::UserView) { + val propertiesByName = User::class.memberProperties.associateBy { it.name } + callBy(parameters.associate { parameter -> + parameter to when (parameter.name) { + UserView::name.name -> "$firstName $lastName" + UserView::address.name -> "$street $houseNumber" + UserView::telephone.name -> phone + else -> propertiesByName[parameter.name]?.get(this@toUserViewReflection) + } + }) +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/datamapping/UserView.kt b/core-kotlin/src/main/kotlin/com/baeldung/datamapping/UserView.kt new file mode 100644 index 0000000000..ca27b1961c --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/datamapping/UserView.kt @@ -0,0 +1,8 @@ +package com.baeldung.datamapping + +data class UserView( + val name: String, + val address: String, + val telephone: String, + val age: Int +) \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt b/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt new file mode 100644 index 0000000000..2309d23c36 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/sorting/SortingExample.kt @@ -0,0 +1,44 @@ +package com.baeldung.sorting + +import kotlin.comparisons.* + +fun sortMethodUsage() { + val sortedValues = mutableListOf(1, 2, 7, 6, 5, 6) + sortedValues.sort() + println(sortedValues) +} + +fun sortByMethodUsage() { + val sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e") + sortedValues.sortBy { it.second } + println(sortedValues) +} + +fun sortWithMethodUsage() { + val sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e") + sortedValues.sortWith(compareBy({it.second}, {it.first})) + println(sortedValues) +} + +fun > getSimpleComparator() : Comparator { + val ascComparator = naturalOrder() + return ascComparator +} + +fun getComplexComparator() { + val complexComparator = compareBy>({it.first}, {it.second}) +} + +fun nullHandlingUsage() { + val sortedValues = mutableListOf(1 to "a", 2 to null, 7 to "c", 6 to "d", 5 to "c", 6 to "e") + sortedValues.sortWith(nullsLast(compareBy { it.second })) + println(sortedValues) +} + +fun extendedComparatorUsage() { + val students = mutableListOf(21 to "Helen", 21 to "Tom", 20 to "Jim") + + val ageComparator = compareBy> {it.first} + val ageAndNameComparator = ageComparator.thenByDescending {it.second} + println(students.sortedWith(ageAndNameComparator)) +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/datamapping/UserTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/datamapping/UserTest.kt new file mode 100644 index 0000000000..2d03039a80 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/datamapping/UserTest.kt @@ -0,0 +1,43 @@ +package com.baeldung.datamapping + +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertAll +import kotlin.test.assertEquals + +class UserTest { + + @Test + fun `maps User to UserResponse using extension function`() { + val p = buildUser() + val view = p.toUserView() + assertUserView(view) + } + + @Test + fun `maps User to UserResponse using reflection`() { + val p = buildUser() + val view = p.toUserViewReflection() + assertUserView(view) + } + + private fun buildUser(): User { + return User( + "Java", + "Duke", + "Javastreet", + "42", + "1234567", + 30, + "s3cr37" + ) + } + + private fun assertUserView(pr: UserView) { + assertAll( + { assertEquals("Java Duke", pr.name) }, + { assertEquals("Javastreet 42", pr.address) }, + { assertEquals("1234567", pr.telephone) }, + { assertEquals(30, pr.age) } + ) + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ArrayInitializationTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ArrayInitializationTest.kt new file mode 100644 index 0000000000..ba3694c831 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/ArrayInitializationTest.kt @@ -0,0 +1,49 @@ +package com.baeldung.kotlin + +import org.junit.Test +import kotlin.test.assertEquals + +class ArrayInitializationTest { + + @Test + fun givenArrayOfStrings_thenValuesPopulated() { + val strings = arrayOf("January", "February", "March") + + assertEquals(3, strings.size) + assertEquals("March", strings[2]) + } + + @Test + fun givenArrayOfIntegers_thenValuesPopulated() { + val integers = intArrayOf(1, 2, 3, 4) + + assertEquals(4, integers.size) + assertEquals(1, integers[0]) + } + + @Test + fun givenArrayOfNulls_whenPopulated_thenValuesPresent() { + val array = arrayOfNulls(5) + + for (i in array.indices) { + array[i] = i * i + } + + assertEquals(16, array[4]) + } + + @Test + fun whenGeneratorUsed_thenValuesPresent() { + val generatedArray = IntArray(10) { i -> i * i } + + assertEquals(81, generatedArray[9]) + } + + @Test + fun whenStringGenerated_thenValuesPresent() { + val generatedStringArray = Array(10) { i -> "Number of index: $i" } + + assertEquals("Number of index: 0", generatedStringArray[0]) + } + +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt new file mode 100644 index 0000000000..8a94e29c2f --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/sorting/SortingExampleKtTest.kt @@ -0,0 +1,14 @@ +package com.baeldung.sorting + +import org.junit.jupiter.api.Test + +import org.junit.jupiter.api.Assertions.* + +class SortingExampleKtTest { + + @Test + fun naturalOrderComparator_ShouldBeAscendingTest() { + val resultingList = listOf(1, 5, 6, 6, 2, 3, 4).sortedWith(getSimpleComparator()) + assertTrue(listOf(1, 2, 3, 4, 5, 6, 6) == resultingList) + } +} \ No newline at end of file diff --git a/core-scala/pom.xml b/core-scala/pom.xml new file mode 100644 index 0000000000..eb7c1c3330 --- /dev/null +++ b/core-scala/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + core-scala + 1.0-SNAPSHOT + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.scala-lang + scala-library + ${scala.version} + + + + + src/main/scala + src/test/scala + + + net.alchim31.maven + scala-maven-plugin + 3.3.2 + + + + compile + testCompile + + + + -dependencyfile + ${project.build.directory}/.scala_dependencies + + + + + + + + + + 2.12.7 + + + diff --git a/core-scala/src/main/scala/com/baeldung/scala/ControlStructuresDemo.scala b/core-scala/src/main/scala/com/baeldung/scala/ControlStructuresDemo.scala new file mode 100644 index 0000000000..7c1281e573 --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/scala/ControlStructuresDemo.scala @@ -0,0 +1,44 @@ +package com.baeldung.scala + +/** + * Sample code demonstrating the various control structured. + * + * @author Chandra Prakash + * + */ +object ControlStructuresDemo { + def gcd(x : Int, y : Int) : Int = { + if (y == 0) x else gcd(y, x % y) + } + + def gcdIter(x : Int, y : Int) : Int = { + var a = x + var b = y + while (b > 0) { + a = a % b + val t = a + a = b + b = t + } + a + } + + def rangeSum(a : Int, b : Int) = { + var sum = 0; + for (i <- a to b) { + sum += i + } + sum + } + + def factorial(a : Int) : Int = { + var result = 1; + var i = 1; + do { + result *= i + i = i + 1 + } while (i <= a) + result + } + +} \ No newline at end of file diff --git a/core-scala/src/main/scala/com/baeldung/scala/Employee.scala b/core-scala/src/main/scala/com/baeldung/scala/Employee.scala new file mode 100644 index 0000000000..397f166aa7 --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/scala/Employee.scala @@ -0,0 +1,27 @@ +package com.baeldung.scala + +/** + * Sample Code demonstrating a class. + * + * @author Chandra Prakash + * + */ +class Employee(val name : String, + var salary : Int, + annualIncrement : Int = 20) { + + def incrementSalary() : Unit = { + salary += annualIncrement + } + + override def toString = + s"Employee(name=$name, salary=$salary)" +} + +/** + * A Trait which will make the toString return upper case value. + */ +trait UpperCasePrinter { + override def toString = super.toString toUpperCase +} + diff --git a/core-scala/src/main/scala/com/baeldung/scala/HelloWorld.scala b/core-scala/src/main/scala/com/baeldung/scala/HelloWorld.scala new file mode 100644 index 0000000000..b3f0ce09a5 --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/scala/HelloWorld.scala @@ -0,0 +1,6 @@ +package com.baeldung.scala + +object HelloWorld extends App { + println("Hello World!") + args foreach println +} diff --git a/core-scala/src/main/scala/com/baeldung/scala/HigherOrderFunctions.scala b/core-scala/src/main/scala/com/baeldung/scala/HigherOrderFunctions.scala new file mode 100644 index 0000000000..df97013206 --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/scala/HigherOrderFunctions.scala @@ -0,0 +1,27 @@ +package com.baeldung.scala + +/** + * Sample higher order functions. + * + * @author Chandra Prakash + * + */ +object HigherOrderFunctions { + + def mapReduce(r : (Int, Int) => Int, + i : Int, + m : Int => Int, + a : Int, b : Int) = { + def iter(a : Int, result : Int) : Int = { + if (a > b) result + else iter(a + 1, r(m(a), result)) + } + iter(a, i) + } + + def whileLoop(condition : => Boolean)(body : => Unit) : Unit = + if (condition) { + body + whileLoop(condition)(body) + } +} \ No newline at end of file diff --git a/core-scala/src/main/scala/com/baeldung/scala/IntSet.scala b/core-scala/src/main/scala/com/baeldung/scala/IntSet.scala new file mode 100644 index 0000000000..f1a5722a4e --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/scala/IntSet.scala @@ -0,0 +1,34 @@ +package com.baeldung.scala + +/** + * An abstract class for set of integers and its implementation. + * + * @author Chandra Prakash + * + */ +abstract class IntSet { + // add an element to the set + def incl(x : Int) : IntSet + + // whether an element belongs to the set + def contains(x : Int) : Boolean +} + +class EmptyIntSet extends IntSet { + + def contains(x : Int) : Boolean = false + + def incl(x : Int) = + new NonEmptyIntSet(x, this) +} + +class NonEmptyIntSet(val head : Int, val tail : IntSet) + extends IntSet { + + def contains(x : Int) : Boolean = + head == x || (tail contains x) + + def incl(x : Int) : IntSet = + if (this contains x) this + else new NonEmptyIntSet(x, this) +} \ No newline at end of file diff --git a/core-scala/src/main/scala/com/baeldung/scala/Utils.scala b/core-scala/src/main/scala/com/baeldung/scala/Utils.scala new file mode 100644 index 0000000000..93cd3e697e --- /dev/null +++ b/core-scala/src/main/scala/com/baeldung/scala/Utils.scala @@ -0,0 +1,33 @@ +package com.baeldung.scala + +/** + * Some utility methods. + * + * @author Chandra Prakash + * + */ +object Utils { + def average(x : Double, y : Double) = (x + y) / 2 + + def randomLessThan(d : Double) = { + var random = 0d + do { + random = Math.random() + } while (random >= d) + random + } + + def power(x : Int, y : Int) : Int = { + def powNested(i : Int, accumulator : Int) : Int = { + if (i <= 0) accumulator + else powNested(i - 1, x * accumulator) + } + powNested(y, 1) + } + + def fibonacci(n : Int) : Int = n match { + case 0 | 1 => 1 + case x if x > 1 => + fibonacci(x - 1) + fibonacci(x - 2) + } +} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/ControlStructuresDemoUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/ControlStructuresDemoUnitTest.scala new file mode 100644 index 0000000000..71422a8b4f --- /dev/null +++ b/core-scala/src/test/scala/com/baeldung/scala/ControlStructuresDemoUnitTest.scala @@ -0,0 +1,33 @@ +package com.baeldung.scala + +import com.baeldung.scala.ControlStructuresDemo._ +import org.junit.Test +import org.junit.Assert.assertEquals + +class ControlStructuresDemoUnitTest { + @Test + def givenTwoIntegers_whenGcdCalled_thenCorrectValueReturned = { + assertEquals(3, gcd(15, 27)) + } + + @Test + def givenTwoIntegers_whenGcdIterCalled_thenCorrectValueReturned = { + assertEquals(3, gcdIter(15, 27)) + } + + @Test + def givenTwoIntegers_whenRangeSumcalled_thenCorrectValueReturned = { + assertEquals(55, rangeSum(1, 10)) + } + + @Test + def givenPositiveInteger_whenFactorialInvoked_thenCorrectValueReturned = { + assertEquals(720, factorial(6)) + } + + @Test + def whenFactorialOf0Invoked_then1Returned = { + assertEquals(1, factorial(0)) + } + +} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/EmployeeUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/EmployeeUnitTest.scala new file mode 100644 index 0000000000..c51631dd2c --- /dev/null +++ b/core-scala/src/test/scala/com/baeldung/scala/EmployeeUnitTest.scala @@ -0,0 +1,30 @@ +package com.baeldung.scala + +import org.junit.Assert.assertEquals +import org.junit.Test + +class EmployeeUnitTest { + + @Test + def whenEmployeeSalaryIncremented_thenCorrectSalary = { + val employee = new Employee("John Doe", 1000) + employee.incrementSalary() + assertEquals(1020, employee.salary) + } + + @Test + def givenEmployee_whenToStringCalled_thenCorrectStringReturned = { + val employee = new Employee("John Doe", 1000) + assertEquals("Employee(name=John Doe, salary=1000)", employee.toString) + } + + @Test + def givenEmployeeWithTrait_whenToStringCalled_thenCorrectStringReturned = { + val employee = + new Employee("John Doe", 1000) with UpperCasePrinter + assertEquals("EMPLOYEE(NAME=JOHN DOE, SALARY=1000)", employee.toString) + } + +} + + diff --git a/core-scala/src/test/scala/com/baeldung/scala/HigherOrderFunctionsUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/HigherOrderFunctionsUnitTest.scala new file mode 100644 index 0000000000..63530ecaf4 --- /dev/null +++ b/core-scala/src/test/scala/com/baeldung/scala/HigherOrderFunctionsUnitTest.scala @@ -0,0 +1,49 @@ +package com.baeldung.scala + +import org.junit.Assert.assertEquals +import org.junit.Test + +import HigherOrderFunctions.mapReduce + +class HigherOrderFunctionsUnitTest { + + @Test + def whenCalledWithSumAndSquareFunctions_thenCorrectValueReturned = { + def square(x : Int) = x * x + + def sum(x : Int, y : Int) = x + y + + def sumSquares(a : Int, b : Int) = + mapReduce(sum, 0, square, a, b) + + assertEquals(385, sumSquares(1, 10)) + } + + @Test + def whenComputingSumOfSquaresWithAnonymousFunctions_thenCorrectValueReturned = { + def sumSquares(a : Int, b : Int) = + mapReduce((x, y) => x + y, 0, x => x * x, a, b) + + assertEquals(385, sumSquares(1, 10)) + } + + @Test + def givenCurriedFunctions_whenInvoked_thenCorrectValueReturned = { + // a curried function + def sum(f : Int => Int)(a : Int, + b : Int) : Int = + if (a > b) 0 else f(a) + sum(f)(a + 1, b) + + // another curried function + def mod(n : Int)(x : Int) = x % n + + // application of a curried function + assertEquals(1, mod(5)(6)) + + // partial application of curried function + // trailing underscore is required to make function type explicit + val sumMod5 = sum(mod(5)) _ + + assertEquals(10, sumMod5(6, 10)) + } +} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/IntSetUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/IntSetUnitTest.scala new file mode 100644 index 0000000000..5cc19e9215 --- /dev/null +++ b/core-scala/src/test/scala/com/baeldung/scala/IntSetUnitTest.scala @@ -0,0 +1,23 @@ +package com.baeldung.scala + +import scala.Range + +import org.junit.Assert.assertFalse +import org.junit.Test + +class IntSetUnitTest { + + @Test + def givenSetof1To10_whenContains11Called_thenFalse = { + + // Set up a set containing integers 1 to 10. + val set1To10 = + Range(1, 10) + .foldLeft(new EmptyIntSet() : IntSet) { + (x, y) => x incl y + } + + assertFalse(set1To10 contains 11) + } + +} \ No newline at end of file diff --git a/core-scala/src/test/scala/com/baeldung/scala/UtilsUnitTest.scala b/core-scala/src/test/scala/com/baeldung/scala/UtilsUnitTest.scala new file mode 100644 index 0000000000..47f9873aad --- /dev/null +++ b/core-scala/src/test/scala/com/baeldung/scala/UtilsUnitTest.scala @@ -0,0 +1,37 @@ +package com.baeldung.scala + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +import Utils.average +import Utils.fibonacci +import Utils.power +import Utils.randomLessThan + +class UtilsUnitTest { + + @Test + def whenAverageCalled_thenCorrectValueReturned() = { + assertEquals(15.0, average(10, 20), 1e-5) + } + + @Test + def whenRandomLessThanInvokedWithANumber_thenARandomLessThanItReturned = { + val d = 0.1 + assertTrue(randomLessThan(d) < d) + } + + @Test + def whenPowerInvokedWith2And3_then8Returned = { + assertEquals(8, power(2, 3)) + } + + @Test + def whenFibonacciCalled_thenCorrectValueReturned = { + assertEquals(1, fibonacci(0)) + assertEquals(1, fibonacci(1)) + assertEquals(fibonacci(6), + fibonacci(4) + fibonacci(5)) + } +} \ No newline at end of file diff --git a/guest/slf4j/guide/pom.xml b/guest/slf4j/guide/pom.xml new file mode 100644 index 0000000000..0db9b46247 --- /dev/null +++ b/guest/slf4j/guide/pom.xml @@ -0,0 +1,64 @@ + + + 4.0.0 + + com.stackify.slf4j.guide + slf4j-parent-module + 1.0.0-SNAPSHOT + pom + + + + org.springframework.boot + spring-boot-starter-parent + 2.0.6.RELEASE + + + + slf4j-logback + slf4j-log4j2 + slf4j-log4j + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + org.powermock + powermock-module-junit4 + ${powermock.version} + test + + + org.powermock + powermock-api-mockito2 + ${powermock.version} + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + UTF-8 + UTF-8 + 1.8 + 2.0.0-beta.5 + + diff --git a/spring-boot-h2/spring-boot-h2-database/.gitignore b/guest/slf4j/guide/slf4j-log4j/.gitignore similarity index 100% rename from spring-boot-h2/spring-boot-h2-database/.gitignore rename to guest/slf4j/guide/slf4j-log4j/.gitignore diff --git a/guest/slf4j/guide/slf4j-log4j/pom.xml b/guest/slf4j/guide/slf4j-log4j/pom.xml new file mode 100644 index 0000000000..0d08fa6191 --- /dev/null +++ b/guest/slf4j/guide/slf4j-log4j/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + + slf4j-log4j + 0.0.1-SNAPSHOT + jar + + + com.stackify.slf4j.guide + slf4j-parent-module + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.slf4j + slf4j-log4j12 + + + org.springframework.boot + spring-boot-starter-test + test + + + + 1.7.25 + + diff --git a/guest/slf4j/guide/slf4j-log4j/src/main/java/com/stackify/slf4j/guide/Application.java b/guest/slf4j/guide/slf4j-log4j/src/main/java/com/stackify/slf4j/guide/Application.java new file mode 100644 index 0000000000..01ccf519b3 --- /dev/null +++ b/guest/slf4j/guide/slf4j-log4j/src/main/java/com/stackify/slf4j/guide/Application.java @@ -0,0 +1,12 @@ +package com.stackify.slf4j.guide; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/guest/slf4j/guide/slf4j-log4j/src/main/java/com/stackify/slf4j/guide/controllers/SimpleController.java b/guest/slf4j/guide/slf4j-log4j/src/main/java/com/stackify/slf4j/guide/controllers/SimpleController.java new file mode 100644 index 0000000000..14f4439545 --- /dev/null +++ b/guest/slf4j/guide/slf4j-log4j/src/main/java/com/stackify/slf4j/guide/controllers/SimpleController.java @@ -0,0 +1,42 @@ +package com.stackify.slf4j.guide.controllers; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class SimpleController { + + Logger logger = LoggerFactory.getLogger(SimpleController.class); + + @GetMapping("/slf4j-guide-request") + public String processList(List list) { + logger.info("Client requested process the following list: {}", list); + try { + logger.debug("Starting process"); + // ...processing list here... + Thread.sleep(500); + } catch (RuntimeException | InterruptedException e) { + logger.error("There was an issue processing the list.", e); + } finally { + logger.info("Finished processing"); + } + return "done"; + } + + @GetMapping("/slf4j-guide-mdc-request") + public String clientMDCRequest(@RequestHeader String clientId) throws InterruptedException { + MDC.put("clientId", clientId); + logger.info("Client {} has made a request", clientId); + logger.info("Starting request"); + Thread.sleep(500); + logger.info("Finished request"); + MDC.clear(); + return "finished"; + } +} diff --git a/flyway/src/main/resources/application.properties b/guest/slf4j/guide/slf4j-log4j/src/main/resources/application.properties similarity index 100% rename from flyway/src/main/resources/application.properties rename to guest/slf4j/guide/slf4j-log4j/src/main/resources/application.properties diff --git a/guest/slf4j/guide/slf4j-log4j/src/main/resources/log4j.xml b/guest/slf4j/guide/slf4j-log4j/src/main/resources/log4j.xml new file mode 100644 index 0000000000..ea432bff77 --- /dev/null +++ b/guest/slf4j/guide/slf4j-log4j/src/main/resources/log4j.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/guest/slf4j/guide/slf4j-log4j/src/test/java/com/stackify/slf4j/guide/controllers/SimpleControllerIntegrationTest.java b/guest/slf4j/guide/slf4j-log4j/src/test/java/com/stackify/slf4j/guide/controllers/SimpleControllerIntegrationTest.java new file mode 100644 index 0000000000..991a1e2686 --- /dev/null +++ b/guest/slf4j/guide/slf4j-log4j/src/test/java/com/stackify/slf4j/guide/controllers/SimpleControllerIntegrationTest.java @@ -0,0 +1,80 @@ +package com.stackify.slf4j.guide.controllers; + +import static org.powermock.api.mockito.PowerMockito.doNothing; +import static org.powermock.api.mockito.PowerMockito.spy; + +import java.util.Collections; + +import org.apache.log4j.Level; +import org.apache.log4j.spi.LoggingEvent; +import org.assertj.core.api.Condition; +import org.assertj.core.api.SoftAssertions; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.MDC; + +import com.stackify.slf4j.guide.utils.ListAppender; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(MDC.class) +public class SimpleControllerIntegrationTest { + + private SimpleController controller = new SimpleController(); + + @Before + public void clearLogList() { + ListAppender.clearEventList(); + } + + @Test + public void whenSimpleRequestMade_thenAllRegularMessagesLogged() { + String output = controller.processList(Collections.emptyList()); + + SoftAssertions errorCollector = new SoftAssertions(); + errorCollector.assertThat(ListAppender.getEvents()) + .haveAtLeastOne(eventContains("Client requested process the following list: []", Level.INFO)) + .haveAtLeastOne(eventContains("Starting process", Level.DEBUG)) + .haveAtLeastOne(eventContains("Finished processing", Level.INFO)) + .haveExactly(0, eventOfLevel(Level.ERROR)); + errorCollector.assertThat(output) + .isEqualTo("done"); + errorCollector.assertAll(); + } + + @Test + public void givenClientId_whenMDCRequestMade_thenMessagesWithClientIdLogged() throws Exception { + // We avoid cleaning the context so tht we can check it afterwards + spy(MDC.class); + doNothing().when(MDC.class); + MDC.clear(); + String clientId = "id-1234"; + + String output = controller.clientMDCRequest(clientId); + + SoftAssertions errorCollector = new SoftAssertions(); + errorCollector.assertThat(ListAppender.getEvents()) + .allMatch(entry -> { + return clientId.equals(entry.getMDC("clientId")); + }) + .haveAtLeastOne(eventContains("Client id-1234 has made a request", Level.INFO)) + .haveAtLeastOne(eventContains("Starting request", Level.INFO)) + .haveAtLeastOne(eventContains("Finished request", Level.INFO)); + errorCollector.assertThat(output) + .isEqualTo("finished"); + errorCollector.assertAll(); + + } + + private Condition eventOfLevel(Level level) { + return eventContains(null, level); + } + + private Condition eventContains(String substring, Level level) { + + return new Condition(entry -> (substring == null || (entry.getRenderedMessage() != null && entry.getRenderedMessage() + .contains(substring))) && (level == null || level.equals(entry.getLevel())), String.format("entry with message '%s', level %s", substring, level)); + } +} diff --git a/guest/slf4j/guide/slf4j-log4j/src/test/java/com/stackify/slf4j/guide/utils/ListAppender.java b/guest/slf4j/guide/slf4j-log4j/src/test/java/com/stackify/slf4j/guide/utils/ListAppender.java new file mode 100644 index 0000000000..4ce9e73d6d --- /dev/null +++ b/guest/slf4j/guide/slf4j-log4j/src/test/java/com/stackify/slf4j/guide/utils/ListAppender.java @@ -0,0 +1,33 @@ +package com.stackify.slf4j.guide.utils; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.log4j.AppenderSkeleton; +import org.apache.log4j.spi.LoggingEvent; + +public class ListAppender extends AppenderSkeleton { + public static List events = new ArrayList(); + + @Override + public void close() { + } + + @Override + public boolean requiresLayout() { + return false; + } + + @Override + protected void append(LoggingEvent event) { + events.add(event); + } + + public static List getEvents() { + return events; + } + + public static void clearEventList() { + events.clear(); + } +} diff --git a/guest/slf4j/guide/slf4j-log4j/src/test/resources/log4j.xml b/guest/slf4j/guide/slf4j-log4j/src/test/resources/log4j.xml new file mode 100644 index 0000000000..10443e5eab --- /dev/null +++ b/guest/slf4j/guide/slf4j-log4j/src/test/resources/log4j.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/guest/slf4j/guide/slf4j-log4j2/.gitignore b/guest/slf4j/guide/slf4j-log4j2/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/guest/slf4j/guide/slf4j-log4j2/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/guest/slf4j/guide/slf4j-log4j2/pom.xml b/guest/slf4j/guide/slf4j-log4j2/pom.xml new file mode 100644 index 0000000000..643649335f --- /dev/null +++ b/guest/slf4j/guide/slf4j-log4j2/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + slf4j-log4j2 + 0.0.1-SNAPSHOT + jar + + + com.stackify.slf4j.guide + slf4j-parent-module + 1.0.0-SNAPSHOT + .. + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-log4j2 + + + org.springframework.boot + spring-boot-starter-test + test + + + org.apache.logging.log4j + log4j-core + ${log4j.version} + test-jar + + + org.apache.logging.log4j + log4j-api + ${log4j.version} + test-jar + + + + + 2.11.0 + + diff --git a/guest/slf4j/guide/slf4j-log4j2/src/main/java/com/stackify/slf4j/guide/Application.java b/guest/slf4j/guide/slf4j-log4j2/src/main/java/com/stackify/slf4j/guide/Application.java new file mode 100644 index 0000000000..01ccf519b3 --- /dev/null +++ b/guest/slf4j/guide/slf4j-log4j2/src/main/java/com/stackify/slf4j/guide/Application.java @@ -0,0 +1,12 @@ +package com.stackify.slf4j.guide; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/guest/slf4j/guide/slf4j-log4j2/src/main/java/com/stackify/slf4j/guide/controllers/SimpleController.java b/guest/slf4j/guide/slf4j-log4j2/src/main/java/com/stackify/slf4j/guide/controllers/SimpleController.java new file mode 100644 index 0000000000..14f4439545 --- /dev/null +++ b/guest/slf4j/guide/slf4j-log4j2/src/main/java/com/stackify/slf4j/guide/controllers/SimpleController.java @@ -0,0 +1,42 @@ +package com.stackify.slf4j.guide.controllers; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class SimpleController { + + Logger logger = LoggerFactory.getLogger(SimpleController.class); + + @GetMapping("/slf4j-guide-request") + public String processList(List list) { + logger.info("Client requested process the following list: {}", list); + try { + logger.debug("Starting process"); + // ...processing list here... + Thread.sleep(500); + } catch (RuntimeException | InterruptedException e) { + logger.error("There was an issue processing the list.", e); + } finally { + logger.info("Finished processing"); + } + return "done"; + } + + @GetMapping("/slf4j-guide-mdc-request") + public String clientMDCRequest(@RequestHeader String clientId) throws InterruptedException { + MDC.put("clientId", clientId); + logger.info("Client {} has made a request", clientId); + logger.info("Starting request"); + Thread.sleep(500); + logger.info("Finished request"); + MDC.clear(); + return "finished"; + } +} diff --git a/guest/slf4j/guide/slf4j-log4j2/src/main/resources/application.properties b/guest/slf4j/guide/slf4j-log4j2/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/guest/slf4j/guide/slf4j-log4j2/src/main/resources/log4j2-spring.xml b/guest/slf4j/guide/slf4j-log4j2/src/main/resources/log4j2-spring.xml new file mode 100644 index 0000000000..7d1494c7a6 --- /dev/null +++ b/guest/slf4j/guide/slf4j-log4j2/src/main/resources/log4j2-spring.xml @@ -0,0 +1,28 @@ + + + ???? + %5p + yyyy-MM-dd HH:mm:ss.SSS + %clr{%d{${LOG_DATEFORMAT_PATTERN}}}{faint} %clr{${LOG_LEVEL_PATTERN}} %clr{${sys:PID}}{magenta} + %clr{---}{faint} %clr{%X{clientId}}{red}%clr{@%15.15t}{faint} %clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/guest/slf4j/guide/slf4j-log4j2/src/test/java/com/stackify/slf4j/guide/controllers/SimpleControllerIntegrationTest.java b/guest/slf4j/guide/slf4j-log4j2/src/test/java/com/stackify/slf4j/guide/controllers/SimpleControllerIntegrationTest.java new file mode 100644 index 0000000000..f41c857533 --- /dev/null +++ b/guest/slf4j/guide/slf4j-log4j2/src/test/java/com/stackify/slf4j/guide/controllers/SimpleControllerIntegrationTest.java @@ -0,0 +1,81 @@ +package com.stackify.slf4j.guide.controllers; + +import java.util.Collections; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.junit.LoggerContextRule; +import org.apache.logging.log4j.test.appender.ListAppender; +import org.assertj.core.api.Condition; +import org.assertj.core.api.SoftAssertions; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Test; + +public class SimpleControllerIntegrationTest { + + private static ListAppender appender; + private SimpleController controller = new SimpleController(); + + @ClassRule + public static LoggerContextRule init = new LoggerContextRule("log4j2-test.xml"); + + @BeforeClass + public static void setupLogging() { + appender = init.getListAppender("ListAppender"); + } + + @Before + public void clearAppender() { + appender.clear(); + } + + @Test + public void whenSimpleRequestMade_thenAllRegularMessagesLogged() { + String output = controller.processList(Collections.emptyList()); + + SoftAssertions errorCollector = new SoftAssertions(); + errorCollector.assertThat(appender.getEvents()) + .haveAtLeastOne(eventContains("Client requested process the following list: []", Level.INFO)) + .haveAtLeastOne(eventContains("Starting process", Level.DEBUG)) + .haveAtLeastOne(eventContains("Finished processing", Level.INFO)) + .haveExactly(0, eventOfLevel(Level.ERROR)); + errorCollector.assertThat(output) + .isEqualTo("done"); + errorCollector.assertAll(); + } + + @Test + public void givenClientId_whenMDCRequestMade_thenMessagesWithClientIdLogged() throws Exception { + String clientId = "id-1234"; + + String output = controller.clientMDCRequest(clientId); + + SoftAssertions errorCollector = new SoftAssertions(); + errorCollector.assertThat(appender.getEvents()) + .allMatch(entry -> { + return clientId.equals(entry.getContextData() + .getValue("clientId")); + }) + .haveAtLeastOne(eventContains("Client id-1234 has made a request", Level.INFO)) + .haveAtLeastOne(eventContains("Starting request", Level.INFO)) + .haveAtLeastOne(eventContains("Finished request", Level.INFO)); + errorCollector.assertThat(output) + .isEqualTo("finished"); + errorCollector.assertAll(); + } + + private Condition eventOfLevel(Level level) { + return eventContains(null, level); + } + + private Condition eventContains(String substring, Level level) { + + return new Condition(entry -> (substring == null || (entry.getMessage() + .getFormattedMessage() != null && entry.getMessage() + .getFormattedMessage() + .contains(substring))) + && (level == null || level.equals(entry.getLevel())), String.format("entry with message '%s', level %s", substring, level)); + } +} diff --git a/guest/slf4j/guide/slf4j-log4j2/src/test/resources/log4j2-test.xml b/guest/slf4j/guide/slf4j-log4j2/src/test/resources/log4j2-test.xml new file mode 100644 index 0000000000..2ca386f7f6 --- /dev/null +++ b/guest/slf4j/guide/slf4j-log4j2/src/test/resources/log4j2-test.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/guest/slf4j/guide/slf4j-logback/.gitignore b/guest/slf4j/guide/slf4j-logback/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/guest/slf4j/guide/slf4j-logback/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/guest/slf4j/guide/slf4j-logback/pom.xml b/guest/slf4j/guide/slf4j-logback/pom.xml new file mode 100644 index 0000000000..e8aebf0ef6 --- /dev/null +++ b/guest/slf4j/guide/slf4j-logback/pom.xml @@ -0,0 +1,32 @@ + + + 4.0.0 + + slf4j-logback + 0.0.1-SNAPSHOT + jar + + + com.stackify.slf4j.guide + slf4j-parent-module + 1.0.0-SNAPSHOT + .. + + + + + org.slf4j + slf4j-ext + + + ch.qos.cal10n + cal10n-api + ${cal10n.version} + + + + + 0.8.1 + + diff --git a/guest/slf4j/guide/slf4j-logback/src/main/java/com/stackify/slf4j/guide/Application.java b/guest/slf4j/guide/slf4j-logback/src/main/java/com/stackify/slf4j/guide/Application.java new file mode 100644 index 0000000000..01ccf519b3 --- /dev/null +++ b/guest/slf4j/guide/slf4j-logback/src/main/java/com/stackify/slf4j/guide/Application.java @@ -0,0 +1,12 @@ +package com.stackify.slf4j.guide; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/guest/slf4j/guide/slf4j-logback/src/main/java/com/stackify/slf4j/guide/controllers/SimpleController.java b/guest/slf4j/guide/slf4j-logback/src/main/java/com/stackify/slf4j/guide/controllers/SimpleController.java new file mode 100644 index 0000000000..1fab675c94 --- /dev/null +++ b/guest/slf4j/guide/slf4j-logback/src/main/java/com/stackify/slf4j/guide/controllers/SimpleController.java @@ -0,0 +1,133 @@ +package com.stackify.slf4j.guide.controllers; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; +import org.slf4j.cal10n.LocLogger; +import org.slf4j.cal10n.LocLoggerFactory; +import org.slf4j.ext.EventData; +import org.slf4j.ext.EventLogger; +import org.slf4j.profiler.Profiler; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.stackify.slf4j.guide.l10n.Messages; + +import ch.qos.cal10n.IMessageConveyor; +import ch.qos.cal10n.MessageConveyor; + +@RestController +public class SimpleController { + + Logger logger = LoggerFactory.getLogger(SimpleController.class); + + @GetMapping("/slf4j-guide-request") + public String processList(List list) { + logger.info("Client requested process the following list: {}", list); + try { + logger.debug("Starting process"); + // ...processing list here... + Thread.sleep(500); + } catch (RuntimeException | InterruptedException e) { + logger.error("There was an issue processing the list.", e); + } finally { + logger.info("Finished processing"); + } + return "done"; + } + + @GetMapping("/slf4j-guide-mdc-request") + public String clientMDCRequest(@RequestHeader String clientId) throws InterruptedException { + MDC.put("clientId", clientId); + logger.info("Client {} has made a request", clientId); + logger.info("Starting request"); + Thread.sleep(500); + logger.info("Finished request"); + MDC.clear(); + return "finished"; + } + + @GetMapping("/slf4j-guide-marker-request") + public String clientMarkerRequest() throws InterruptedException { + logger.info("client has made a request"); + Marker myMarker = MarkerFactory.getMarker("MYMARKER"); + logger.info(myMarker, "Starting request"); + Thread.sleep(500); + logger.debug(myMarker, "Finished request"); + return "finished"; + } + + @GetMapping("/slf4j-guide-profiler-request") + public String clientProfilerRequest() { + logger.info("client has made a request"); + Profiler myProfiler = new Profiler("MYPROFILER"); + // Associate the logger to handle the output( for testing purposes here) + myProfiler.setLogger(logger); + + myProfiler.start("List generation process"); + List list = generateList(); + + myProfiler.start("List sorting process"); + Collections.sort(list); + + // Use the log() method instead of print() to use the logger (for testing purposes here) + myProfiler.stop() + .log(); + return "finished"; + } + + private List generateList() { + List generated = new ArrayList<>(); + for (int i = 0; i < 5000; i++) { + generated.add(ThreadLocalRandom.current() + .nextInt(2000)); + } + return generated; + } + + @GetMapping("/slf4j-guide-event-request") + public String clientEventRequest(@RequestParam("sender") String sender, @RequestParam("receiver") String receiver) { + logger.info("sending from {} to {}", sender, receiver); + + // ...sending process... + + EventData data = new EventData(); + data.setEventDateTime(new Date()); + data.setEventType("sending"); + String confirm = UUID.randomUUID() + .toString(); + data.setEventId(confirm); + data.put("from", sender); + data.put("to", receiver); + EventLogger.logEvent(data); + + return "finished"; + } + + @GetMapping("/slf4j-guide-locale-request") + public String clientLocaleRequest(@RequestHeader("Accept-Language") String localeHeader) { + List list = Locale.LanguageRange.parse(localeHeader); + Locale locale = Locale.lookup(list, Arrays.asList(Locale.getAvailableLocales())); + IMessageConveyor messageConveyor = new MessageConveyor(locale); + LocLoggerFactory llFactory = new LocLoggerFactory(messageConveyor); + LocLogger locLogger = llFactory.getLocLogger(this.getClass()); + locLogger.info(Messages.CLIENT_REQUEST, "parametrizedClientId", localeHeader); + locLogger.debug(Messages.REQUEST_STARTED); + locLogger.info(Messages.REQUEST_FINISHED); + return "finished"; + } + +} diff --git a/guest/slf4j/guide/slf4j-logback/src/main/java/com/stackify/slf4j/guide/l10n/Messages.java b/guest/slf4j/guide/slf4j-logback/src/main/java/com/stackify/slf4j/guide/l10n/Messages.java new file mode 100644 index 0000000000..e4aacaf3be --- /dev/null +++ b/guest/slf4j/guide/slf4j-logback/src/main/java/com/stackify/slf4j/guide/l10n/Messages.java @@ -0,0 +1,11 @@ +package com.stackify.slf4j.guide.l10n; + +import ch.qos.cal10n.BaseName; +import ch.qos.cal10n.Locale; +import ch.qos.cal10n.LocaleData; + +@BaseName("messages") +@LocaleData({ @Locale("en_US"), @Locale("es_ES") }) +public enum Messages { + CLIENT_REQUEST, REQUEST_STARTED, REQUEST_FINISHED +} diff --git a/guest/slf4j/guide/slf4j-logback/src/main/java/com/stackify/slf4j/guide/xlogger/XLoggerController.java b/guest/slf4j/guide/slf4j-logback/src/main/java/com/stackify/slf4j/guide/xlogger/XLoggerController.java new file mode 100644 index 0000000000..8690c0ebc9 --- /dev/null +++ b/guest/slf4j/guide/slf4j-logback/src/main/java/com/stackify/slf4j/guide/xlogger/XLoggerController.java @@ -0,0 +1,28 @@ +package com.stackify.slf4j.guide.xlogger; + +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class XLoggerController { + + private XLogger logger = XLoggerFactory.getXLogger(XLoggerController.class); + + @GetMapping("/slf4j-guide-xlogger-request") + public Integer clientXLoggerRequest(@RequestParam("queryParam") Integer queryParam) { + logger.info("Starting process"); + logger.entry(queryParam); + Integer rest = 0; + try { + rest = queryParam % 3; + } catch (RuntimeException anyException) { + logger.catching(anyException); + } + logger.exit(rest); + return rest; + } + +} diff --git a/guest/slf4j/guide/slf4j-logback/src/main/resources/application.properties b/guest/slf4j/guide/slf4j-logback/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/guest/slf4j/guide/slf4j-logback/src/main/resources/logback-spring.xml b/guest/slf4j/guide/slf4j-logback/src/main/resources/logback-spring.xml new file mode 100644 index 0000000000..112e79c340 --- /dev/null +++ b/guest/slf4j/guide/slf4j-logback/src/main/resources/logback-spring.xml @@ -0,0 +1,11 @@ + + + + + %marker %d{yyyy-MM-dd HH:mm:ss.SSS} -%5p %X{clientId}@%15.15t %-40.40logger{39} : %m%n + + + + + + \ No newline at end of file diff --git a/guest/slf4j/guide/slf4j-logback/src/main/resources/messages_en_US.properties b/guest/slf4j/guide/slf4j-logback/src/main/resources/messages_en_US.properties new file mode 100644 index 0000000000..a35dd60da3 --- /dev/null +++ b/guest/slf4j/guide/slf4j-logback/src/main/resources/messages_en_US.properties @@ -0,0 +1,3 @@ +CLIENT_REQUEST=Client {0} has made a request using locale {1} +REQUEST_STARTED=Request started +REQUEST_FINISHED=Request finished \ No newline at end of file diff --git a/guest/slf4j/guide/slf4j-logback/src/main/resources/messages_es_ES.properties b/guest/slf4j/guide/slf4j-logback/src/main/resources/messages_es_ES.properties new file mode 100644 index 0000000000..6cdab09236 --- /dev/null +++ b/guest/slf4j/guide/slf4j-logback/src/main/resources/messages_es_ES.properties @@ -0,0 +1,3 @@ +CLIENT_REQUEST=El cliente {0} ha realizado una solicitud usando locale {1} +REQUEST_STARTED=Solicitud iniciada +REQUEST_FINISHED=Solicitud finalizada \ No newline at end of file diff --git a/guest/slf4j/guide/slf4j-logback/src/test/java/com/stackify/slf4j/guide/controllers/SimpleControllerIntegrationTest.java b/guest/slf4j/guide/slf4j-logback/src/test/java/com/stackify/slf4j/guide/controllers/SimpleControllerIntegrationTest.java new file mode 100644 index 0000000000..b870cc9ebd --- /dev/null +++ b/guest/slf4j/guide/slf4j-logback/src/test/java/com/stackify/slf4j/guide/controllers/SimpleControllerIntegrationTest.java @@ -0,0 +1,163 @@ +package com.stackify.slf4j.guide.controllers; + +import static org.powermock.api.mockito.PowerMockito.doNothing; +import static org.powermock.api.mockito.PowerMockito.spy; + +import java.util.Collections; + +import org.assertj.core.api.Condition; +import org.assertj.core.api.SoftAssertions; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.MDC; + +import com.stackify.slf4j.guide.utils.ListAppender; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(MDC.class) +public class SimpleControllerIntegrationTest { + + SimpleController controller = new SimpleController(); + + @Before + public void clearLogList() { + ListAppender.clearEventList(); + } + + @Test + public void whenSimpleRequestMade_thenAllRegularMessagesLogged() { + String output = controller.processList(Collections.emptyList()); + + SoftAssertions errorCollector = new SoftAssertions(); + errorCollector.assertThat(ListAppender.getEvents()) + .haveAtLeastOne(eventContains("Client requested process the following list: []", Level.INFO)) + .haveAtLeastOne(eventContains("Starting process", Level.DEBUG)) + .haveAtLeastOne(eventContains("Finished processing", Level.INFO)) + .haveExactly(0, eventOfLevel(Level.ERROR)); + errorCollector.assertThat(output) + .isEqualTo("done"); + errorCollector.assertAll(); + } + + @Test + public void givenClientId_whenMDCRequestMade_thenMessagesWithClientIdLogged() throws Exception { + // We avoid cleaning the context so tht we can check it afterwards + spy(MDC.class); + doNothing().when(MDC.class); + MDC.clear(); + String clientId = "id-1234"; + + String output = controller.clientMDCRequest(clientId); + + SoftAssertions errorCollector = new SoftAssertions(); + errorCollector.assertThat(ListAppender.getEvents()) + .allMatch(entry -> { + return clientId.equals(entry.getMDCPropertyMap() + .get("clientId")); + }) + .haveAtLeastOne(eventContains("Client id-1234 has made a request", Level.INFO)) + .haveAtLeastOne(eventContains("Starting request", Level.INFO)) + .haveAtLeastOne(eventContains("Finished request", Level.INFO)); + errorCollector.assertThat(output) + .isEqualTo("finished"); + errorCollector.assertAll(); + } + + @Test + public void whenMarkerRequestMade_thenMessagesWithMarkerLogged() throws Exception { + String output = controller.clientMarkerRequest(); + + SoftAssertions errorCollector = new SoftAssertions(); + errorCollector.assertThat(ListAppender.getEvents()) + .haveAtLeastOne(eventContains("client has made a request", Level.INFO)) + .haveAtLeastOne(eventContains("Starting request", Level.INFO, "MYMARKER")) + .haveAtLeastOne(eventContains("Finished request", Level.DEBUG, "MYMARKER")) + .haveExactly(2, eventContains(null, null, "MYMARKER")); + errorCollector.assertThat(output) + .isEqualTo("finished"); + errorCollector.assertAll(); + } + + @Test + public void whenProfilerRequestMade_thenMessagesWithPerformanceLogged() throws Exception { + String output = controller.clientProfilerRequest(); + + SoftAssertions errorCollector = new SoftAssertions(); + errorCollector.assertThat(ListAppender.getEvents()) + .haveAtLeastOne(eventContains("client has made a request", Level.INFO)) + .haveAtLeastOne(eventContains("Profiler [MYPROFILER]", Level.DEBUG)); + errorCollector.assertThat(output) + .isEqualTo("finished"); + errorCollector.assertAll(); + } + + @Test + public void whenEventRequestMade_thenMessagesWithEventLogged() throws Exception { + String sender = "sender"; + String receiver = "receiver"; + String output = controller.clientEventRequest(sender, receiver); + + SoftAssertions errorCollector = new SoftAssertions(); + errorCollector.assertThat(ListAppender.getEvents()) + .haveAtLeastOne(eventContains("sending from sender to receiver", Level.INFO)) + .haveAtLeastOne(eventContains("", Level.INFO)) + .haveAtLeastOne(eventContains("sender", Level.INFO)) + .haveAtLeastOne(eventContains("receiver", Level.INFO)); + errorCollector.assertThat(output) + .isEqualTo("finished"); + errorCollector.assertAll(); + } + + @Test + public void givenESLocale_whenLocaleRequestMade_thenMessagesWithEventLogged() throws Exception { + String locale = "es-ES"; + String output = controller.clientLocaleRequest(locale); + + SoftAssertions errorCollector = new SoftAssertions(); + errorCollector.assertThat(ListAppender.getEvents()) + .haveAtLeastOne(eventContains("El cliente parametrizedClientId ha realizado una solicitud usando locale es-ES", Level.INFO)) + .haveAtLeastOne(eventContains("Solicitud iniciada", Level.DEBUG)) + .haveAtLeastOne(eventContains("Solicitud finalizada", Level.INFO)); + errorCollector.assertThat(output) + .isEqualTo("finished"); + errorCollector.assertAll(); + } + + @Test + public void givenENLocale_whenLocaleRequestMade_thenMessagesWithEventLogged() throws Exception { + String locale = "en-US"; + String output = controller.clientLocaleRequest(locale); + + SoftAssertions errorCollector = new SoftAssertions(); + errorCollector.assertThat(ListAppender.getEvents()) + .haveAtLeastOne(eventContains("Client parametrizedClientId has made a request using locale en-US", Level.INFO)) + .haveAtLeastOne(eventContains("Request started", Level.DEBUG)) + .haveAtLeastOne(eventContains("Request finished", Level.INFO)); + errorCollector.assertThat(output) + .isEqualTo("finished"); + errorCollector.assertAll(); + } + + private Condition eventContains(String substring, Level level) { + return eventContains(substring, level, null); + } + + private Condition eventOfLevel(Level level) { + return eventContains(null, level, null); + } + + private Condition eventContains(String substring, Level level, String markerName) { + + return new Condition(entry -> (substring == null || (entry.getFormattedMessage() != null && entry.getFormattedMessage() + .contains(substring))) && (level == null || level.equals(entry.getLevel())) && (markerName == null || (entry.getMarker() != null + && markerName.equals(entry.getMarker() + .getName()))), + String.format("entry with message '%s', level %s and marker %s", substring, level, markerName)); + } +} diff --git a/guest/slf4j/guide/slf4j-logback/src/test/java/com/stackify/slf4j/guide/utils/ListAppender.java b/guest/slf4j/guide/slf4j-logback/src/test/java/com/stackify/slf4j/guide/utils/ListAppender.java new file mode 100644 index 0000000000..e6d4e47fb2 --- /dev/null +++ b/guest/slf4j/guide/slf4j-logback/src/test/java/com/stackify/slf4j/guide/utils/ListAppender.java @@ -0,0 +1,25 @@ +package com.stackify.slf4j.guide.utils; + +import java.util.ArrayList; +import java.util.List; + +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; + +public class ListAppender extends AppenderBase { + + static private List events = new ArrayList<>(); + + @Override + protected void append(ILoggingEvent eventObject) { + events.add(eventObject); + } + + public static List getEvents() { + return events; + } + + public static void clearEventList() { + events.clear(); + } +} diff --git a/guest/slf4j/guide/slf4j-logback/src/test/resources/logback-test.xml b/guest/slf4j/guide/slf4j-logback/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..90168a0fea --- /dev/null +++ b/guest/slf4j/guide/slf4j-logback/src/test/resources/logback-test.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/helidon/helidon-mp/pom.xml b/helidon/helidon-mp/pom.xml new file mode 100644 index 0000000000..1ec1131a67 --- /dev/null +++ b/helidon/helidon-mp/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + + helidon-mp + + + com.baeldung.helidon + helidon + 1.0.0-SNAPSHOT + + + + + io.helidon.microprofile.bundles + helidon-microprofile-1.2 + 0.10.4 + + + org.glassfish.jersey.media + jersey-media-json-binding + 2.26 + + + + diff --git a/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/LibraryApplication.java b/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/LibraryApplication.java new file mode 100644 index 0000000000..58913c8b39 --- /dev/null +++ b/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/LibraryApplication.java @@ -0,0 +1,26 @@ +package com.baeldung.microprofile; + +import com.baeldung.microprofile.web.BookEndpoint; +import io.helidon.common.CollectionsHelper; +import io.helidon.microprofile.server.Server; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; +import java.util.Set; + +@ApplicationPath("/library") +public class LibraryApplication extends Application { + + @Override + public Set> getClasses() { + return CollectionsHelper.setOf(BookEndpoint.class); + } + + public static void main(String... args) { + Server server = Server.builder() + .addApplication(LibraryApplication.class) + .port(9080) + .build(); + server.start(); + } +} diff --git a/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/model/Book.java b/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/model/Book.java new file mode 100644 index 0000000000..44b7f5428d --- /dev/null +++ b/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/model/Book.java @@ -0,0 +1,50 @@ +package com.baeldung.microprofile.model; + +public class Book { + + private String id; + private String isbn; + private String name; + private String author; + private Integer pages; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getIsbn() { + return isbn; + } + + public void setIsbn(String isbn) { + this.isbn = isbn; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public Integer getPages() { + return pages; + } + + public void setPages(Integer pages) { + this.pages = pages; + } +} diff --git a/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/providers/BookListMessageBodyWriter.java b/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/providers/BookListMessageBodyWriter.java new file mode 100644 index 0000000000..f7d0bfc5f7 --- /dev/null +++ b/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/providers/BookListMessageBodyWriter.java @@ -0,0 +1,42 @@ +package com.baeldung.microprofile.providers; + +import com.baeldung.microprofile.model.Book; +import com.baeldung.microprofile.util.BookMapper; + +import javax.json.Json; +import javax.json.JsonArray; +import javax.json.JsonWriter; +import javax.ws.rs.Produces; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.MessageBodyWriter; +import javax.ws.rs.ext.Provider; +import java.io.IOException; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.List; + +@Provider +@Produces(MediaType.APPLICATION_JSON) +public class BookListMessageBodyWriter implements MessageBodyWriter> { + + @Override + public boolean isWriteable(Class clazz, Type genericType, Annotation[] annotations, MediaType mediaType) { + return true; + } + + @Override + public long getSize(List books, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { + return 0; + } + + @Override + public void writeTo(List books, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { + JsonWriter jsonWriter = Json.createWriter(entityStream); + JsonArray jsonArray = BookMapper.map(books); + jsonWriter.writeArray(jsonArray); + jsonWriter.close(); + } +} diff --git a/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/providers/BookMessageBodyReader.java b/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/providers/BookMessageBodyReader.java new file mode 100644 index 0000000000..26ce4c1b64 --- /dev/null +++ b/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/providers/BookMessageBodyReader.java @@ -0,0 +1,30 @@ +package com.baeldung.microprofile.providers; + +import com.baeldung.microprofile.model.Book; +import com.baeldung.microprofile.util.BookMapper; + +import javax.ws.rs.Consumes; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.MessageBodyReader; +import javax.ws.rs.ext.Provider; +import java.io.IOException; +import java.io.InputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +@Provider +@Consumes(MediaType.APPLICATION_JSON) +public class BookMessageBodyReader implements MessageBodyReader { + + @Override + public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { + return type.equals(Book.class); + } + + @Override + public Book readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { + return BookMapper.map(entityStream); + } +} \ No newline at end of file diff --git a/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/providers/BookMessageBodyWriter.java b/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/providers/BookMessageBodyWriter.java new file mode 100644 index 0000000000..9bc6e89958 --- /dev/null +++ b/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/providers/BookMessageBodyWriter.java @@ -0,0 +1,57 @@ +package com.baeldung.microprofile.providers; + +import com.baeldung.microprofile.model.Book; +import com.baeldung.microprofile.util.BookMapper; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonWriter; +import javax.ws.rs.Produces; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.MessageBodyWriter; +import javax.ws.rs.ext.Provider; +import java.io.IOException; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +@Provider +@Produces(MediaType.APPLICATION_JSON) +public class BookMessageBodyWriter implements MessageBodyWriter { + @Override + public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { + return type.equals(Book.class); + } + + /* + Deprecated in JAX RS 2.0 + */ + @Override + public long getSize(Book book, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { + return 0; + } + + /** + * Marsahl Book to OutputStream + * + * @param book + * @param type + * @param genericType + * @param annotations + * @param mediaType + * @param httpHeaders + * @param entityStream + * @throws IOException + * @throws WebApplicationException + */ + @Override + public void writeTo(Book book, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { + JsonWriter jsonWriter = Json.createWriter(entityStream); + JsonObject jsonObject = BookMapper.map(book); + jsonWriter.writeObject(jsonObject); + jsonWriter.close(); + } + +} diff --git a/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/repo/BookManager.java b/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/repo/BookManager.java new file mode 100644 index 0000000000..924cf0ce71 --- /dev/null +++ b/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/repo/BookManager.java @@ -0,0 +1,53 @@ +package com.baeldung.microprofile.repo; + +import com.baeldung.microprofile.model.Book; + +import javax.enterprise.context.ApplicationScoped; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicInteger; + +@ApplicationScoped +public class BookManager { + + private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM"); + private AtomicInteger bookIdGenerator = new AtomicInteger(0); + + private ConcurrentMap inMemoryStore = new ConcurrentHashMap<>(); + + public BookManager() { + Book book = new Book(); + book.setId(getNextId()); + book.setName("Building Microservice With Eclipse MicroProfile"); + book.setIsbn("1"); + book.setAuthor("baeldung"); + book.setPages(420); + inMemoryStore.put(book.getId(), book); + } + + private String getNextId() { + String date = LocalDate.now().format(formatter); + return String.format("%04d-%s", bookIdGenerator.incrementAndGet(), date); + } + + public String add(Book book) { + String id = getNextId(); + book.setId(id); + inMemoryStore.put(id, book); + return id; + } + + public Book get(String id) { + return inMemoryStore.get(id); + } + + public List getAll() { + List books = new ArrayList<>(); + books.addAll(inMemoryStore.values()); + return books; + } +} diff --git a/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/util/BookMapper.java b/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/util/BookMapper.java new file mode 100644 index 0000000000..861b172299 --- /dev/null +++ b/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/util/BookMapper.java @@ -0,0 +1,72 @@ +package com.baeldung.microprofile.util; + +import com.baeldung.microprofile.model.Book; + +import javax.json.*; +import java.io.InputStream; +import java.util.List; + +public class BookMapper { + + public static JsonObject map(Book book) { + JsonObjectBuilder builder = Json.createObjectBuilder(); + addValue(builder, "id", book.getId()); + addValue(builder, "isbn", book.getIsbn()); + addValue(builder, "name", book.getName()); + addValue(builder, "author", book.getAuthor()); + addValue(builder, "pages", book.getPages()); + return builder.build(); + } + + private static void addValue(JsonObjectBuilder builder, String key, Object value) { + if (value != null) { + builder.add(key, value.toString()); + } else { + builder.addNull(key); + } + } + + public static JsonArray map(List books) { + final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder(); + books.forEach(book -> { + JsonObject jsonObject = map(book); + arrayBuilder.add(jsonObject); + }); + return arrayBuilder.build(); + } + + public static Book map(InputStream is) { + try(JsonReader jsonReader = Json.createReader(is)) { + JsonObject jsonObject = jsonReader.readObject(); + Book book = new Book(); + book.setId(getStringFromJson("id", jsonObject)); + book.setIsbn(getStringFromJson("isbn", jsonObject)); + book.setName(getStringFromJson("name", jsonObject)); + book.setAuthor(getStringFromJson("author", jsonObject)); + book.setPages(getIntFromJson("pages",jsonObject)); + return book; + } + } + + private static String getStringFromJson(String key, JsonObject json) { + String returnedString = null; + if (json.containsKey(key)) { + JsonString value = json.getJsonString(key); + if (value != null) { + returnedString = value.getString(); + } + } + return returnedString; + } + + private static Integer getIntFromJson(String key, JsonObject json) { + Integer returnedValue = null; + if (json.containsKey(key)) { + JsonNumber value = json.getJsonNumber(key); + if (value != null) { + returnedValue = value.intValue(); + } + } + return returnedValue; + } +} diff --git a/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/web/BookEndpoint.java b/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/web/BookEndpoint.java new file mode 100644 index 0000000000..13143a5644 --- /dev/null +++ b/helidon/helidon-mp/src/main/java/com/baeldung/microprofile/web/BookEndpoint.java @@ -0,0 +1,42 @@ +package com.baeldung.microprofile.web; + +import com.baeldung.microprofile.model.Book; +import com.baeldung.microprofile.repo.BookManager; + +import javax.enterprise.context.RequestScoped; +import javax.inject.Inject; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; + +@Path("books") +@RequestScoped +public class BookEndpoint { + + @Inject + private BookManager bookManager; + + @GET + @Path("{id}") + @Produces(MediaType.APPLICATION_JSON) + public Response getBook(@PathParam("id") String id) { + Book book = bookManager.get(id); + return Response.ok(book).build(); + } + + @GET + @Produces(MediaType.APPLICATION_JSON) + public Response getAllBooks() { + return Response.ok(bookManager.getAll()).build(); + } + + @POST + @Consumes(MediaType.APPLICATION_JSON) + public Response add(Book book) { + String bookId = bookManager.add(book); + return Response.created( + UriBuilder.fromResource(this.getClass()).path(bookId).build()) + .build(); + } +} diff --git a/helidon/helidon-mp/src/main/resources/META-INF/beans.xml b/helidon/helidon-mp/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..faae50dfc2 --- /dev/null +++ b/helidon/helidon-mp/src/main/resources/META-INF/beans.xml @@ -0,0 +1,7 @@ + + diff --git a/hibernate5/src/main/resources/logback.xml b/helidon/helidon-mp/src/main/resources/logback.xml similarity index 100% rename from hibernate5/src/main/resources/logback.xml rename to helidon/helidon-mp/src/main/resources/logback.xml diff --git a/helidon/helidon-se/pom.xml b/helidon/helidon-se/pom.xml new file mode 100644 index 0000000000..5e14ecb81c --- /dev/null +++ b/helidon/helidon-se/pom.xml @@ -0,0 +1,64 @@ + + + 4.0.0 + + helidon-se + + + com.baeldung.helidon + helidon + 1.0.0-SNAPSHOT + + + + 0.10.4 + + + + + + io.helidon.config + helidon-config-yaml + ${helidon.version} + + + + + io.helidon.webserver + helidon-webserver + ${helidon.version} + + + io.helidon.webserver + helidon-webserver-netty + ${helidon.version} + runtime + + + io.helidon.webserver + helidon-webserver-json + ${helidon.version} + + + + + io.helidon.security + helidon-security + ${helidon.version} + + + io.helidon.security + helidon-security-provider-http-auth + ${helidon.version} + + + io.helidon.security + helidon-security-integration-webserver + ${helidon.version} + + + + + \ No newline at end of file diff --git a/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/config/ConfigApplication.java b/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/config/ConfigApplication.java new file mode 100644 index 0000000000..acfcdb2373 --- /dev/null +++ b/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/config/ConfigApplication.java @@ -0,0 +1,29 @@ +package com.baeldung.helidon.se.config; + +import io.helidon.config.Config; +import io.helidon.config.ConfigSources; +import io.helidon.config.spi.ConfigSource; + +public class ConfigApplication { + + public static void main(String... args) throws Exception { + + ConfigSource configSource = ConfigSources.classpath("application.yaml").build(); + Config config = Config.builder() + .disableSystemPropertiesSource() + .disableEnvironmentVariablesSource() + .sources(configSource) + .build(); + + int port = config.get("server.port").asInt(); + int pageSize = config.get("web.page-size").asInt(); + boolean debug = config.get("web.debug").asBoolean(); + String userHome = config.get("user.home").asString(); + + System.out.println("port: " + port); + System.out.println("pageSize: " + pageSize); + System.out.println("debug: " + debug); + System.out.println("userHome: " + userHome); + } + +} diff --git a/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/Book.java b/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/Book.java new file mode 100644 index 0000000000..9a591bcc73 --- /dev/null +++ b/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/Book.java @@ -0,0 +1,49 @@ +package com.baeldung.helidon.se.routing; + +public class Book { + private String id; + private String isbn; + private String name; + private String author; + private Integer pages; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getIsbn() { + return isbn; + } + + public void setIsbn(String isbn) { + this.isbn = isbn; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public Integer getPages() { + return pages; + } + + public void setPages(Integer pages) { + this.pages = pages; + } +} \ No newline at end of file diff --git a/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/BookManager.java b/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/BookManager.java new file mode 100644 index 0000000000..2e6e694041 --- /dev/null +++ b/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/BookManager.java @@ -0,0 +1,49 @@ +package com.baeldung.helidon.se.routing; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicInteger; + +public class BookManager { + + private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM"); + private AtomicInteger bookIdGenerator = new AtomicInteger(0); + + private ConcurrentMap inMemoryStore = new ConcurrentHashMap<>(); + + public BookManager() { + Book book = new Book(); + book.setId(getNextId()); + book.setName("Building Microservice With Oracle Helidon"); + book.setIsbn("11223344"); + book.setAuthor("baeldung"); + book.setPages(560); + inMemoryStore.put(book.getId(), book); + } + + private String getNextId() { + String date = LocalDate.now().format(formatter); + return String.format("%04d-%s", bookIdGenerator.incrementAndGet(), date); + } + + public String add(Book book) { + String id = getNextId(); + book.setId(id); + inMemoryStore.put(id, book); + return id; + } + + public Book get(String id) { + return inMemoryStore.get(id); + } + + public List getAll() { + List books = new ArrayList<>(); + books.addAll(inMemoryStore.values()); + return books; + } +} \ No newline at end of file diff --git a/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/BookResource.java b/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/BookResource.java new file mode 100644 index 0000000000..0648930841 --- /dev/null +++ b/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/BookResource.java @@ -0,0 +1,58 @@ +package com.baeldung.helidon.se.routing; + +import io.helidon.webserver.Routing; +import io.helidon.webserver.ServerRequest; +import io.helidon.webserver.ServerResponse; +import io.helidon.webserver.Service; + +import javax.json.Json; +import javax.json.JsonArray; +import javax.json.JsonArrayBuilder; +import javax.json.JsonObject; +import java.util.List; + +public class BookResource implements Service { + + private BookManager bookManager = new BookManager(); + + @Override + public void update(Routing.Rules rules) { + rules + .get("/", this::books) + .get("/{id}", this::bookById); + } + + private void bookById(ServerRequest serverRequest, ServerResponse serverResponse) { + //get the book with the given id + String id = serverRequest.path().param("id"); + Book book = bookManager.get(id); + JsonObject jsonObject = from(book); + serverResponse.send(jsonObject); + } + + private void books(ServerRequest serverRequest, ServerResponse serverResponse) { + //get all books + List books = bookManager.getAll(); + JsonArray jsonArray = from(books); + serverResponse.send(jsonArray); + } + + private JsonObject from(Book book) { + JsonObject jsonObject = Json.createObjectBuilder() + .add("id", book.getId()) + .add("isbn", book.getIsbn()) + .add("name", book.getName()) + .add("author", book.getAuthor()) + .add("pages", book.getPages()) + .build(); + return jsonObject; + } + + private JsonArray from(List books) { + JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder(); + books.forEach(book -> { + jsonArrayBuilder.add(from(book)); + }); + return jsonArrayBuilder.build(); + } +} diff --git a/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/WebApplicationRouting.java b/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/WebApplicationRouting.java new file mode 100644 index 0000000000..1f32d3c528 --- /dev/null +++ b/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/routing/WebApplicationRouting.java @@ -0,0 +1,29 @@ +package com.baeldung.helidon.se.routing; + +import io.helidon.webserver.Routing; +import io.helidon.webserver.ServerConfiguration; +import io.helidon.webserver.WebServer; +import io.helidon.webserver.json.JsonSupport; + +public class WebApplicationRouting { + + public static void main(String... args) throws Exception { + + ServerConfiguration serverConfig = ServerConfiguration.builder() + .port(9080) + .build(); + + Routing routing = Routing.builder() + .register(JsonSupport.get()) + .register("/books", new BookResource()) + .get("/greet", (request, response) -> response.send("Hello World !")) + .build(); + + WebServer.create(serverConfig, routing) + .start() + .thenAccept(ws -> + System.out.println("Server started at: http://localhost:" + ws.port()) + ); + } + +} diff --git a/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/security/MyUser.java b/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/security/MyUser.java new file mode 100644 index 0000000000..e8009a98ad --- /dev/null +++ b/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/security/MyUser.java @@ -0,0 +1,33 @@ +package com.baeldung.helidon.se.security; + +import io.helidon.security.provider.httpauth.UserStore; + +import java.util.Collection; + +public class MyUser implements UserStore.User { + + private String login; + private char[] password; + private Collection roles; + + public MyUser(String login, char[] password, Collection roles) { + this.login = login; + this.password = password; + this.roles = roles; + } + + @Override + public String getLogin() { + return login; + } + + @Override + public char[] getPassword() { + return password; + } + + @Override + public Collection getRoles() { + return roles; + } +} diff --git a/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/security/WebApplicationSecurity.java b/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/security/WebApplicationSecurity.java new file mode 100644 index 0000000000..9a67f3d716 --- /dev/null +++ b/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/security/WebApplicationSecurity.java @@ -0,0 +1,61 @@ +package com.baeldung.helidon.se.security; + +import io.helidon.config.Config; +import io.helidon.security.Security; +import io.helidon.security.SubjectType; +import io.helidon.security.provider.httpauth.HttpBasicAuthProvider; +import io.helidon.security.provider.httpauth.UserStore; +import io.helidon.security.webserver.WebSecurity; +import io.helidon.webserver.Routing; +import io.helidon.webserver.ServerConfiguration; +import io.helidon.webserver.WebServer; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +public class WebApplicationSecurity { + + public static void main(String... args) throws Exception { + + Config config = Config.create(); + ServerConfiguration serverConfig = + ServerConfiguration.fromConfig(config.get("server")); + + Map users = new HashMap<>(); + users.put("user", new MyUser("user", "user".toCharArray(), Arrays.asList("ROLE_USER"))); + users.put("admin", new MyUser("admin", "admin".toCharArray(), Arrays.asList("ROLE_USER", "ROLE_ADMIN"))); + UserStore store = user -> Optional.ofNullable(users.get(user)); + + HttpBasicAuthProvider httpBasicAuthProvider = HttpBasicAuthProvider.builder() + .realm("myRealm") + .subjectType(SubjectType.USER) + .userStore(store) + .build(); + + //1. Using Builder Pattern or Config Pattern + Security security = Security.builder() + .addAuthenticationProvider(httpBasicAuthProvider) + .build(); + //Security security = Security.fromConfig(config); + + //2. WebSecurity from Security or from Config + // WebSecurity webSecurity = WebSecurity.from(security) + // .securityDefaults(WebSecurity.authenticate()); + + WebSecurity webSecurity = WebSecurity.from(config); + + Routing routing = Routing.builder() + .register(webSecurity) + .get("/user", (request, response) -> response.send("Hello, I'm a Helidon SE user with ROLE_USER")) + .get("/admin", (request, response) -> response.send("Hello, I'm a Helidon SE user with ROLE_ADMIN")) + .build(); + + WebServer webServer = WebServer.create(serverConfig, routing); + + webServer.start().thenAccept(ws -> + System.out.println("Server started at: http://localhost:" + ws.port()) + ); + } +} diff --git a/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/webserver/SimpleWebApplication.java b/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/webserver/SimpleWebApplication.java new file mode 100644 index 0000000000..0a603a5123 --- /dev/null +++ b/helidon/helidon-se/src/main/java/com/baeldung/helidon/se/webserver/SimpleWebApplication.java @@ -0,0 +1,26 @@ +package com.baeldung.helidon.se.webserver; + +import io.helidon.webserver.Routing; +import io.helidon.webserver.ServerConfiguration; +import io.helidon.webserver.WebServer; + +public class SimpleWebApplication { + + public static void main(String... args) throws Exception { + + ServerConfiguration serverConfig = ServerConfiguration.builder() + .port(9001) + .build(); + + Routing routing = Routing.builder() + .get("/greet", (request, response) -> response.send("Hello World !")) + .build(); + + WebServer.create(serverConfig, routing) + .start() + .thenAccept(ws -> + System.out.println("Server started at: http://localhost:" + ws.port()) + ); + } + +} diff --git a/helidon/helidon-se/src/main/resources/application.json b/helidon/helidon-se/src/main/resources/application.json new file mode 100644 index 0000000000..9e26dfeeb6 --- /dev/null +++ b/helidon/helidon-se/src/main/resources/application.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/helidon/helidon-se/src/main/resources/application.properties b/helidon/helidon-se/src/main/resources/application.properties new file mode 100644 index 0000000000..062047de4a --- /dev/null +++ b/helidon/helidon-se/src/main/resources/application.properties @@ -0,0 +1,4 @@ +server.port=9080 +web.debug=true +web.page-size=15 +user.home=C:/Users/app \ No newline at end of file diff --git a/helidon/helidon-se/src/main/resources/application.yaml b/helidon/helidon-se/src/main/resources/application.yaml new file mode 100644 index 0000000000..b6dd6cec22 --- /dev/null +++ b/helidon/helidon-se/src/main/resources/application.yaml @@ -0,0 +1,33 @@ +server: + port: 9080 +web: + debug: true + page-size: 15 +user: + home: C:/Users/app + +#Config 4 Security ==> Mapped to Security Object +security: + providers: + - http-basic-auth: + realm: "myRealm" + principal-type: USER # Can be USER or SERVICE, default is USER + users: + - login: "user" + password: "user" + roles: ["ROLE_USER"] + - login: "admin" + password: "admin" + roles: ["ROLE_USER", "ROLE_ADMIN"] + + #Config 4 Security Web Server Integration ==> Mapped to WebSecurity Object + web-server: + securityDefaults: + authenticate: true + paths: + - path: "/user" + methods: ["get"] + roles-allowed: ["ROLE_USER", "ROLE_ADMIN"] + - path: "/admin" + methods: ["get"] + roles-allowed: ["ROLE_ADMIN"] \ No newline at end of file diff --git a/helidon/pom.xml b/helidon/pom.xml new file mode 100644 index 0000000000..ea8cc52ee0 --- /dev/null +++ b/helidon/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + + com.baeldung.helidon + helidon + 1.0.0-SNAPSHOT + pom + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + helidon-se + helidon-mp + + + diff --git a/java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java b/java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java index 1b64c8924a..371ac3a9bb 100644 --- a/java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java +++ b/java-streams/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java @@ -4,10 +4,9 @@ import com.codepoetics.protonpack.Indexed; import com.codepoetics.protonpack.StreamUtils; import com.codepoetics.protonpack.collectors.CollectorUtils; import com.codepoetics.protonpack.collectors.NonUniqueValueException; -import com.codepoetics.protonpack.selectors.Selector; +import com.codepoetics.protonpack.selectors.Selectors; import org.junit.Test; -import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.Set; @@ -21,7 +20,6 @@ import static java.util.Arrays.stream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -@SuppressWarnings("unchecked") public class ProtonpackUnitTest { @Test public void whenTakeWhile_thenTakenWhile() { @@ -39,17 +37,18 @@ public class ProtonpackUnitTest { @Test public void givenMultipleStream_whenZipped_thenZipped() { - String[] clubs = { "Juventus", "Barcelona", "Liverpool", "PSG" }; - String[] players = { "Ronaldo", "Messi", "Salah" }; - Set zippedFrom2Sources = StreamUtils.zip(stream(clubs), stream(players), (club, player) -> club + " " + player) - .collect(Collectors.toSet()); + String[] clubs = {"Juventus", "Barcelona", "Liverpool", "PSG"}; + String[] players = {"Ronaldo", "Messi", "Salah"}; + Set zippedFrom2Sources = StreamUtils + .zip(stream(clubs), stream(players), (club, player) -> club + " " + player) + .collect(Collectors.toSet()); assertThat(zippedFrom2Sources).contains("Juventus Ronaldo", "Barcelona Messi", "Liverpool Salah"); - String[] leagues = { "Serie A", "La Liga", "Premier League" }; + String[] leagues = {"Serie A", "La Liga", "Premier League"}; Set zippedFrom3Sources = StreamUtils.zip(stream(clubs), stream(players), stream(leagues), - (club, player, league) -> club + " " + player + " " + league).collect(Collectors.toSet()); + (club, player, league) -> club + " " + player + " " + league).collect(Collectors.toSet()); assertThat(zippedFrom3Sources).contains("Juventus Ronaldo Serie A", "Barcelona Messi La Liga", - "Liverpool Salah Premier League"); + "Liverpool Salah Premier League"); } @Test @@ -57,7 +56,7 @@ public class ProtonpackUnitTest { Stream streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool"); Set> zipsWithIndex = StreamUtils.zipWithIndex(streamOfClubs).collect(Collectors.toSet()); assertThat(zipsWithIndex).contains(Indexed.index(0, "Juventus"), Indexed.index(1, "Barcelona"), - Indexed.index(2, "Liverpool")); + Indexed.index(2, "Liverpool")); } @Test @@ -67,9 +66,10 @@ public class ProtonpackUnitTest { Stream streamOfLeagues = Stream.of("Serie A", "La Liga", "Premier League"); Set merged = StreamUtils.merge(() -> "", (valOne, valTwo) -> valOne + " " + valTwo, streamOfClubs, - streamOfPlayers, streamOfLeagues).collect(Collectors.toSet()); + streamOfPlayers, streamOfLeagues).collect(Collectors.toSet()); - assertThat(merged).contains(" Juventus Ronaldo Serie A", " Barcelona Messi La Liga", " Liverpool Salah Premier League", + assertThat(merged) + .contains(" Juventus Ronaldo Serie A", " Barcelona Messi La Liga", " Liverpool Salah Premier League", " PSG"); } @@ -79,7 +79,7 @@ public class ProtonpackUnitTest { Stream streamOfPlayers = Stream.of("Ronaldo", "Messi"); List> mergedListOfList = StreamUtils.mergeToList(streamOfClubs, streamOfPlayers) - .collect(Collectors.toList()); + .collect(Collectors.toList()); assertThat(mergedListOfList.get(0)).isInstanceOf(List.class); assertThat(mergedListOfList.get(0)).containsExactly("Juventus", "Ronaldo"); assertThat(mergedListOfList.get(1)).containsExactly("Barcelona", "Messi"); @@ -92,72 +92,67 @@ public class ProtonpackUnitTest { Stream streamOfPlayers = Stream.of("Ronaldo", "Messi"); Stream streamOfLeagues = Stream.of("Serie A", "La Liga"); - AtomicInteger counter = new AtomicInteger(0); - Selector roundRobinSelector = (o) -> { - Object[] vals = (Object[]) o; - while (counter.get() >= vals.length || vals[counter.get()] == null) { - if (counter.incrementAndGet() >= vals.length) - counter.set(0); - } - return counter.getAndIncrement(); - }; - Stream interleavedStream = StreamUtils.interleave(roundRobinSelector, streamOfClubs, streamOfPlayers, - streamOfLeagues); - List interleavedList = interleavedStream.collect(Collectors.toList()); - assertThat(interleavedList).containsExactly("Juventus", "Ronaldo", "Serie A", "Barcelona", "Messi", "La Liga", - "Liverpool"); + List interleavedList = StreamUtils + .interleave(Selectors.roundRobin(), streamOfClubs, streamOfPlayers, streamOfLeagues) + .collect(Collectors.toList()); + + assertThat(interleavedList) + .hasSize(7) + .containsExactly("Juventus", "Ronaldo", "Serie A", "Barcelona", "Messi", "La Liga", "Liverpool"); } @Test public void whenSkippedUntil_thenSkippedUntil() { - Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; - List skippedUntilGreaterThan5 = StreamUtils.skipUntil(stream(numbers), i -> i > 5).collect(Collectors.toList()); + Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + List skippedUntilGreaterThan5 = StreamUtils.skipUntil(stream(numbers), i -> i > 5) + .collect(Collectors.toList()); assertThat(skippedUntilGreaterThan5).containsExactly(6, 7, 8, 9, 10); List skippedUntilLessThanEquals5 = StreamUtils.skipUntil(stream(numbers), i -> i <= 5) - .collect(Collectors.toList()); + .collect(Collectors.toList()); assertThat(skippedUntilLessThanEquals5).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } @Test public void whenSkippedWhile_thenSkippedWhile() { - Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; List skippedWhileLessThanEquals5 = StreamUtils.skipWhile(stream(numbers), i -> i <= 5) - .collect(Collectors.toList()); + .collect(Collectors.toList()); assertThat(skippedWhileLessThanEquals5).containsExactly(6, 7, 8, 9, 10); - List skippedWhileGreaterThan5 = StreamUtils.skipWhile(stream(numbers), i -> i > 5).collect(Collectors.toList()); + List skippedWhileGreaterThan5 = StreamUtils.skipWhile(stream(numbers), i -> i > 5) + .collect(Collectors.toList()); assertThat(skippedWhileGreaterThan5).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } @Test public void givenFibonacciGenerator_whenUnfolded_thenUnfolded() { - AtomicInteger lastValue = new AtomicInteger(0); - Function> fibonacciGenerator = (i) -> (i < 10) ? - Optional.of(i + lastValue.getAndSet(i)) : - Optional.empty(); + Stream unfolded = StreamUtils.unfold(2, i -> (i < 100) ? Optional.of(i * i) : Optional.empty()); - List fib = StreamUtils.unfold(1, fibonacciGenerator).collect(Collectors.toList()); - assertThat(fib).containsExactly(1, 1, 2, 3, 5, 8, 13); + assertThat(unfolded.collect(Collectors.toList())).containsExactly(2, 4, 16, 256); } @Test public void whenWindowed_thenWindowed() { - Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7 }; + Integer[] numbers = {1, 2, 3, 4, 5, 6, 7}; - List> windowedWithSkip1 = StreamUtils.windowed(stream(numbers), 3, 1).collect(Collectors.toList()); - assertThat(windowedWithSkip1).containsExactly(asList(1, 2, 3), asList(2, 3, 4), asList(3, 4, 5), asList(4, 5, 6), + List> windowedWithSkip1 = StreamUtils.windowed(stream(numbers), 3, 1) + .collect(Collectors.toList()); + assertThat(windowedWithSkip1) + .containsExactly(asList(1, 2, 3), asList(2, 3, 4), asList(3, 4, 5), asList(4, 5, 6), asList(5, 6, 7)); - List> windowedWithSkip2 = StreamUtils.windowed(stream(numbers), 3, 2).collect(Collectors.toList()); + List> windowedWithSkip2 = StreamUtils.windowed(stream(numbers), 3, 2) + .collect(Collectors.toList()); assertThat(windowedWithSkip2).containsExactly(asList(1, 2, 3), asList(3, 4, 5), asList(5, 6, 7)); } @Test public void whenAggregated_thenAggregated() { - Integer[] numbers = { 1, 2, 2, 3, 4, 4, 4, 5 }; - List> aggregated = StreamUtils.aggregate(stream(numbers), (int1, int2) -> int1.compareTo(int2) == 0) - .collect(Collectors.toList()); + Integer[] numbers = {1, 2, 2, 3, 4, 4, 4, 5}; + List> aggregated = StreamUtils + .aggregate(stream(numbers), (int1, int2) -> int1.compareTo(int2) == 0) + .collect(Collectors.toList()); assertThat(aggregated).containsExactly(asList(1), asList(2, 2), asList(3), asList(4, 4, 4), asList(5)); List> aggregatedFixSize = StreamUtils.aggregate(stream(numbers), 5).collect(Collectors.toList()); @@ -166,20 +161,20 @@ public class ProtonpackUnitTest { @Test public void whenGroupedRun_thenGroupedRun() { - Integer[] numbers = { 1, 1, 2, 3, 4, 4, 5 }; + Integer[] numbers = {1, 1, 2, 3, 4, 4, 5}; List> grouped = StreamUtils.groupRuns(stream(numbers)).collect(Collectors.toList()); assertThat(grouped).containsExactly(asList(1, 1), asList(2), asList(3), asList(4, 4), asList(5)); - Integer[] numbers2 = { 1, 2, 3, 1 }; + Integer[] numbers2 = {1, 2, 3, 1}; List> grouped2 = StreamUtils.groupRuns(stream(numbers2)).collect(Collectors.toList()); assertThat(grouped2).containsExactly(asList(1), asList(2), asList(3), asList(1)); } @Test public void whenAggregatedOnListCondition_thenAggregatedOnListCondition() { - Integer[] numbers = { 1, 1, 2, 3, 4, 4, 5 }; + Integer[] numbers = {1, 1, 2, 3, 4, 4, 5}; Stream> aggregated = StreamUtils.aggregateOnListCondition(stream(numbers), - (currentList, nextInt) -> currentList.stream().mapToInt(Integer::intValue).sum() + nextInt <= 5); + (currentList, nextInt) -> currentList.stream().mapToInt(Integer::intValue).sum() + nextInt <= 5); assertThat(aggregated).containsExactly(asList(1, 1, 2), asList(3), asList(4), asList(4), asList(5)); } @@ -187,15 +182,14 @@ public class ProtonpackUnitTest { public void givenProjectionFunction_whenMaxedBy_thenMaxedBy() { Stream clubs = Stream.of("Juventus", "Barcelona", "PSG"); Optional longestName = clubs.collect(CollectorUtils.maxBy(String::length)); - assertThat(longestName.get()).isEqualTo("Barcelona"); + assertThat(longestName).contains("Barcelona"); } @Test public void givenStreamOfMultipleElem_whenUniqueCollector_thenValueReturned() { Stream singleElement = Stream.of(1); Optional unique = singleElement.collect(CollectorUtils.unique()); - assertThat(unique.get()).isEqualTo(1); - + assertThat(unique).contains(1); } @Test @@ -205,5 +199,4 @@ public class ProtonpackUnitTest { multipleElement.collect(CollectorUtils.unique()); }); } - } diff --git a/java-strings/pom.xml b/java-strings/pom.xml old mode 100644 new mode 100755 index a43490ce5c..ab94c28d4d --- a/java-strings/pom.xml +++ b/java-strings/pom.xml @@ -68,6 +68,21 @@ emoji-java 4.0.0 + + + org.junit.jupiter + junit-jupiter-api + 5.3.1 + test + + + + org.hamcrest + hamcrest-library + 1.3 + test + + org.passay @@ -79,6 +94,7 @@ commons-text 1.4 + @@ -115,4 +131,4 @@ 26.0-jre - \ No newline at end of file + diff --git a/java-strings/src/main/java/com/baeldung/string/searching/WordIndexer.java b/java-strings/src/main/java/com/baeldung/string/searching/WordIndexer.java new file mode 100644 index 0000000000..5314efb0b4 --- /dev/null +++ b/java-strings/src/main/java/com/baeldung/string/searching/WordIndexer.java @@ -0,0 +1,42 @@ +package com.baeldung.string.searching; + +import java.util.ArrayList; +import java.util.List; + +public class WordIndexer { + + public List findWord(String textString, String word) { + int index = 0; + List indexes = new ArrayList(); + String lowerCaseTextString = textString.toLowerCase(); + String lowerCaseWord = word.toLowerCase(); + + while(index != -1){ + index = lowerCaseTextString.indexOf(lowerCaseWord, index + 1); + if (index != -1) { + indexes.add(index); + } + } + return indexes; + } + + + + public List findWordUpgrade(String textString, String word) { + int index = 0; + List indexes = new ArrayList(); + StringBuilder output = new StringBuilder(); + String lowerCaseTextString = textString.toLowerCase(); + String lowerCaseWord = word.toLowerCase(); + int wordLength = 0; + + while(index != -1){ + index = lowerCaseTextString.indexOf(lowerCaseWord, index + wordLength); // Slight improvement + if (index != -1) { + indexes.add(index); + } + wordLength = word.length(); + } + return indexes; + } +} diff --git a/java-strings/src/test/java/com/baeldung/string/searching/WordIndexerUnitTest.java b/java-strings/src/test/java/com/baeldung/string/searching/WordIndexerUnitTest.java new file mode 100644 index 0000000000..f3f76db01f --- /dev/null +++ b/java-strings/src/test/java/com/baeldung/string/searching/WordIndexerUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.string.searching; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + + +public class WordIndexerUnitTest { + + String theString; + WordIndexer wordIndexer; + + @BeforeEach + public void setUp() throws Exception { + wordIndexer = new WordIndexer(); + + theString = "To be, or not to be: that is the question: " + + "Whether 'tis nobler in the mind to suffer " + + "The slings and arrows of outrageous fortune, " + + "Or to take arms against a sea of troubles, " + + "And by opposing end them? To die: to sleep; " + + "No more; and by a sleep to say we end " + + "The heart-ache and the thousand natural shocks " + + "That flesh is heir to, 'tis a consummation " + + "Devoutly to be wish'd. To die, to sleep; " + + "To sleep: perchance to dream: ay, there's the rub: " + + "For in that sleep of death what dreams may come,"; + } + + @Test + + public void givenWord_whenSearching_thenFindAllIndexedLocations() { + List expectedResult = Arrays.asList(7, 122, 130, 221, 438); + + List actualResult = wordIndexer.findWord(theString, "or"); + + assertEquals(expectedResult, actualResult); + } + + @Test + public void givenWordWithNoRepeatCharacters_whenImprovedSearching_thenFindAllIndexedLocations() { + List expectedResult = Arrays.asList(7, 122, 130, 221, 438); + + List actualResult = wordIndexer.findWordUpgrade(theString, "or"); + + assertEquals(expectedResult, actualResult); + } + + + @Test + public void givenWord_whenSearching_thenFindAtEndOfString() { + List expectedResult = Arrays.asList(480); + + List actualResult = wordIndexer.findWordUpgrade(theString, "come,"); + + assertEquals(expectedResult, actualResult); + } +} diff --git a/javaxval/pom.xml b/javaxval/pom.xml index 0263fb68af..22f1827213 100644 --- a/javaxval/pom.xml +++ b/javaxval/pom.xml @@ -22,16 +22,6 @@ hibernate-validator ${hibernate-validator.version} - - org.hibernate - hibernate-validator-annotation-processor - ${hibernate-validator.version} - - - javax.el - javax.el-api - ${javax.el-api.version} - org.glassfish javax.el @@ -60,13 +50,11 @@ test - 2.0.1.Final 6.0.13.Final - 3.0.0 3.0.0 - 5.0.2.RELEASE + 5.0.2.RELEASE 4.12 3.11.1 diff --git a/json/src/main/java/com/baeldung/jsonjava/JSONArrayGetValueByKey.java b/json/src/main/java/com/baeldung/jsonjava/JSONArrayGetValueByKey.java new file mode 100644 index 0000000000..b3df318e22 --- /dev/null +++ b/json/src/main/java/com/baeldung/jsonjava/JSONArrayGetValueByKey.java @@ -0,0 +1,30 @@ +package com.baeldung.jsonjava; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.json.JSONArray; +import org.json.JSONObject; + +public class JSONArrayGetValueByKey { + + public List getValuesByKeyInJSONArray(String jsonArrayStr, String key) { + List values = new ArrayList<>(); + JSONArray jsonArray = new JSONArray(jsonArrayStr); + for (int idx = 0; idx < jsonArray.length(); idx++) { + JSONObject jsonObj = jsonArray.getJSONObject(idx); + values.add(jsonObj.optString(key)); + } + return values; + } + + public List getValuesByKeyInJSONArrayUsingJava8(String jsonArrayStr, String key) { + JSONArray jsonArray = new JSONArray(jsonArrayStr); + return IntStream.range(0, jsonArray.length()) + .mapToObj(index -> ((JSONObject) jsonArray.get(index)).optString(key)) + .collect(Collectors.toList()); + } + +} diff --git a/json/src/test/java/com/baeldung/jsonjava/JSONArrayGetValueByKeyUnitTest.java b/json/src/test/java/com/baeldung/jsonjava/JSONArrayGetValueByKeyUnitTest.java new file mode 100644 index 0000000000..265c603acd --- /dev/null +++ b/json/src/test/java/com/baeldung/jsonjava/JSONArrayGetValueByKeyUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.jsonjava; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +import static org.junit.Assert.assertThat; +import static org.hamcrest.CoreMatchers.equalTo; + +public class JSONArrayGetValueByKeyUnitTest { + + private static final JSONArrayGetValueByKey obj = new JSONArrayGetValueByKey(); + + @Test + public void givenJSONArrayAndAKey_thenReturnAllValuesForGivenKey() { + String jsonStr = "[" + " {" + " \"name\": \"John\"," + " \"city\": \"chicago\"," + " \"age\": \"22\" " + "}," + " { " + "\"name\": \"Gary\"," + " \"city\": \"florida\"," + " \"age\": \"35\" " + "}," + " { " + "\"name\": \"Selena\"," + + " \"city\": \"vegas\"," + " \"age\": \"18\" " + "} " + "]"; + + List actualValues = obj.getValuesByKeyInJSONArray(jsonStr, "name"); + + assertThat(actualValues, equalTo(Arrays.asList("John", "Gary", "Selena"))); + } + + @Test + public void givenJSONArrayAndAKey_whenUsingJava8Syntax_thenReturnAllValuesForGivenKey() { + String jsonStr = "[" + " {" + " \"name\": \"John\"," + " \"city\": \"chicago\"," + " \"age\": \"22\" " + "}," + " { " + "\"name\": \"Gary\"," + " \"city\": \"florida\"," + " \"age\": \"35\" " + "}," + " { " + "\"name\": \"Selena\"," + + " \"city\": \"vegas\"," + " \"age\": \"18\" " + "} " + "]"; + + List actualValues = obj.getValuesByKeyInJSONArrayUsingJava8(jsonStr, "name"); + + assertThat(actualValues, equalTo(Arrays.asList("John", "Gary", "Selena"))); + } + +} diff --git a/lombok/README.md b/lombok/README.md index d12c14416d..a297aeb31e 100644 --- a/lombok/README.md +++ b/lombok/README.md @@ -3,3 +3,4 @@ - [Using Lombok’s @Builder Annotation](http://www.baeldung.com/lombok-builder) - [Using Lombok’s @Getter for Boolean Fields](https://www.baeldung.com/lombok-getter-boolean) - [Lombok @Builder with Inheritance](https://www.baeldung.com/lombok-builder-inheritance) +- [Lombok Builder with Default Value](https://www.baeldung.com/lombok-builder-default-value) diff --git a/out/production/main/com/baeldung/.gitignore b/out/production/main/com/baeldung/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/out/production/main/com/baeldung/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/out/production/main/com/baeldung/README.md b/out/production/main/com/baeldung/README.md deleted file mode 100644 index 51809b2882..0000000000 --- a/out/production/main/com/baeldung/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [SHA-256 Hashing in Java](http://www.baeldung.com/sha-256-hashing-java) diff --git a/out/production/main/com/baeldung/enums/README.md b/out/production/main/com/baeldung/enums/README.md deleted file mode 100644 index 6ccfa725f5..0000000000 --- a/out/production/main/com/baeldung/enums/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums) diff --git a/out/production/main/com/baeldung/networking/README.md b/out/production/main/com/baeldung/networking/README.md deleted file mode 100644 index b9e827f085..0000000000 --- a/out/production/main/com/baeldung/networking/README.md +++ /dev/null @@ -1,5 +0,0 @@ -### Relevant Articles: -- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java) -- [A Guide To HTTP Cookies In Java](http://www.baeldung.com/cookies-java) -- [A Guide to the Java URL](http://www.baeldung.com/java-url) -- [Working with Network Interfaces in Java](http://www.baeldung.com/java-network-interfaces) diff --git a/out/production/main/com/baeldung/objectsize/MANIFEST.MF b/out/production/main/com/baeldung/objectsize/MANIFEST.MF deleted file mode 100644 index b814f624d0..0000000000 --- a/out/production/main/com/baeldung/objectsize/MANIFEST.MF +++ /dev/null @@ -1 +0,0 @@ -Premain-class: com.baeldung.objectsize.InstrumentationAgent diff --git a/out/production/main/com/baeldung/printscreen/README.md b/out/production/main/com/baeldung/printscreen/README.md deleted file mode 100644 index 7b3b40c102..0000000000 --- a/out/production/main/com/baeldung/printscreen/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java) diff --git a/out/production/main/javac-args/arguments b/out/production/main/javac-args/arguments deleted file mode 100644 index 51639800a7..0000000000 --- a/out/production/main/javac-args/arguments +++ /dev/null @@ -1,2 +0,0 @@ --d javac-target -verbose -com/baeldung/javac/Data.java \ No newline at end of file diff --git a/out/production/main/javac-args/options b/out/production/main/javac-args/options deleted file mode 100644 index f02f2344ff..0000000000 --- a/out/production/main/javac-args/options +++ /dev/null @@ -1,2 +0,0 @@ --d javac-target --verbose \ No newline at end of file diff --git a/out/production/main/javac-args/types b/out/production/main/javac-args/types deleted file mode 100644 index ef2d861f84..0000000000 --- a/out/production/main/javac-args/types +++ /dev/null @@ -1 +0,0 @@ -com/baeldung/javac/Data.java \ No newline at end of file diff --git a/out/production/main/javac-args/xlint-ops b/out/production/main/javac-args/xlint-ops deleted file mode 100644 index cdccbc0cce..0000000000 --- a/out/production/main/javac-args/xlint-ops +++ /dev/null @@ -1,3 +0,0 @@ --d javac-target --Xlint:rawtypes,unchecked,static,cast,serial,fallthrough -com/baeldung/javac/Data.java \ No newline at end of file diff --git a/out/production/main/log4j.properties b/out/production/main/log4j.properties deleted file mode 100644 index 5fe42d854c..0000000000 --- a/out/production/main/log4j.properties +++ /dev/null @@ -1,9 +0,0 @@ -# Set root logger level to DEBUG and its only appender to A1. -log4j.rootLogger=DEBUG, A1 - -# A1 is set to be a ConsoleAppender. -log4j.appender.A1=org.apache.log4j.ConsoleAppender - -# A1 uses PatternLayout. -log4j.appender.A1.layout=org.apache.log4j.PatternLayout -log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n diff --git a/out/production/main1/com/baeldung/datetime/README.md b/out/production/main1/com/baeldung/datetime/README.md deleted file mode 100644 index 1e4adbb612..0000000000 --- a/out/production/main1/com/baeldung/datetime/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro) diff --git a/out/test/test/com/baeldung/hexToAscii/README.md b/out/test/test/com/baeldung/hexToAscii/README.md deleted file mode 100644 index c6d5826333..0000000000 --- a/out/test/test/com/baeldung/hexToAscii/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Convert Hex to ASCII in Java](http://www.baeldung.com/java-convert-hex-to-ascii) diff --git a/out/test/test/com/baeldung/java/conversion/README.md b/out/test/test/com/baeldung/java/conversion/README.md deleted file mode 100644 index 7c81180249..0000000000 --- a/out/test/test/com/baeldung/java/conversion/README.md +++ /dev/null @@ -1,2 +0,0 @@ -Relevant Articles: -- [Java String Conversions](http://www.baeldung.com/java-string-conversions) diff --git a/out/test/test/com/baeldung/stringisnumeric.zip b/out/test/test/com/baeldung/stringisnumeric.zip deleted file mode 100644 index b8a7b9b35a..0000000000 Binary files a/out/test/test/com/baeldung/stringisnumeric.zip and /dev/null differ diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index bcfcfdec44..47d382f58d 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -42,6 +42,10 @@ org.springframework.boot spring-boot-maven-plugin ${spring-boot.version} + + ${start-class} + + diff --git a/activejdbc/README.md b/persistence-modules/activejdbc/README.md similarity index 100% rename from activejdbc/README.md rename to persistence-modules/activejdbc/README.md diff --git a/activejdbc/pom.xml b/persistence-modules/activejdbc/pom.xml similarity index 98% rename from activejdbc/pom.xml rename to persistence-modules/activejdbc/pom.xml index 542e674ff3..6a29f14ced 100644 --- a/activejdbc/pom.xml +++ b/persistence-modules/activejdbc/pom.xml @@ -11,6 +11,7 @@ parent-modules com.baeldung 1.0.0-SNAPSHOT + ../../ diff --git a/activejdbc/src/main/java/com/baeldung/ActiveJDBCApp.java b/persistence-modules/activejdbc/src/main/java/com/baeldung/ActiveJDBCApp.java similarity index 100% rename from activejdbc/src/main/java/com/baeldung/ActiveJDBCApp.java rename to persistence-modules/activejdbc/src/main/java/com/baeldung/ActiveJDBCApp.java diff --git a/activejdbc/src/main/java/com/baeldung/model/Employee.java b/persistence-modules/activejdbc/src/main/java/com/baeldung/model/Employee.java similarity index 100% rename from activejdbc/src/main/java/com/baeldung/model/Employee.java rename to persistence-modules/activejdbc/src/main/java/com/baeldung/model/Employee.java diff --git a/activejdbc/src/main/java/com/baeldung/model/Role.java b/persistence-modules/activejdbc/src/main/java/com/baeldung/model/Role.java similarity index 100% rename from activejdbc/src/main/java/com/baeldung/model/Role.java rename to persistence-modules/activejdbc/src/main/java/com/baeldung/model/Role.java diff --git a/activejdbc/src/main/migration/_create_tables.sql b/persistence-modules/activejdbc/src/main/migration/_create_tables.sql similarity index 100% rename from activejdbc/src/main/migration/_create_tables.sql rename to persistence-modules/activejdbc/src/main/migration/_create_tables.sql diff --git a/activejdbc/src/main/resources/database.properties b/persistence-modules/activejdbc/src/main/resources/database.properties similarity index 100% rename from activejdbc/src/main/resources/database.properties rename to persistence-modules/activejdbc/src/main/resources/database.properties diff --git a/jnosql/jnosql-artemis/src/main/resources/logback.xml b/persistence-modules/activejdbc/src/main/resources/logback.xml similarity index 100% rename from jnosql/jnosql-artemis/src/main/resources/logback.xml rename to persistence-modules/activejdbc/src/main/resources/logback.xml diff --git a/activejdbc/src/test/java/com/baeldung/ActiveJDBCAppManualTest.java b/persistence-modules/activejdbc/src/test/java/com/baeldung/ActiveJDBCAppManualTest.java similarity index 100% rename from activejdbc/src/test/java/com/baeldung/ActiveJDBCAppManualTest.java rename to persistence-modules/activejdbc/src/test/java/com/baeldung/ActiveJDBCAppManualTest.java diff --git a/apache-cayenne/README.md b/persistence-modules/apache-cayenne/README.md similarity index 100% rename from apache-cayenne/README.md rename to persistence-modules/apache-cayenne/README.md diff --git a/apache-cayenne/pom.xml b/persistence-modules/apache-cayenne/pom.xml similarity index 97% rename from apache-cayenne/pom.xml rename to persistence-modules/apache-cayenne/pom.xml index 591809d47f..d0c6d1f2b2 100644 --- a/apache-cayenne/pom.xml +++ b/persistence-modules/apache-cayenne/pom.xml @@ -13,6 +13,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../../ diff --git a/apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/Article.java b/persistence-modules/apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/Article.java similarity index 100% rename from apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/Article.java rename to persistence-modules/apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/Article.java diff --git a/apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/Author.java b/persistence-modules/apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/Author.java similarity index 100% rename from apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/Author.java rename to persistence-modules/apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/Author.java diff --git a/apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/auto/_Article.java b/persistence-modules/apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/auto/_Article.java similarity index 100% rename from apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/auto/_Article.java rename to persistence-modules/apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/auto/_Article.java diff --git a/apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/auto/_Author.java b/persistence-modules/apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/auto/_Author.java similarity index 100% rename from apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/auto/_Author.java rename to persistence-modules/apache-cayenne/src/main/java/com/baeldung/apachecayenne/persistent/auto/_Author.java diff --git a/apache-cayenne/src/main/resources/cayenne-project.xml b/persistence-modules/apache-cayenne/src/main/resources/cayenne-project.xml similarity index 100% rename from apache-cayenne/src/main/resources/cayenne-project.xml rename to persistence-modules/apache-cayenne/src/main/resources/cayenne-project.xml diff --git a/apache-cayenne/src/main/resources/datamap.map.xml b/persistence-modules/apache-cayenne/src/main/resources/datamap.map.xml similarity index 100% rename from apache-cayenne/src/main/resources/datamap.map.xml rename to persistence-modules/apache-cayenne/src/main/resources/datamap.map.xml diff --git a/jnosql/jnosql-diana/src/main/resources/logback.xml b/persistence-modules/apache-cayenne/src/main/resources/logback.xml similarity index 100% rename from jnosql/jnosql-diana/src/main/resources/logback.xml rename to persistence-modules/apache-cayenne/src/main/resources/logback.xml diff --git a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationLiveTest.java b/persistence-modules/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationLiveTest.java similarity index 100% rename from apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationLiveTest.java rename to persistence-modules/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationLiveTest.java diff --git a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationLiveTest.java b/persistence-modules/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationLiveTest.java similarity index 100% rename from apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationLiveTest.java rename to persistence-modules/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationLiveTest.java diff --git a/flyway/.gitignore b/persistence-modules/flyway/.gitignore similarity index 100% rename from flyway/.gitignore rename to persistence-modules/flyway/.gitignore diff --git a/flyway/README.MD b/persistence-modules/flyway/README.MD similarity index 100% rename from flyway/README.MD rename to persistence-modules/flyway/README.MD diff --git a/flyway/db/migration/V1_0__create_employee_schema.sql b/persistence-modules/flyway/db/migration/V1_0__create_employee_schema.sql similarity index 100% rename from flyway/db/migration/V1_0__create_employee_schema.sql rename to persistence-modules/flyway/db/migration/V1_0__create_employee_schema.sql diff --git a/flyway/db/migration/V2_0__create_department_schema.sql b/persistence-modules/flyway/db/migration/V2_0__create_department_schema.sql similarity index 100% rename from flyway/db/migration/V2_0__create_department_schema.sql rename to persistence-modules/flyway/db/migration/V2_0__create_department_schema.sql diff --git a/flyway/myFlywayConfig.properties b/persistence-modules/flyway/myFlywayConfig.properties similarity index 100% rename from flyway/myFlywayConfig.properties rename to persistence-modules/flyway/myFlywayConfig.properties diff --git a/flyway/pom.xml b/persistence-modules/flyway/pom.xml similarity index 97% rename from flyway/pom.xml rename to persistence-modules/flyway/pom.xml index 353bbfb1ec..237b426521 100644 --- a/flyway/pom.xml +++ b/persistence-modules/flyway/pom.xml @@ -11,7 +11,7 @@ parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-1 + ../../parent-boot-1 diff --git a/flyway/src/main/java/com/baeldung/flywaycallbacks/ExampleFlywayCallback.java b/persistence-modules/flyway/src/main/java/com/baeldung/flywaycallbacks/ExampleFlywayCallback.java similarity index 100% rename from flyway/src/main/java/com/baeldung/flywaycallbacks/ExampleFlywayCallback.java rename to persistence-modules/flyway/src/main/java/com/baeldung/flywaycallbacks/ExampleFlywayCallback.java diff --git a/flyway/src/main/java/com/baeldung/flywaycallbacks/FlywayApplication.java b/persistence-modules/flyway/src/main/java/com/baeldung/flywaycallbacks/FlywayApplication.java similarity index 100% rename from flyway/src/main/java/com/baeldung/flywaycallbacks/FlywayApplication.java rename to persistence-modules/flyway/src/main/java/com/baeldung/flywaycallbacks/FlywayApplication.java diff --git a/persistence-modules/flyway/src/main/resources/application.properties b/persistence-modules/flyway/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/flyway/src/main/resources/db/callbacks/beforeEachMigrate.sql b/persistence-modules/flyway/src/main/resources/db/callbacks/beforeEachMigrate.sql similarity index 100% rename from flyway/src/main/resources/db/callbacks/beforeEachMigrate.sql rename to persistence-modules/flyway/src/main/resources/db/callbacks/beforeEachMigrate.sql diff --git a/flyway/src/main/resources/db/callbacks/beforeMigrate.sql b/persistence-modules/flyway/src/main/resources/db/callbacks/beforeMigrate.sql similarity index 100% rename from flyway/src/main/resources/db/callbacks/beforeMigrate.sql rename to persistence-modules/flyway/src/main/resources/db/callbacks/beforeMigrate.sql diff --git a/flyway/src/main/resources/db/migration/V1_0__add_table_one.sql b/persistence-modules/flyway/src/main/resources/db/migration/V1_0__add_table_one.sql similarity index 100% rename from flyway/src/main/resources/db/migration/V1_0__add_table_one.sql rename to persistence-modules/flyway/src/main/resources/db/migration/V1_0__add_table_one.sql diff --git a/flyway/src/main/resources/db/migration/V1_1__add_table_two.sql b/persistence-modules/flyway/src/main/resources/db/migration/V1_1__add_table_two.sql similarity index 100% rename from flyway/src/main/resources/db/migration/V1_1__add_table_two.sql rename to persistence-modules/flyway/src/main/resources/db/migration/V1_1__add_table_two.sql diff --git a/flyway/src/main/resources/logback.xml b/persistence-modules/flyway/src/main/resources/logback.xml similarity index 100% rename from flyway/src/main/resources/logback.xml rename to persistence-modules/flyway/src/main/resources/logback.xml diff --git a/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationUnitTest.java b/persistence-modules/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationUnitTest.java similarity index 100% rename from flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationUnitTest.java rename to persistence-modules/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayApplicationUnitTest.java diff --git a/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayCallbackTestConfig.java b/persistence-modules/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayCallbackTestConfig.java similarity index 100% rename from flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayCallbackTestConfig.java rename to persistence-modules/flyway/src/test/java/com/baeldung/flywaycallbacks/FlywayCallbackTestConfig.java diff --git a/hbase/README.md b/persistence-modules/hbase/README.md similarity index 100% rename from hbase/README.md rename to persistence-modules/hbase/README.md diff --git a/hbase/pom.xml b/persistence-modules/hbase/pom.xml similarity index 96% rename from hbase/pom.xml rename to persistence-modules/hbase/pom.xml index 117cf72e30..ffd1464482 100644 --- a/hbase/pom.xml +++ b/persistence-modules/hbase/pom.xml @@ -8,6 +8,7 @@ parent-modules com.baeldung 1.0.0-SNAPSHOT + ../../ diff --git a/hbase/src/main/java/org/baeldung/hbase/HBaseClientOperations.java b/persistence-modules/hbase/src/main/java/org/baeldung/hbase/HBaseClientOperations.java similarity index 100% rename from hbase/src/main/java/org/baeldung/hbase/HBaseClientOperations.java rename to persistence-modules/hbase/src/main/java/org/baeldung/hbase/HBaseClientOperations.java diff --git a/hbase/src/main/java/org/baeldung/hbase/HbaseClientExample.java b/persistence-modules/hbase/src/main/java/org/baeldung/hbase/HbaseClientExample.java similarity index 100% rename from hbase/src/main/java/org/baeldung/hbase/HbaseClientExample.java rename to persistence-modules/hbase/src/main/java/org/baeldung/hbase/HbaseClientExample.java diff --git a/hbase/src/main/resources/hbase-site.xml b/persistence-modules/hbase/src/main/resources/hbase-site.xml similarity index 100% rename from hbase/src/main/resources/hbase-site.xml rename to persistence-modules/hbase/src/main/resources/hbase-site.xml diff --git a/spring-data-couchbase-2/src/test/resources/logback.xml b/persistence-modules/hbase/src/main/resources/logback.xml similarity index 57% rename from spring-data-couchbase-2/src/test/resources/logback.xml rename to persistence-modules/hbase/src/main/resources/logback.xml index 56af2d397e..7d900d8ea8 100644 --- a/spring-data-couchbase-2/src/test/resources/logback.xml +++ b/persistence-modules/hbase/src/main/resources/logback.xml @@ -7,12 +7,6 @@ - - - - - - diff --git a/hibernate5/README.md b/persistence-modules/hibernate5/README.md similarity index 100% rename from hibernate5/README.md rename to persistence-modules/hibernate5/README.md diff --git a/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml similarity index 98% rename from hibernate5/pom.xml rename to persistence-modules/hibernate5/pom.xml index 748a106cca..24f4055a82 100644 --- a/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -10,6 +10,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../../ diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/UnsupportedTenancyException.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Address.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Address.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Address.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Address.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringType.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/OfficeEmployee.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumber.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Salary.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Salary.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Salary.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/Salary.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryCurrencyConvertor.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/entities/Department.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/entities/Department.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/entities/Department.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptor.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptor.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptor.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptor.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptorImpl.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptorImpl.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptorImpl.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/CustomInterceptorImpl.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/HibernateUtil.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/interceptors/HibernateUtil.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/HibernateUtil.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/entity/User.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/entity/User.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/interceptors/entity/User.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/interceptors/entity/User.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/CustomPhysicalNamingStrategy.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/CustomPhysicalNamingStrategy.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/CustomPhysicalNamingStrategy.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/CustomPhysicalNamingStrategy.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/Customer.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/Customer.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/Customer.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/namingstrategy/Customer.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Course.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Course.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/Course.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Course.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Department.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Department.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/Department.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Department.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Employee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Employee.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/Employee.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Employee.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntry.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntry.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntry.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntry.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryIdClass.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryIdClass.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryIdClass.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryIdClass.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryPK.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryPK.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryPK.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/OrderEntryPK.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Person.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Person.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/Person.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Person.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PersonName.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PersonName.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/PersonName.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PersonName.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Phone.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/Phone.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Phone.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Product.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Product.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/Product.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Product.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Result.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Result.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/Result.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Result.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/Student.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/User.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/UserProfile.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/UserProfile.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/UserProfile.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/UserProfile.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/generator/MyGenerator.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Item.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/package-info.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/package-info.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/pojo/package-info.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/pojo/package-info.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Company.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Company.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/proxy/Company.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Company.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/proxy/Employee.java diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java b/persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java similarity index 100% rename from hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java rename to persistence-modules/hibernate5/src/main/java/com/baeldung/hibernate/proxy/HibernateUtil.java diff --git a/persistence-modules/hibernate5/src/main/resources/logback.xml b/persistence-modules/hibernate5/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/hibernate5/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/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/IdentifiersIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/IdentifiersIntegrationTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/IdentifiersIntegrationTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/IdentifiersIntegrationTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/TemporalValuesUnitTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/converter/PersonNameConverterUnitTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesManualTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorUnitTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorUnitTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/interceptors/HibernateInterceptorUnitTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUnitTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUnitTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUnitTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobUnitTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/Car.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/Car.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/Car.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/Car.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/database/TenantIdNames.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaApproachMultitenancyIntegrationTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/multitenancy/schema/TenantIdNames.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/namingstrategy/NamingStrategyLiveTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/namingstrategy/NamingStrategyLiveTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/namingstrategy/NamingStrategyLiveTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/namingstrategy/NamingStrategyLiveTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java b/persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java similarity index 100% rename from hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java rename to persistence-modules/hibernate5/src/test/java/com/baeldung/hibernate/proxy/HibernateProxyUnitTest.java diff --git a/hibernate5/src/test/resources/hibernate-customtypes.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties similarity index 100% rename from hibernate5/src/test/resources/hibernate-customtypes.properties rename to persistence-modules/hibernate5/src/test/resources/hibernate-customtypes.properties diff --git a/hibernate5/src/test/resources/hibernate-database-multitenancy.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-database-multitenancy.properties similarity index 100% rename from hibernate5/src/test/resources/hibernate-database-multitenancy.properties rename to persistence-modules/hibernate5/src/test/resources/hibernate-database-multitenancy.properties diff --git a/hibernate5/src/test/resources/hibernate-database-mydb1.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb1.properties similarity index 100% rename from hibernate5/src/test/resources/hibernate-database-mydb1.properties rename to persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb1.properties diff --git a/hibernate5/src/test/resources/hibernate-database-mydb2.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb2.properties similarity index 100% rename from hibernate5/src/test/resources/hibernate-database-mydb2.properties rename to persistence-modules/hibernate5/src/test/resources/hibernate-database-mydb2.properties diff --git a/hibernate5/src/test/resources/hibernate-interceptors.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-interceptors.properties similarity index 100% rename from hibernate5/src/test/resources/hibernate-interceptors.properties rename to persistence-modules/hibernate5/src/test/resources/hibernate-interceptors.properties diff --git a/hibernate5/src/test/resources/hibernate-lifecycle.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-lifecycle.properties similarity index 100% rename from hibernate5/src/test/resources/hibernate-lifecycle.properties rename to persistence-modules/hibernate5/src/test/resources/hibernate-lifecycle.properties diff --git a/hibernate5/src/test/resources/hibernate-namingstrategy.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-namingstrategy.properties similarity index 100% rename from hibernate5/src/test/resources/hibernate-namingstrategy.properties rename to persistence-modules/hibernate5/src/test/resources/hibernate-namingstrategy.properties diff --git a/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties similarity index 100% rename from hibernate5/src/test/resources/hibernate-pessimistic-locking.properties rename to persistence-modules/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties diff --git a/hibernate5/src/test/resources/hibernate-schema-multitenancy.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-schema-multitenancy.properties similarity index 100% rename from hibernate5/src/test/resources/hibernate-schema-multitenancy.properties rename to persistence-modules/hibernate5/src/test/resources/hibernate-schema-multitenancy.properties diff --git a/hibernate5/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties similarity index 100% rename from hibernate5/src/test/resources/hibernate-spatial.properties rename to persistence-modules/hibernate5/src/test/resources/hibernate-spatial.properties diff --git a/hibernate5/src/test/resources/hibernate.properties b/persistence-modules/hibernate5/src/test/resources/hibernate.properties similarity index 100% rename from hibernate5/src/test/resources/hibernate.properties rename to persistence-modules/hibernate5/src/test/resources/hibernate.properties diff --git a/hibernate5/src/test/resources/lifecycle-init.sql b/persistence-modules/hibernate5/src/test/resources/lifecycle-init.sql similarity index 100% rename from hibernate5/src/test/resources/lifecycle-init.sql rename to persistence-modules/hibernate5/src/test/resources/lifecycle-init.sql diff --git a/hibernate5/src/test/resources/profile.png b/persistence-modules/hibernate5/src/test/resources/profile.png similarity index 100% rename from hibernate5/src/test/resources/profile.png rename to persistence-modules/hibernate5/src/test/resources/profile.png diff --git a/jnosql/README.md b/persistence-modules/jnosql/README.md similarity index 100% rename from jnosql/README.md rename to persistence-modules/jnosql/README.md diff --git a/jnosql/jnosql-artemis/pom.xml b/persistence-modules/jnosql/jnosql-artemis/pom.xml similarity index 100% rename from jnosql/jnosql-artemis/pom.xml rename to persistence-modules/jnosql/jnosql-artemis/pom.xml diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/AppConfig.java b/persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/AppConfig.java similarity index 100% rename from jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/AppConfig.java rename to persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/AppConfig.java diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EmbeddedMongoDBSetup.java b/persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EmbeddedMongoDBSetup.java similarity index 100% rename from jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EmbeddedMongoDBSetup.java rename to persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EmbeddedMongoDBSetup.java diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EntityManagerProducer.java b/persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EntityManagerProducer.java similarity index 100% rename from jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EntityManagerProducer.java rename to persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/EntityManagerProducer.java diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/RepositoryTodoManager.java b/persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/RepositoryTodoManager.java similarity index 100% rename from jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/RepositoryTodoManager.java rename to persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/RepositoryTodoManager.java diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TemplateTodoManager.java b/persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TemplateTodoManager.java similarity index 100% rename from jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TemplateTodoManager.java rename to persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TemplateTodoManager.java diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/Todo.java b/persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/Todo.java similarity index 100% rename from jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/Todo.java rename to persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/Todo.java diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoManager.java b/persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoManager.java similarity index 100% rename from jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoManager.java rename to persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoManager.java diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoRepository.java b/persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoRepository.java similarity index 100% rename from jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoRepository.java rename to persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoRepository.java diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoResource.java b/persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoResource.java similarity index 100% rename from jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoResource.java rename to persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/TodoResource.java diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Repo.java b/persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Repo.java similarity index 100% rename from jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Repo.java rename to persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Repo.java diff --git a/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Template.java b/persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Template.java similarity index 100% rename from jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Template.java rename to persistence-modules/jnosql/jnosql-artemis/src/main/java/com/baeldung/jnosql/artemis/qualifier/Template.java diff --git a/jnosql/jnosql-artemis/src/main/liberty/config/server.xml b/persistence-modules/jnosql/jnosql-artemis/src/main/liberty/config/server.xml similarity index 100% rename from jnosql/jnosql-artemis/src/main/liberty/config/server.xml rename to persistence-modules/jnosql/jnosql-artemis/src/main/liberty/config/server.xml diff --git a/jnosql/jnosql-artemis/src/main/resources/META-INF/beans.xml b/persistence-modules/jnosql/jnosql-artemis/src/main/resources/META-INF/beans.xml similarity index 100% rename from jnosql/jnosql-artemis/src/main/resources/META-INF/beans.xml rename to persistence-modules/jnosql/jnosql-artemis/src/main/resources/META-INF/beans.xml diff --git a/jnosql/jnosql-artemis/src/main/resources/META-INF/jnosql.json b/persistence-modules/jnosql/jnosql-artemis/src/main/resources/META-INF/jnosql.json similarity index 100% rename from jnosql/jnosql-artemis/src/main/resources/META-INF/jnosql.json rename to persistence-modules/jnosql/jnosql-artemis/src/main/resources/META-INF/jnosql.json diff --git a/persistence-modules/jnosql/jnosql-artemis/src/main/resources/logback.xml b/persistence-modules/jnosql/jnosql-artemis/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/jnosql/jnosql-artemis/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/jnosql/jnosql-artemis/src/main/webapp/WEB-INF/jnosql.json b/persistence-modules/jnosql/jnosql-artemis/src/main/webapp/WEB-INF/jnosql.json similarity index 100% rename from jnosql/jnosql-artemis/src/main/webapp/WEB-INF/jnosql.json rename to persistence-modules/jnosql/jnosql-artemis/src/main/webapp/WEB-INF/jnosql.json diff --git a/jnosql/jnosql-diana/pom.xml b/persistence-modules/jnosql/jnosql-diana/pom.xml similarity index 100% rename from jnosql/jnosql-diana/pom.xml rename to persistence-modules/jnosql/jnosql-diana/pom.xml diff --git a/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/column/ColumnFamilyApp.java b/persistence-modules/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/column/ColumnFamilyApp.java similarity index 100% rename from jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/column/ColumnFamilyApp.java rename to persistence-modules/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/column/ColumnFamilyApp.java diff --git a/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/DocumentApp.java b/persistence-modules/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/DocumentApp.java similarity index 100% rename from jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/DocumentApp.java rename to persistence-modules/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/DocumentApp.java diff --git a/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/MongoDbInit.java b/persistence-modules/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/MongoDbInit.java similarity index 100% rename from jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/MongoDbInit.java rename to persistence-modules/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/document/MongoDbInit.java diff --git a/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/Book.java b/persistence-modules/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/Book.java similarity index 100% rename from jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/Book.java rename to persistence-modules/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/Book.java diff --git a/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/KeyValueApp.java b/persistence-modules/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/KeyValueApp.java similarity index 100% rename from jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/KeyValueApp.java rename to persistence-modules/jnosql/jnosql-diana/src/main/java/com/baeldung/jnosql/diana/key/KeyValueApp.java diff --git a/jnosql/jnosql-diana/src/main/resources/diana-cassandra.properties b/persistence-modules/jnosql/jnosql-diana/src/main/resources/diana-cassandra.properties similarity index 100% rename from jnosql/jnosql-diana/src/main/resources/diana-cassandra.properties rename to persistence-modules/jnosql/jnosql-diana/src/main/resources/diana-cassandra.properties diff --git a/jnosql/jnosql-diana/src/main/resources/diana-hazelcast.properties b/persistence-modules/jnosql/jnosql-diana/src/main/resources/diana-hazelcast.properties similarity index 100% rename from jnosql/jnosql-diana/src/main/resources/diana-hazelcast.properties rename to persistence-modules/jnosql/jnosql-diana/src/main/resources/diana-hazelcast.properties diff --git a/jnosql/jnosql-diana/src/main/resources/diana-mongodb.properties b/persistence-modules/jnosql/jnosql-diana/src/main/resources/diana-mongodb.properties similarity index 100% rename from jnosql/jnosql-diana/src/main/resources/diana-mongodb.properties rename to persistence-modules/jnosql/jnosql-diana/src/main/resources/diana-mongodb.properties diff --git a/persistence-modules/jnosql/jnosql-diana/src/main/resources/logback.xml b/persistence-modules/jnosql/jnosql-diana/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/jnosql/jnosql-diana/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/jnosql/pom.xml b/persistence-modules/jnosql/pom.xml similarity index 100% rename from jnosql/pom.xml rename to persistence-modules/jnosql/pom.xml diff --git a/spring-boot-h2/README.md b/persistence-modules/spring-boot-h2/README.md similarity index 100% rename from spring-boot-h2/README.md rename to persistence-modules/spring-boot-h2/README.md diff --git a/persistence-modules/spring-boot-h2/spring-boot-h2-database/.gitignore b/persistence-modules/spring-boot-h2/spring-boot-h2-database/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/persistence-modules/spring-boot-h2/spring-boot-h2-database/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/spring-boot-h2/spring-boot-h2-database/pom.xml b/persistence-modules/spring-boot-h2/spring-boot-h2-database/pom.xml similarity index 95% rename from spring-boot-h2/spring-boot-h2-database/pom.xml rename to persistence-modules/spring-boot-h2/spring-boot-h2-database/pom.xml index 94f2293c34..4d677ab0d4 100644 --- a/spring-boot-h2/spring-boot-h2-database/pom.xml +++ b/persistence-modules/spring-boot-h2/spring-boot-h2-database/pom.xml @@ -23,7 +23,7 @@ UTF-8 1.8 - com.mycorp.starter.HelloWorldApplication + com.baeldung.h2db.demo.server.SpringBootApp diff --git a/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java b/persistence-modules/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java similarity index 96% rename from spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java rename to persistence-modules/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java index 8d92e18754..18236be234 100644 --- a/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java +++ b/persistence-modules/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/auto/configuration/AutoConfigurationDemo.java @@ -1,14 +1,14 @@ -package com.baeldung.h2db.auto.configuration; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; - -@SpringBootApplication -public class AutoConfigurationDemo { - - public static void main(String[] args) { - SpringApplication.run(AutoConfigurationDemo.class, args); - } - -} +package com.baeldung.h2db.auto.configuration; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +public class AutoConfigurationDemo { + + public static void main(String[] args) { + SpringApplication.run(AutoConfigurationDemo.class, args); + } + +} diff --git a/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/client/ClientSpringBootApp.java b/persistence-modules/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/client/ClientSpringBootApp.java similarity index 100% rename from spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/client/ClientSpringBootApp.java rename to persistence-modules/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/client/ClientSpringBootApp.java diff --git a/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/server/SpringBootApp.java b/persistence-modules/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/server/SpringBootApp.java similarity index 100% rename from spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/server/SpringBootApp.java rename to persistence-modules/spring-boot-h2/spring-boot-h2-database/src/main/java/com/baeldung/h2db/demo/server/SpringBootApp.java diff --git a/spring-boot-h2/spring-boot-h2-database/src/main/resources/application.properties b/persistence-modules/spring-boot-h2/spring-boot-h2-database/src/main/resources/application.properties similarity index 100% rename from spring-boot-h2/spring-boot-h2-database/src/main/resources/application.properties rename to persistence-modules/spring-boot-h2/spring-boot-h2-database/src/main/resources/application.properties diff --git a/spring-boot-h2/spring-boot-h2-remote-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-boot-h2/spring-boot-h2-remote-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 100% rename from spring-boot-h2/spring-boot-h2-remote-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to persistence-modules/spring-boot-h2/spring-boot-h2-remote-app/src/test/java/org/baeldung/SpringContextIntegrationTest.java diff --git a/spring-data-couchbase-2/README.md b/persistence-modules/spring-data-couchbase-2/README.md similarity index 100% rename from spring-data-couchbase-2/README.md rename to persistence-modules/spring-data-couchbase-2/README.md diff --git a/spring-data-couchbase-2/pom.xml b/persistence-modules/spring-data-couchbase-2/pom.xml similarity index 98% rename from spring-data-couchbase-2/pom.xml rename to persistence-modules/spring-data-couchbase-2/pom.xml index 6c7d7a9d11..a857ee538f 100644 --- a/spring-data-couchbase-2/pom.xml +++ b/persistence-modules/spring-data-couchbase-2/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../../ diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepository.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepository.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepository.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepository.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/CustomStudentRepositoryImpl.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonService.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonService.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonService.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/PersonTemplateService.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentService.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentService.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentService.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/service/StudentTemplateService.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonService.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonService.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonService.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentService.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentService.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentService.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentService.java diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java b/persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java rename to persistence-modules/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java diff --git a/spring-custom-aop/src/main/resources/logback.xml b/persistence-modules/spring-data-couchbase-2/src/main/resources/logback.xml similarity index 100% rename from spring-custom-aop/src/main/resources/logback.xml rename to persistence-modules/spring-data-couchbase-2/src/main/resources/logback.xml diff --git a/spring-data-couchbase-2/src/site/site.xml b/persistence-modules/spring-data-couchbase-2/src/site/site.xml similarity index 100% rename from spring-data-couchbase-2/src/site/site.xml rename to persistence-modules/spring-data-couchbase-2/src/site/site.xml diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 100% rename from spring-data-couchbase-2/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/SpringContextIntegrationTest.java diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java similarity index 100% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTest.java similarity index 100% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTest.java diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTestConfig.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTestConfig.java similarity index 100% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTestConfig.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTestConfig.java diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java similarity index 100% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java similarity index 100% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceIntegrationTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceIntegrationTest.java similarity index 100% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceIntegrationTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceIntegrationTest.java diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceIntegrationTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceIntegrationTest.java similarity index 100% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceIntegrationTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceIntegrationTest.java diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceIntegrationTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceIntegrationTest.java similarity index 100% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceIntegrationTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonTemplateServiceIntegrationTest.java diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceIntegrationTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceIntegrationTest.java similarity index 100% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceIntegrationTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceIntegrationTest.java diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceIntegrationTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceIntegrationTest.java similarity index 100% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceIntegrationTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentServiceIntegrationTest.java diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceIntegrationTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceIntegrationTest.java similarity index 100% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceIntegrationTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/StudentTemplateServiceIntegrationTest.java diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java similarity index 100% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTest.java similarity index 100% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTest.java diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTestConfig.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTestConfig.java similarity index 100% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTestConfig.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTestConfig.java diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java similarity index 100% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java similarity index 100% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java similarity index 100% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java rename to persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java diff --git a/spring-data-couchbase-2/src/main/resources/logback.xml b/persistence-modules/spring-data-couchbase-2/src/test/resources/logback.xml similarity index 100% rename from spring-data-couchbase-2/src/main/resources/logback.xml rename to persistence-modules/spring-data-couchbase-2/src/test/resources/logback.xml diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java index 7f28c958f1..56ba68dcbb 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java @@ -23,23 +23,19 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement -@PropertySource({ "classpath:persistence-jndi.properties" }) -@ComponentScan({ "org.baeldung.persistence" }) +@PropertySource("classpath:persistence-jndi.properties") +@ComponentScan("org.baeldung.persistence") @EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao") public class PersistenceJNDIConfig { @Autowired private Environment env; - public PersistenceJNDIConfig() { - super(); - } - @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + em.setPackagesToScan("org.baeldung.persistence.model"); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; @@ -52,9 +48,7 @@ public class PersistenceJNDIConfig { @Bean public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(emf); - return transactionManager; + return new JpaTransactionManager(emf); } @Bean diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Foo.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Foo.java index 209ab081de..5294860311 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Foo.java +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/persistence/model/Foo.java @@ -25,7 +25,7 @@ public class Foo implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ID") - private long id; + private Long id; @Column(name = "NAME") private String name; @@ -41,11 +41,11 @@ public class Foo implements Serializable { this.bar = bar; } - public long getId() { + public Long getId() { return id; } - public void setId(final int id) { + public void setId(final Long id) { this.id = id; } diff --git a/pom.xml b/pom.xml index 302530fd24..fa8a1108b5 100644 --- a/pom.xml +++ b/pom.xml @@ -330,11 +330,14 @@ parent-kotlin asm atomix - apache-cayenne + persistence-modules/apache-cayenne aws aws-lambda akka-streams - algorithms + algorithms-genetic + algorithms-miscellaneous-1 + algorithms-miscellaneous-2 + algorithms-sorting annotations apache-cxf apache-fop @@ -386,10 +389,11 @@ guava-modules/guava-21 guice disruptor + core-scala spring-static-resources hazelcast - hbase - hibernate5 + persistence-modules/hbase + persistence-modules/hibernate5 httpclient hystrix image-processing @@ -493,7 +497,7 @@ spring-ejb spring-aop persistence-modules/spring-data-cassandra - spring-data-couchbase-2 + persistence-modules/spring-data-couchbase-2 persistence-modules/spring-data-dynamodb persistence-modules/spring-data-elasticsearch persistence-modules/spring-data-jpa @@ -517,25 +521,7 @@ spring-jms spring-jooq persistence-modules/spring-jpa - spring-kafka - spring-katharsis - spring-ldap - spring-mockito - spring-mvc-forms-jsp - spring-mvc-forms-thymeleaf - spring-mvc-java - spring-mvc-velocity - spring-mvc-webflow - spring-mvc-xml - spring-mvc-kotlin - spring-protobuf - spring-quartz - spring-rest-angular - spring-rest-full - spring-rest-query-language - - - spring-resttemplate + @@ -627,13 +613,13 @@ optaplanner apache-meecrowave spring-reactive-kotlin - jnosql + persistence-modules/jnosql spring-boot-angular-ecommerce cdi-portable-extension jta java-websocket - activejdbc + persistence-modules/activejdbc animal-sniffer-mvn-plugin apache-avro apache-bval @@ -648,7 +634,7 @@ dagger data-structures dubbo - flyway + persistence-modules/flyway jni @@ -661,7 +647,6 @@ spring-boot-autoconfiguration spring-boot-custom-starter spring-boot-jasypt - spring-custom-aop spring-data-rest-querydsl spring-groovy spring-mobile @@ -699,8 +684,8 @@ spring-boot-custom-starter/greeter - spring-boot-h2/spring-boot-h2-database - + persistence-modules/spring-boot-h2/spring-boot-h2-database + @@ -730,7 +715,28 @@ spring-security-rest-custom spring-security-rest spring-security-sso - spring-security-x509 + spring-security-x509 + + spring-kafka + spring-katharsis + spring-ldap + spring-mockito + spring-mvc-forms-jsp + spring-mvc-forms-thymeleaf + spring-mvc-java + spring-mvc-velocity + spring-mvc-webflow + spring-mvc-xml + spring-mvc-kotlin + spring-protobuf + spring-quartz + spring-rest-angular + spring-rest-full + spring-rest-query-language + + + spring-resttemplate + helidon @@ -779,7 +785,7 @@ spring-boot-custom-starter greeter-spring-boot-autoconfigure greeter-spring-boot-sample-app - spring-boot-h2/spring-boot-h2-database + persistence-modules/spring-boot-h2/spring-boot-h2-database spring-boot-jasypt spring-boot-keycloak spring-boot-mvc @@ -933,7 +939,7 @@ parent-kotlin - java-websocket - activejdbc + persistence-modules/activejdbc animal-sniffer-mvn-plugin apache-avro apache-bval @@ -1146,7 +1152,7 @@ dagger data-structures dubbo - flyway + persistence-modules/flyway jni @@ -1159,7 +1165,6 @@ spring-boot-autoconfiguration spring-boot-custom-starter spring-boot-jasypt - spring-custom-aop spring-data-rest-querydsl spring-groovy spring-mobile @@ -1197,8 +1202,8 @@ spring-boot-custom-starter/greeter - spring-boot-h2/spring-boot-h2-database - + persistence-modules/spring-boot-h2/spring-boot-h2-database + @@ -1250,11 +1255,14 @@ parent-kotlin asm atomix - apache-cayenne + persistence-modules/apache-cayenne aws aws-lambda akka-streams - algorithms + algorithms-genetic + algorithms-miscellaneous-1 + algorithms-miscellaneous-2 + algorithms-sorting annotations apache-cxf apache-fop @@ -1297,7 +1305,7 @@ disruptor spring-static-resources hazelcast - hbase + persistence-modules/hbase hystrix image-processing @@ -1522,7 +1530,7 @@ persistence-modules/java-cassandra persistence-modules/spring-data-cassandra logging-modules/log4j2 - spring-data-couchbase-2 + persistence-modules/spring-data-couchbase-2 persistence-modules/spring-data-redis jmeter @@ -1603,7 +1611,7 @@ core-java google-web-toolkit spring-security-mvc-custom - hibernate5 + persistence-modules/hibernate5 persistence-modules/spring-data-elasticsearch core-java-concurrency core-java-concurrency-collections diff --git a/reactor-core/src/main/java/com/baeldung/reactor/ItemProducerCreate.java b/reactor-core/src/main/java/com/baeldung/reactor/ItemProducerCreate.java index 6078f8ef0b..e475303a3d 100644 --- a/reactor-core/src/main/java/com/baeldung/reactor/ItemProducerCreate.java +++ b/reactor-core/src/main/java/com/baeldung/reactor/ItemProducerCreate.java @@ -1,44 +1,22 @@ package com.baeldung.reactor; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Consumer; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import reactor.core.publisher.Flux; -public class ItemProducerCreate { +import java.util.List; +import java.util.function.Consumer; - Logger logger = LoggerFactory.getLogger(NetworTrafficProducerPush.class); +public class ItemProducerCreate { Consumer> listener; - public void create() { + public Flux create() { Flux articlesFlux = Flux.create((sink) -> { ItemProducerCreate.this.listener = (items) -> { items.stream() .forEach(article -> sink.next(article)); }; }); - articlesFlux.subscribe(ItemProducerCreate.this.logger::info); + return articlesFlux; } - public static void main(String[] args) { - ItemProducerCreate producer = new ItemProducerCreate(); - producer.create(); - - new Thread(new Runnable() { - - @Override - public void run() { - List items = new ArrayList<>(); - items.add("Item 1"); - items.add("Item 2"); - items.add("Item 3"); - producer.listener.accept(items); - } - }).start(); - } } diff --git a/reactor-core/src/main/java/com/baeldung/reactor/NetworTrafficProducerPush.java b/reactor-core/src/main/java/com/baeldung/reactor/NetworTrafficProducerPush.java deleted file mode 100644 index 807ceae84d..0000000000 --- a/reactor-core/src/main/java/com/baeldung/reactor/NetworTrafficProducerPush.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.reactor; - -import java.util.function.Consumer; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import reactor.core.publisher.Flux; -import reactor.core.publisher.FluxSink.OverflowStrategy; - -public class NetworTrafficProducerPush { - - Logger logger = LoggerFactory.getLogger(NetworTrafficProducerPush.class); - - Consumer listener; - - public void subscribe(Consumer consumer) { - Flux flux = Flux.push(sink -> { - NetworTrafficProducerPush.this.listener = (t) -> sink.next(t); - }, OverflowStrategy.DROP); - flux.subscribe(consumer); - } - - public void onPacket(String packet) { - listener.accept(packet); - } - - public static void main(String[] args) { - NetworTrafficProducerPush trafficProducer = new NetworTrafficProducerPush(); - trafficProducer.subscribe(trafficProducer.logger::info); - trafficProducer.onPacket("Packet[A18]"); - } - -} diff --git a/reactor-core/src/main/java/com/baeldung/reactor/NetworkTrafficProducerPush.java b/reactor-core/src/main/java/com/baeldung/reactor/NetworkTrafficProducerPush.java new file mode 100644 index 0000000000..a81d41ac11 --- /dev/null +++ b/reactor-core/src/main/java/com/baeldung/reactor/NetworkTrafficProducerPush.java @@ -0,0 +1,23 @@ +package com.baeldung.reactor; + +import java.util.function.Consumer; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.FluxSink.OverflowStrategy; + +public class NetworkTrafficProducerPush { + + Consumer listener; + + public void subscribe(Consumer consumer) { + Flux flux = Flux.push(sink -> { + NetworkTrafficProducerPush.this.listener = (t) -> sink.next(t); + }, OverflowStrategy.DROP); + flux.subscribe(consumer); + } + + public void onPacket(String packet) { + listener.accept(packet); + } + +} diff --git a/reactor-core/src/main/java/com/baeldung/reactor/ProgramaticSequences.java b/reactor-core/src/main/java/com/baeldung/reactor/ProgramaticSequences.java deleted file mode 100644 index b52def377d..0000000000 --- a/reactor-core/src/main/java/com/baeldung/reactor/ProgramaticSequences.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.reactor; - -import java.util.concurrent.atomic.AtomicInteger; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import reactor.core.publisher.Flux; - -public class ProgramaticSequences { - - Logger logger = LoggerFactory.getLogger(ProgramaticSequences.class); - - public void statefullImutableGenerate() { - Flux flux = Flux.generate(() -> 1, (state, sink) -> { - sink.next("2 + " + state + " = " + 2 + state); - if (state == 101) - sink.complete(); - return state + 1; - }); - - flux.subscribe(logger::info); - } - - public void statefullMutableGenerate() { - Flux flux = Flux.generate(AtomicInteger::new, (state, sink) -> { - int i = state.getAndIncrement(); - sink.next("2 + " + state + " = " + 2 + state); - if (i == 101) - sink.complete(); - return state; - }); - - flux.subscribe(logger::info); - } - - public void handle() { - Flux elephants = Flux.just(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) - .handle((i, sink) -> { - String animal = "Elephant nr " + i; - if (i % 2 == 0) { - sink.next(animal); - } - }); - - elephants.subscribe(logger::info); - } - - public static void main(String[] args) { - ProgramaticSequences ps = new ProgramaticSequences(); - - ps.statefullImutableGenerate(); - ps.statefullMutableGenerate(); - ps.handle(); - - } - -} diff --git a/reactor-core/src/main/java/com/baeldung/reactor/ProgrammaticSequences.java b/reactor-core/src/main/java/com/baeldung/reactor/ProgrammaticSequences.java new file mode 100644 index 0000000000..5c11240753 --- /dev/null +++ b/reactor-core/src/main/java/com/baeldung/reactor/ProgrammaticSequences.java @@ -0,0 +1,38 @@ +package com.baeldung.reactor; + +import java.util.concurrent.atomic.AtomicInteger; + +import reactor.core.publisher.Flux; + +public class ProgrammaticSequences { + + public Flux statefulImutableGenerate() { + return Flux.generate(() -> 1, (state, sink) -> { + sink.next("2 + " + state + " = " + (2 + state)); + if (state == 101) + sink.complete(); + return state + 1; + }); + } + + public Flux statefulMutableGenerate() { + return Flux.generate(AtomicInteger::new, (state, sink) -> { + int i = state.getAndIncrement(); + sink.next("2 + " + i + " = " + (2 + i)); + if (i == 101) + sink.complete(); + return state; + }); + } + + public Flux handle() { + return Flux.just(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + .handle((i, sink) -> { + String animal = "Elephant nr " + i; + if (i % 2 == 0) { + sink.next(animal); + } + }); + } + +} diff --git a/reactor-core/src/main/java/com/baeldung/reactor/StatelessGenerate.java b/reactor-core/src/main/java/com/baeldung/reactor/StatelessGenerate.java index c82f8e160b..3b9f0bb522 100644 --- a/reactor-core/src/main/java/com/baeldung/reactor/StatelessGenerate.java +++ b/reactor-core/src/main/java/com/baeldung/reactor/StatelessGenerate.java @@ -1,24 +1,12 @@ package com.baeldung.reactor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import reactor.core.publisher.Flux; public class StatelessGenerate { - Logger logger = LoggerFactory.getLogger(StatelessGenerate.class); - - public void statelessGenerate() { - Flux flux = Flux.generate((sink) -> { - sink.next("hallo"); + public Flux statelessGenerate() { + return Flux.generate((sink) -> { + sink.next("hello"); }); - flux.subscribe(logger::info); } - - public static void main(String[] args) { - StatelessGenerate ps = new StatelessGenerate(); - ps.statelessGenerate(); - } - } diff --git a/reactor-core/src/test/java/com/baeldung/reactor/ItemProducerCreateUnitTest.java b/reactor-core/src/test/java/com/baeldung/reactor/ItemProducerCreateUnitTest.java new file mode 100644 index 0000000000..8c436306d1 --- /dev/null +++ b/reactor-core/src/test/java/com/baeldung/reactor/ItemProducerCreateUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.reactor; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ItemProducerCreateUnitTest { + + @Test + public void givenFluxWithAsynchronousCreate_whenProduceItemsFromDifferentThread_thenAllItemsAreCollectedByTheSubscriber() throws InterruptedException { + List elements = new ArrayList<>(); + ItemProducerCreate producer = new ItemProducerCreate(); + producer.create() + .subscribe(elements::add); + + Thread producerThread = new Thread(() -> { + List items = new ArrayList<>(); + items.add("Item 1"); + items.add("Item 2"); + items.add("Item 3"); + producer.listener.accept(items); + }); + + producerThread.start(); + producerThread.join(); + + assertThat(elements).containsExactly("Item 1", "Item 2", "Item 3"); + } + +} diff --git a/reactor-core/src/test/java/com/baeldung/reactor/NetworkTrafficProducerPushUnitTest.java b/reactor-core/src/test/java/com/baeldung/reactor/NetworkTrafficProducerPushUnitTest.java new file mode 100644 index 0000000000..168ab1f297 --- /dev/null +++ b/reactor-core/src/test/java/com/baeldung/reactor/NetworkTrafficProducerPushUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.reactor; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class NetworkTrafficProducerPushUnitTest { + + @Test + public void givenFluxWithAsynchronousPushWithListener_whenListenerIsInvoked_thenItemCollectedByTheSubscriber() throws InterruptedException { + List elements = new ArrayList<>(); + + NetworkTrafficProducerPush trafficProducer = new NetworkTrafficProducerPush(); + trafficProducer.subscribe(elements::add); + trafficProducer.onPacket("Packet[A18]"); + + assertThat(elements).containsExactly("Packet[A18]"); + } + +} diff --git a/reactor-core/src/test/java/com/baeldung/reactor/ProgrammaticSequencesUnitTest.java b/reactor-core/src/test/java/com/baeldung/reactor/ProgrammaticSequencesUnitTest.java new file mode 100644 index 0000000000..996ca9e20c --- /dev/null +++ b/reactor-core/src/test/java/com/baeldung/reactor/ProgrammaticSequencesUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.reactor; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ProgrammaticSequencesUnitTest { + + @Test + public void givenFluxWithStatefulImmutableGenerate_whenSubscribeAddItemsToCollect_thenAllItemsAreCollectedByTheSubscriber() throws InterruptedException { + List elements = new ArrayList<>(); + ProgrammaticSequences producer = new ProgrammaticSequences(); + producer.statefulImutableGenerate() + .subscribe(elements::add); + assertThat(elements).hasSize(101); + assertThat(elements).contains("2 + 1 = 3", "2 + 101 = 103"); + } + + @Test + public void givenFluxWithStatefulMutableGenerate_whenSubscribeAddItemsToCollect_thenAllItemsAreCollectedByTheSubscriber() throws InterruptedException { + List elements = new ArrayList<>(); + ProgrammaticSequences producer = new ProgrammaticSequences(); + producer.statefulMutableGenerate() + .subscribe(elements::add); + assertThat(elements).hasSize(102); + assertThat(elements).contains("2 + 0 = 2", "2 + 101 = 103"); + } + + @Test + public void givenFluxWithHandle_whenSubscribeAddItemsToCollect_thenAllItemsAreCollectedByTheSubscriber() throws InterruptedException { + List elements = new ArrayList<>(); + ProgrammaticSequences producer = new ProgrammaticSequences(); + producer.handle() + .subscribe(elements::add); + assertThat(elements).hasSize(5); + assertThat(elements).contains("Elephant nr 2", "Elephant nr 10"); + } + +} diff --git a/spring-all/pom.xml b/spring-all/pom.xml index bab2e431ec..2dc4915bab 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung spring-all 0.1-SNAPSHOT spring-all diff --git a/spring-boot-logging-log4j2/README.md b/spring-boot-logging-log4j2/README.md index 7676bd1919..ea968d7fae 100644 --- a/spring-boot-logging-log4j2/README.md +++ b/spring-boot-logging-log4j2/README.md @@ -1,2 +1,4 @@ ### Relevant Articles: - [Logging in Spring Boot](http://www.baeldung.com/spring-boot-logging) +- [Logging to Graylog with Spring Boot](https://www.baeldung.com/graylog-with-spring-boot) + diff --git a/spring-boot-logging-log4j2/pom.xml b/spring-boot-logging-log4j2/pom.xml index 7220672eaf..38dc5fb341 100644 --- a/spring-boot-logging-log4j2/pom.xml +++ b/spring-boot-logging-log4j2/pom.xml @@ -34,6 +34,20 @@ org.springframework.boot spring-boot-starter-log4j2 + + + + + org.springframework.boot + spring-boot-starter-log4j + 1.3.8.RELEASE + + + org.graylog2 + gelfj + 1.1.16 + compile + @@ -56,6 +70,6 @@ - + com.baeldung.springbootlogging.SpringBootLoggingApplication diff --git a/spring-boot/src/main/java/com/baeldung/graylog/GraylogDemoApplication.java b/spring-boot-logging-log4j2/src/main/java/com/baeldung/graylog/GraylogDemoApplication.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/graylog/GraylogDemoApplication.java rename to spring-boot-logging-log4j2/src/main/java/com/baeldung/graylog/GraylogDemoApplication.java diff --git a/spring-boot/src/main/resources/log4j.xml b/spring-boot-logging-log4j2/src/main/resources/log4j.xml similarity index 100% rename from spring-boot/src/main/resources/log4j.xml rename to spring-boot-logging-log4j2/src/main/resources/log4j.xml diff --git a/spring-boot-mvc/pom.xml b/spring-boot-mvc/pom.xml index 65d23ebfc6..5f6cdff85b 100644 --- a/spring-boot-mvc/pom.xml +++ b/spring-boot-mvc/pom.xml @@ -8,11 +8,11 @@ Module For Spring Boot MVC - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-2 - + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + @@ -23,7 +23,7 @@ org.apache.tomcat.embed tomcat-embed-jasper - + org.glassfish javax.faces @@ -35,18 +35,27 @@ spring-boot-starter-test test - + org.springframework.boot spring-boot-starter-validation - - + + com.rometools rome ${rome.version} + + + org.hibernate.validator + hibernate-validator + + + javax.validation + validation-api + @@ -55,17 +64,17 @@ org.springframework.boot spring-boot-maven-plugin - com.baeldung.springbootmvc.SpringBootMvcApplication - JAR - + com.baeldung.springbootmvc.SpringBootMvcApplication + JAR + - - - 1.10.0 - com.baeldung.springbootmvc.SpringBootMvcApplication - + + + 1.10.0 + com.baeldung.springbootmvc.SpringBootMvcApplication + diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/config/WebConfig.java b/spring-boot-ops/src/main/java/org/baeldung/boot/config/WebConfig.java index 6d8708b06a..6373553837 100644 --- a/spring-boot-ops/src/main/java/org/baeldung/boot/config/WebConfig.java +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/config/WebConfig.java @@ -1,16 +1,17 @@ package org.baeldung.boot.config; +import java.util.List; + import org.baeldung.boot.converter.GenericBigDecimalConverter; +import org.baeldung.boot.converter.StringToAbstractEntityConverterFactory; import org.baeldung.boot.converter.StringToEmployeeConverter; -import org.baeldung.boot.converter.StringToEnumConverterFactory; +import org.baeldung.boot.converter.StringToEnumConverter; import org.baeldung.boot.web.resolver.HeaderVersionArgumentResolver; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import java.util.List; - @Configuration public class WebConfig implements WebMvcConfigurer { @@ -22,7 +23,8 @@ public class WebConfig implements WebMvcConfigurer { @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(new StringToEmployeeConverter()); - registry.addConverterFactory(new StringToEnumConverterFactory()); + registry.addConverter(new StringToEnumConverter()); + registry.addConverterFactory(new StringToAbstractEntityConverterFactory()); registry.addConverter(new GenericBigDecimalConverter()); } } diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToAbstractEntityConverterFactory.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToAbstractEntityConverterFactory.java new file mode 100644 index 0000000000..9e7fd8f858 --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToAbstractEntityConverterFactory.java @@ -0,0 +1,39 @@ +package org.baeldung.boot.converter; + +import org.baeldung.boot.domain.AbstractEntity; +import org.baeldung.boot.domain.Bar; +import org.baeldung.boot.domain.Foo; +import org.springframework.core.convert.converter.Converter; +import org.springframework.core.convert.converter.ConverterFactory; + +public class StringToAbstractEntityConverterFactory implements ConverterFactory{ + + @Override + public Converter getConverter(Class targetClass) { + + return new StringToAbstractEntityConverter<>(targetClass); + } + + + private static class StringToAbstractEntityConverter implements Converter { + + private Class targetClass; + + public StringToAbstractEntityConverter(Class targetClass) { + this.targetClass = targetClass; + } + + @Override + public T convert(String source) { + long id = Long.parseLong(source); + if(this.targetClass == Foo.class) { + return (T) new Foo(id); + } + else if(this.targetClass == Bar.class) { + return (T) new Bar(id); + } else { + return null; + } + } + } +} diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEnumConverter.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEnumConverter.java new file mode 100644 index 0000000000..498b44abec --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEnumConverter.java @@ -0,0 +1,12 @@ +package org.baeldung.boot.converter; + +import org.baeldung.boot.domain.Modes; +import org.springframework.core.convert.converter.Converter; + +public class StringToEnumConverter implements Converter { + + @Override + public Modes convert(String from) { + return Modes.valueOf(from); + } +} \ No newline at end of file diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java deleted file mode 100644 index 6fa51bfdcc..0000000000 --- a/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.baeldung.boot.converter; - -import org.springframework.core.convert.converter.Converter; -import org.springframework.core.convert.converter.ConverterFactory; -import org.springframework.stereotype.Component; - -@Component -public class StringToEnumConverterFactory implements ConverterFactory { - - private static class StringToEnumConverter implements Converter { - - private Class enumType; - - public StringToEnumConverter(Class enumType) { - this.enumType = enumType; - } - - public T convert(String source) { - return (T) Enum.valueOf(this.enumType, source.trim()); - } - } - - @Override - public Converter getConverter(final Class targetType) { - return new StringToEnumConverter(targetType); - } -} diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/converter/controller/AbstractEntityController.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/controller/AbstractEntityController.java new file mode 100644 index 0000000000..d3c012ba31 --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/controller/AbstractEntityController.java @@ -0,0 +1,31 @@ +package org.baeldung.boot.converter.controller; + +import org.baeldung.boot.domain.Bar; +import org.baeldung.boot.domain.Foo; +import org.baeldung.boot.domain.Modes; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/string-to-abstract") +public class AbstractEntityController { + + @GetMapping("/foo/{foo}") + public ResponseEntity getStringToFoo(@PathVariable Foo foo) { + return ResponseEntity.ok(foo); + } + + @GetMapping("/bar/{bar}") + public ResponseEntity getStringToBar(@PathVariable Bar bar) { + return ResponseEntity.ok(bar); + } + + @GetMapping + public ResponseEntity getStringToMode(@RequestParam("mode") Modes mode) { + return ResponseEntity.ok(mode); + } +} diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/domain/AbstractEntity.java b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/AbstractEntity.java new file mode 100644 index 0000000000..30e0d1e5fe --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/AbstractEntity.java @@ -0,0 +1,10 @@ +package org.baeldung.boot.domain; + +public abstract class AbstractEntity { + + long id; + public AbstractEntity(long id){ + this.id = id; + } + +} diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Bar.java b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Bar.java new file mode 100644 index 0000000000..724f5e4bca --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Bar.java @@ -0,0 +1,29 @@ +package org.baeldung.boot.domain; + +public class Bar extends AbstractEntity { + + private int value; + + public Bar(long id) { + super(id); + } + + public Bar(long id, int value) { + super(id); + this.value = value; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + @Override + public String toString() { + return "Bar [value=" + value + ", id=" + id + "]"; + } + +} diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Foo.java b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Foo.java new file mode 100644 index 0000000000..a2ff354e59 --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Foo.java @@ -0,0 +1,31 @@ +package org.baeldung.boot.domain; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric; +public class Foo extends AbstractEntity { + + private String name; + + public Foo(long id) { + super(id); + name = randomAlphanumeric(4); + } + + public Foo(long id, String name) { + super(id); + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Foo [name=" + name + ", id=" + id + "]"; + } + +} diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 9a9f44e1cf..f09ab27fb5 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -34,5 +34,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Introduction to Chaos Monkey](https://www.baeldung.com/spring-boot-chaos-monkey) - [Spring Component Scanning](https://www.baeldung.com/spring-component-scanning) - [Load Spring Boot Properties From a JSON File](https://www.baeldung.com/spring-boot-json-properties) -- [Display Auto-Configuration Report in Spring Boot](https://www.baeldung.com/spring-boot-auto-configuration-report) -- [Logging to Graylog with Spring Boot](https://www.baeldung.com/graylog-with-spring-boot) +- [Display Auto-Configuration Report in Spring Boot](https://www.baeldung.com/spring-boot-auto-configuration-report) \ No newline at end of file diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index 0ea6b6156f..f16460b7c3 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -1,9 +1,7 @@ 4.0.0 - com.baeldung spring-boot - 0.0.1-SNAPSHOT war spring-boot This is simple boot application for Spring boot actuator test @@ -145,19 +143,10 @@ chaos-monkey-spring-boot ${chaos.monkey.version} - - + - - org.springframework.boot - spring-boot-starter-log4j - 1.3.8.RELEASE - - - org.graylog2 - gelfj - 1.1.16 - compile + javax.validation + validation-api @@ -226,7 +215,7 @@ - org.baeldung.demo.DemoApplication + com.baeldung.intro.App 8.5.11 2.4.1.Final 1.9.0 @@ -234,7 +223,6 @@ 3.6.0 3.2.0 18.0 - 1.2.0 2.2.4 diff --git a/spring-custom-aop/README.MD b/spring-custom-aop/README.MD deleted file mode 100644 index 9fe18aaacc..0000000000 --- a/spring-custom-aop/README.MD +++ /dev/null @@ -1,13 +0,0 @@ -###The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring - -###Relevant Articles: -- [Quick Guide to @RestClientTest in Spring Boot](http://www.baeldung.com/restclienttest-in-spring-boot) -- [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters) -- [A Guide to Spring in Eclipse STS](http://www.baeldung.com/eclipse-sts-spring) -- [Introduction to WebJars](http://www.baeldung.com/maven-webjars) -- [Create a Fat Jar App with Spring Boot](http://www.baeldung.com/deployable-fat-jar-spring-boot) -- [The @ServletComponentScan Annotation in Spring Boot](http://www.baeldung.com/spring-servletcomponentscan) -- [A Custom Data Binder in Spring MVC](http://www.baeldung.com/spring-mvc-custom-data-binder) -- [Intro to Building an Application with Spring Boot](http://www.baeldung.com/intro-to-spring-boot) -- [How to Register a Servlet in a Java Web Application](http://www.baeldung.com/register-servlet) diff --git a/spring-custom-aop/pom.xml b/spring-custom-aop/pom.xml deleted file mode 100644 index f0b1dbb5ac..0000000000 --- a/spring-custom-aop/pom.xml +++ /dev/null @@ -1,155 +0,0 @@ - - 4.0.0 - com.baeldung - spring-custom-aop - 0.0.1-SNAPSHOT - war - spring-boot - This is simple boot application for Spring boot actuator test - - - parent-boot-1 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-1 - - - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - org.springframework.boot - spring-boot-starter-actuator - - - - org.springframework.boot - spring-boot-starter-security - - - - org.springframework.boot - spring-boot-starter-tomcat - - - - org.apache.tomcat.embed - tomcat-embed-core - ${tomcat.version} - - - - org.apache.tomcat.embed - tomcat-embed-jasper - ${tomcat.version} - - - - io.dropwizard.metrics - metrics-core - - - - com.h2database - h2 - - - - org.springframework.boot - spring-boot-starter - - - com.jayway.jsonpath - json-path - test - - - org.springframework.boot - spring-boot-starter-mail - - - org.subethamail - subethasmtp - ${subethasmtp.version} - test - - - - org.webjars - bootstrap - ${bootstrap.version} - - - org.webjars - jquery - ${jquery.version} - - - - com.google.guava - guava - ${guava.version} - - - - org.apache.tomcat - tomcat-servlet-api - ${tomee-servlet-api.version} - provided - - - - - - spring-boot - - - src/main/resources - true - - - - - - - org.apache.maven.plugins - maven-war-plugin - - - - pl.project13.maven - git-commit-id-plugin - ${git-commit-id-plugin.version} - - - - - - - - - org.baeldung.boot.DemoApplication - 4.3.4.RELEASE - 2.2.1 - 3.1.1 - 3.3.7-1 - 3.1.7 - 8.5.11 - 18.0 - 8.0.43 - - - diff --git a/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java b/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java deleted file mode 100644 index b4d416dd96..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.annotation.servletcomponentscan; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.servlet.ServletComponentScan; - -/** - * using the following annotations are equivalent: - *
  • - * @ServletComponentScan - *
  • - * @ServletComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components") - *
  • - * @ServletComponentScan(basePackageClasses = {AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class}) - *
- */ -@SpringBootApplication -@ServletComponentScan("com.baeldung.annotation.servletcomponentscan.components") -public class SpringBootAnnotatedApp { - - public static void main(String[] args) { - SpringApplication.run(SpringBootAnnotatedApp.class, args); - } - -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java b/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java deleted file mode 100644 index 8a39078aac..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.annotation.servletcomponentscan; - -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; - -@SpringBootApplication -@ComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components") -public class SpringBootPlainApp { - - public static void main(String[] args) { - } - -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java b/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java deleted file mode 100644 index b1bdc7d781..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.annotation.servletcomponentscan.components; - -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import javax.servlet.annotation.WebListener; - -@WebListener -public class AttrListener implements ServletContextListener { - - @Override - public void contextInitialized(ServletContextEvent servletContextEvent) { - servletContextEvent.getServletContext().setAttribute("servlet-context-attr", "test"); - System.out.println("context init"); - } - - @Override - public void contextDestroyed(ServletContextEvent servletContextEvent) { - System.out.println("context destroy"); - } - -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java b/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java deleted file mode 100644 index d8192c2cb1..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.annotation.servletcomponentscan.components; - -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; - -@WebServlet(name = "echo servlet", urlPatterns = "/echo") -public class EchoServlet extends HttpServlet { - - @Override - public void doPost(HttpServletRequest request, HttpServletResponse response) { - try { - Path path = File.createTempFile("echo", "tmp").toPath(); - Files.copy(request.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); - Files.copy(path, response.getOutputStream()); - Files.delete(path); - } catch (IOException e) { - e.printStackTrace(); - } - } -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java b/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java deleted file mode 100644 index 146e5ae386..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.annotation.servletcomponentscan.components; - -import javax.servlet.*; -import javax.servlet.annotation.WebFilter; -import javax.servlet.annotation.WebInitParam; -import java.io.IOException; - -@WebFilter(urlPatterns = "/hello", description = "a filter for hello servlet", initParams = { @WebInitParam(name = "msg", value = "filtering ") }, filterName = "hello filter", servletNames = { "echo servlet" }) -public class HelloFilter implements Filter { - - private FilterConfig filterConfig; - - @Override - public void init(FilterConfig filterConfig) throws ServletException { - System.out.println("filter init"); - this.filterConfig = filterConfig; - } - - @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { - servletResponse.getOutputStream().print(filterConfig.getInitParameter("msg")); - filterChain.doFilter(servletRequest, servletResponse); - } - - @Override - public void destroy() { - System.out.println("filter destroy"); - } - -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java b/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java deleted file mode 100644 index 5269c1bf29..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.annotation.servletcomponentscan.components; - -import javax.servlet.ServletConfig; -import javax.servlet.annotation.WebInitParam; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -@WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello") }) -public class HelloServlet extends HttpServlet { - - private ServletConfig servletConfig; - - @Override - public void init(ServletConfig servletConfig) { - this.servletConfig = servletConfig; - } - - @Override - public void doGet(HttpServletRequest request, HttpServletResponse response) { - try { - response.getOutputStream().write(servletConfig.getInitParameter("msg").getBytes()); - } catch (IOException e) { - e.printStackTrace(); - } - } - -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/git/CommitIdApplication.java b/spring-custom-aop/src/main/java/com/baeldung/git/CommitIdApplication.java deleted file mode 100644 index cd696eae70..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/git/CommitIdApplication.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.git; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.core.io.ClassPathResource; - -@SpringBootApplication(scanBasePackages = { "com.baeldung.git" }) -public class CommitIdApplication { - public static void main(String[] args) { - SpringApplication.run(CommitIdApplication.class, args); - } - - @Bean - public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() { - PropertySourcesPlaceholderConfigurer c = new PropertySourcesPlaceholderConfigurer(); - c.setLocation(new ClassPathResource("git.properties")); - c.setIgnoreResourceNotFound(true); - c.setIgnoreUnresolvablePlaceholders(true); - return c; - } -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/git/CommitInfoController.java b/spring-custom-aop/src/main/java/com/baeldung/git/CommitInfoController.java deleted file mode 100644 index 6d44e02ec2..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/git/CommitInfoController.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.git; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.HashMap; -import java.util.Map; - -@RestController -public class CommitInfoController { - - @Value("${git.commit.message.short}") - private String commitMessage; - - @Value("${git.branch}") - private String branch; - - @Value("${git.commit.id}") - private String commitId; - - @RequestMapping("/commitId") - public Map getCommitId() { - Map result = new HashMap<>(); - result.put("Commit message", commitMessage); - result.put("Commit branch", branch); - result.put("Commit id", commitId); - return result; - } -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/git/README.md b/spring-custom-aop/src/main/java/com/baeldung/git/README.md deleted file mode 100644 index 7e6a597c28..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/git/README.md +++ /dev/null @@ -1,2 +0,0 @@ -### Relevant Articles: -- [Injecting Git Information Into Spring](http://www.baeldung.com/spring-git-information) diff --git a/spring-custom-aop/src/main/java/com/baeldung/internationalization/InternationalizationApp.java b/spring-custom-aop/src/main/java/com/baeldung/internationalization/InternationalizationApp.java deleted file mode 100644 index c92d1c32e6..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/internationalization/InternationalizationApp.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.internationalization; - -import javax.annotation.security.RolesAllowed; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class InternationalizationApp { - @RolesAllowed("*") - public static void main(String[] args) { - System.setProperty("security.basic.enabled", "false"); - SpringApplication.run(InternationalizationApp.class, args); - } -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/internationalization/config/MvcConfig.java b/spring-custom-aop/src/main/java/com/baeldung/internationalization/config/MvcConfig.java deleted file mode 100644 index 59f7fd3ba5..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/internationalization/config/MvcConfig.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.internationalization.config; - -import java.util.Locale; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.LocaleResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; -import org.springframework.web.servlet.i18n.SessionLocaleResolver; - -@Configuration -@EnableWebMvc -@ComponentScan(basePackages = "com.baeldung.internationalization.config") -public class MvcConfig extends WebMvcConfigurerAdapter { - - @Bean - public LocaleResolver localeResolver() { - SessionLocaleResolver slr = new SessionLocaleResolver(); - slr.setDefaultLocale(Locale.US); - return slr; - } - - @Bean - public LocaleChangeInterceptor localeChangeInterceptor() { - LocaleChangeInterceptor lci = new LocaleChangeInterceptor(); - lci.setParamName("lang"); - return lci; - } - - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(localeChangeInterceptor()); - } -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/internationalization/config/PageController.java b/spring-custom-aop/src/main/java/com/baeldung/internationalization/config/PageController.java deleted file mode 100644 index 96a534b853..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/internationalization/config/PageController.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.internationalization.config; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; - -@Controller -public class PageController { - - @GetMapping("/international") - public String getInternationalPage() { - return "international"; - } - -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/intro/App.java b/spring-custom-aop/src/main/java/com/baeldung/intro/App.java deleted file mode 100644 index 77cdf4ddb9..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/intro/App.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.intro; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class App { - public static void main(String[] args) { - SpringApplication.run(App.class, args); - } -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/intro/controller/HomeController.java b/spring-custom-aop/src/main/java/com/baeldung/intro/controller/HomeController.java deleted file mode 100644 index 5c0cb2d2de..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/intro/controller/HomeController.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.intro.controller; - -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class HomeController { - - @RequestMapping("/") - public String root() { - return "Index Page"; - } - - @RequestMapping("/local") - public String local() { - return "/local"; - } -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/servlets/ApplicationMain.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/ApplicationMain.java deleted file mode 100644 index a6ea3757fe..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/servlets/ApplicationMain.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.servlets; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.support.SpringBootServletInitializer; - -@SpringBootApplication -public class ApplicationMain extends SpringBootServletInitializer { - - public static void main(String[] args) { - SpringApplication.run(ApplicationMain.class, args); - } - - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { - return application.sources(ApplicationMain.class); - } -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java deleted file mode 100644 index eadd40355a..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.servlets.configuration; - -import org.springframework.web.WebApplicationInitializer; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.context.support.XmlWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -public class WebAppInitializer implements WebApplicationInitializer { - - public void onStartup(ServletContext container) throws ServletException { - - AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); - ctx.register(WebMvcConfigure.class); - ctx.setServletContext(container); - - ServletRegistration.Dynamic servletOne = container.addServlet("SpringProgrammaticDispatcherServlet", new DispatcherServlet(ctx)); - servletOne.setLoadOnStartup(1); - servletOne.addMapping("/"); - - XmlWebApplicationContext xctx = new XmlWebApplicationContext(); - xctx.setConfigLocation("/WEB-INF/context.xml"); - xctx.setServletContext(container); - - ServletRegistration.Dynamic servletTwo = container.addServlet("SpringProgrammaticXMLDispatcherServlet", new DispatcherServlet(xctx)); - servletTwo.setLoadOnStartup(1); - servletTwo.addMapping("/"); - } - -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java deleted file mode 100644 index 8dea814bc7..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.servlets.configuration; - -import org.springframework.boot.web.support.ErrorPageFilter; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.resource.PathResourceResolver; -import org.springframework.web.servlet.view.InternalResourceViewResolver; - -@Configuration -public class WebMvcConfigure extends WebMvcConfigurerAdapter { - - @Bean - public ViewResolver getViewResolver() { - InternalResourceViewResolver resolver = new InternalResourceViewResolver(); - resolver.setPrefix("/WEB-INF/"); - resolver.setSuffix(".jsp"); - return resolver; - } - - @Override - public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { - configurer.enable(); - } - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver()); - } - - @Bean - public ErrorPageFilter errorPageFilter() { - return new ErrorPageFilter(); - } -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/servlets/props/Constants.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/props/Constants.java deleted file mode 100644 index 6345d1f969..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/servlets/props/Constants.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.servlets.props; - -import org.springframework.beans.factory.annotation.Autowired; - -import java.util.Properties; - -public final class Constants { - - @Autowired - PropertySourcesLoader psl; - - public static final String breakLine = System.getProperty("line.separator"); - private static final PropertyLoader pl = new PropertyLoader(); - private static final Properties mainProps = pl.getProperties("custom.properties"); - public static final String DISPATCHER_SERVLET_NAME = mainProps.getProperty("dispatcher.servlet.name"); - public static final String DISPATCHER_SERVLET_MAPPING = mainProps.getProperty("dispatcher.servlet.mapping"); - private final String EXAMPLE_SERVLET_NAME = psl.getProperty("example.servlet.name"); - private final String EXAMPLE_SERVLET_MAPPING = psl.getProperty("example.servlet.mapping"); - -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/servlets/props/PropertyLoader.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/props/PropertyLoader.java deleted file mode 100644 index c29da45929..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/servlets/props/PropertyLoader.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.servlets.props; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -public class PropertyLoader { - private static final Logger log = LoggerFactory.getLogger(PropertyLoader.class); - - public Properties getProperties(String file) { - Properties prop = new Properties(); - InputStream input = null; - try { - input = getClass().getResourceAsStream(file); - prop.load(input); - if (input != null) { - input.close(); - } - } catch (IOException ex) { - log.error("IOException: " + ex); - } - return prop; - } -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java deleted file mode 100644 index 21e8949653..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.servlets.props; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.ConfigurableEnvironment; - -@Configuration -@ComponentScan(basePackages = { "com.baeldung.*" }) -@PropertySource("classpath:custom.properties") -public class PropertySourcesLoader { - - private static final Logger log = LoggerFactory.getLogger(PropertySourcesLoader.class); - - @Autowired - ConfigurableEnvironment env; - - public String getProperty(String key) { - return env.getProperty(key); - } -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java deleted file mode 100644 index 49dd9404b7..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.servlets.servlets; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.PrintWriter; - -public class GenericCustomServlet extends HttpServlet { - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); - out.println("

Hello World

"); - } -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java deleted file mode 100644 index 992976ca0e..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.servlets.servlets.javaee; - -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -@WebServlet(name = "AnnotationServlet", description = "Example Servlet Using Annotations", urlPatterns = { "/annotationservlet" }) -public class AnnotationServlet extends HttpServlet { - private static final long serialVersionUID = 1L; - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - request.getRequestDispatcher("/annotationservlet.jsp").forward(request, response); - } -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java deleted file mode 100644 index c7b373064f..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.servlets.servlets.javaee; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.PrintWriter; - -public class EEWebXmlServlet extends HttpServlet { - - private static final long serialVersionUID = 1L; - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); - out.println("

Hello World

"); - } -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java deleted file mode 100644 index e3c225d429..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.servlets.servlets.springboot; - -import com.baeldung.servlets.servlets.GenericCustomServlet; -import org.springframework.boot.web.servlet.ServletRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class SpringRegistrationBeanServlet { - - @Bean - public ServletRegistrationBean genericCustomServlet() { - ServletRegistrationBean bean = new ServletRegistrationBean(new GenericCustomServlet(), "/springregistrationbeanservlet/*"); - bean.setLoadOnStartup(1); - return bean; - } -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java deleted file mode 100644 index 9e460d03a8..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.servlets.servlets.springboot.embedded; - -import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; -import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class EmbeddedTomcatExample { - - @Bean - public EmbeddedServletContainerFactory servletContainer() { - TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(); - return tomcat; - } -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/utils/Application.java b/spring-custom-aop/src/main/java/com/baeldung/utils/Application.java deleted file mode 100644 index 46cf3fb4aa..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/utils/Application.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.utils; - -import javax.annotation.security.RolesAllowed; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; - -@SpringBootApplication -@ComponentScan(basePackages = "com.baeldung.utils") -public class Application { - - @RolesAllowed("*") - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/utils/controller/UtilsController.java b/spring-custom-aop/src/main/java/com/baeldung/utils/controller/UtilsController.java deleted file mode 100644 index 8c7f2f932a..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/utils/controller/UtilsController.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.utils.controller; - -import javax.servlet.http.HttpServletRequest; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.ServletRequestUtils; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.util.WebUtils; - -@Controller -public class UtilsController { - - @GetMapping("/utils") - public String webUtils(Model model) { - return "utils"; - } - - @PostMapping("/setParam") - public String post(HttpServletRequest request, Model model) { - String param = ServletRequestUtils.getStringParameter(request, "param", "DEFAULT"); - - // Long param = ServletRequestUtils.getLongParameter(request, "param",1L); - // boolean param = ServletRequestUtils.getBooleanParameter(request, "param", true); - // double param = ServletRequestUtils.getDoubleParameter(request, "param", 1000); - // float param = ServletRequestUtils.getFloatParameter(request, "param", (float) 1.00); - // int param = ServletRequestUtils.getIntParameter(request, "param", 100); - - // try { - // ServletRequestUtils.getRequiredStringParameter(request, "param"); - // } catch (ServletRequestBindingException e) { - // e.printStackTrace(); - // } - - WebUtils.setSessionAttribute(request, "parameter", param); - model.addAttribute("parameter", "You set: " + (String) WebUtils.getSessionAttribute(request, "parameter")); - return "utils"; - } - - @GetMapping("/other") - public String other(HttpServletRequest request, Model model) { - String param = (String) WebUtils.getSessionAttribute(request, "parameter"); - model.addAttribute("parameter", param); - return "other"; - } - -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/webjar/TestController.java b/spring-custom-aop/src/main/java/com/baeldung/webjar/TestController.java deleted file mode 100644 index e8e7fd5ce9..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/webjar/TestController.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.webjar; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.RequestMapping; - -@Controller -public class TestController { - - @RequestMapping(value = "/") - public String welcome(Model model) { - return "index"; - } - -} diff --git a/spring-custom-aop/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java b/spring-custom-aop/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java deleted file mode 100644 index 2397861f1d..0000000000 --- a/spring-custom-aop/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.webjar; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class WebjarsdemoApplication { - - public static void main(String[] args) { - SpringApplication.run(WebjarsdemoApplication.class, args); - } -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/Application.java b/spring-custom-aop/src/main/java/org/baeldung/Application.java deleted file mode 100644 index aae0c427a9..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/Application.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung; - -import org.springframework.boot.SpringApplication; -import org.springframework.context.ApplicationContext; - -@org.springframework.boot.autoconfigure.SpringBootApplication -public class Application { - private static ApplicationContext applicationContext; - - public static void main(String[] args) { - applicationContext = SpringApplication.run(Application.class, args); - } -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/boot/DemoApplication.java b/spring-custom-aop/src/main/java/org/baeldung/boot/DemoApplication.java deleted file mode 100644 index e61d140396..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/boot/DemoApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.boot; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class DemoApplication { - - public static void main(String[] args) { - System.setProperty("spring.config.name", "demo"); - SpringApplication.run(DemoApplication.class, args); - } - -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/boot/components/FooService.java b/spring-custom-aop/src/main/java/org/baeldung/boot/components/FooService.java deleted file mode 100644 index 4ff8e9fdd4..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/boot/components/FooService.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.boot.components; - -import org.baeldung.boot.model.Foo; -import org.baeldung.boot.repository.FooRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class FooService { - - @Autowired - private FooRepository fooRepository; - - public Foo getFooWithId(Integer id) throws Exception { - return fooRepository.findOne(id); - } - - public Foo getFooWithName(String name) { - return fooRepository.findByName(name); - } -} \ No newline at end of file diff --git a/spring-custom-aop/src/main/java/org/baeldung/boot/exceptions/CommonException.java b/spring-custom-aop/src/main/java/org/baeldung/boot/exceptions/CommonException.java deleted file mode 100644 index e03b859eab..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/boot/exceptions/CommonException.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung.boot.exceptions; - -public class CommonException extends RuntimeException { - - /** - * - */ - private static final long serialVersionUID = 3080004140659213332L; - - public CommonException(String message) { - super(message); - } -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java b/spring-custom-aop/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java deleted file mode 100644 index 0b04bd2759..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.baeldung.boot.exceptions; - -public class FooNotFoundException extends RuntimeException { - - /** - * - */ - private static final long serialVersionUID = 9042200028456133589L; - - public FooNotFoundException(String message) { - super(message); - } -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/boot/model/Foo.java b/spring-custom-aop/src/main/java/org/baeldung/boot/model/Foo.java deleted file mode 100644 index d373e25b85..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/boot/model/Foo.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.baeldung.boot.model; - -import java.io.Serializable; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; - -@Entity -public class Foo implements Serializable { - private static final long serialVersionUID = 1L; - @Id - @GeneratedValue - private Integer id; - private String name; - - public Foo() { - } - - public Foo(String name) { - this.name = name; - } - - public Foo(Integer id, String name) { - super(); - this.id = id; - this.name = name; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/boot/repository/FooRepository.java b/spring-custom-aop/src/main/java/org/baeldung/boot/repository/FooRepository.java deleted file mode 100644 index 09d6975dba..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/boot/repository/FooRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.boot.repository; - -import org.baeldung.boot.model.Foo; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface FooRepository extends JpaRepository { - public Foo findByName(String name); -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/boot/service/FooController.java b/spring-custom-aop/src/main/java/org/baeldung/boot/service/FooController.java deleted file mode 100644 index d400c3bf9e..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/boot/service/FooController.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.baeldung.boot.service; - -import org.baeldung.boot.components.FooService; -import org.baeldung.boot.model.Foo; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class FooController { - - @Autowired - private FooService fooService; - - @GetMapping("/{id}") - public Foo getFooWithId(@PathVariable Integer id) throws Exception { - return fooService.getFooWithId(id); - } - - @GetMapping("/") - public Foo getFooWithName(@RequestParam String name) throws Exception { - return fooService.getFooWithName(name); - } -} \ No newline at end of file diff --git a/spring-custom-aop/src/main/java/org/baeldung/client/Details.java b/spring-custom-aop/src/main/java/org/baeldung/client/Details.java deleted file mode 100644 index 2ae3adc38f..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/client/Details.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.baeldung.client; - -public class Details { - - private String name; - - private String login; - - public Details() { - } - - public Details(String name, String login) { - this.name = name; - this.login = login; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getLogin() { - return login; - } - - public void setLogin(String login) { - this.login = login; - } -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/client/DetailsServiceClient.java b/spring-custom-aop/src/main/java/org/baeldung/client/DetailsServiceClient.java deleted file mode 100644 index 51fa7c6181..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/client/DetailsServiceClient.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.baeldung.client; - -import org.springframework.boot.web.client.RestTemplateBuilder; -import org.springframework.stereotype.Service; -import org.springframework.web.client.RestTemplate; - -@Service -public class DetailsServiceClient { - - private final RestTemplate restTemplate; - - public DetailsServiceClient(RestTemplateBuilder restTemplateBuilder) { - restTemplate = restTemplateBuilder.build(); - } - - public Details getUserDetails(String name) { - return restTemplate.getForObject("/{name}/details", Details.class, name); - } - -} \ No newline at end of file diff --git a/spring-custom-aop/src/main/java/org/baeldung/common/error/MyCustomErrorController.java b/spring-custom-aop/src/main/java/org/baeldung/common/error/MyCustomErrorController.java deleted file mode 100644 index a50b88f94b..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/common/error/MyCustomErrorController.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.baeldung.common.error; - -import org.springframework.boot.autoconfigure.web.ErrorController; -import org.springframework.web.bind.annotation.RequestMapping; - -public class MyCustomErrorController implements ErrorController { - - private static final String PATH = "/error"; - - public MyCustomErrorController() { - // TODO Auto-generated constructor stub - } - - @RequestMapping(value = PATH) - public String error() { - return "Error heaven"; - } - - @Override - public String getErrorPath() { - return PATH; - } - -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java b/spring-custom-aop/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java deleted file mode 100644 index 774cf1b970..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.baeldung.common.error; - -import org.springframework.boot.web.servlet.ServletRegistrationBean; - -import javax.servlet.Servlet; - -public class SpringHelloServletRegistrationBean extends ServletRegistrationBean { - - public SpringHelloServletRegistrationBean() { - } - - public SpringHelloServletRegistrationBean(Servlet servlet, String... urlMappings) { - super(servlet, urlMappings); - } -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/common/error/controller/ErrorController.java b/spring-custom-aop/src/main/java/org/baeldung/common/error/controller/ErrorController.java deleted file mode 100644 index 9e63418a02..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/common/error/controller/ErrorController.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.common.error.controller; - -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class ErrorController { - - public ErrorController() { - } - - @RequestMapping("/400") - String error400() { - return "Error Code: 400 occured."; - } - - @RequestMapping("/errorHeaven") - String errorHeaven() { - return "You have reached the heaven of errors!!!"; - } - -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java b/spring-custom-aop/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java deleted file mode 100644 index 3d239f8944..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.baeldung.common.properties; - -import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; -import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; -import org.springframework.boot.web.servlet.ErrorPage; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Component; - -@Component -public class MyServletContainerCustomizationBean implements EmbeddedServletContainerCustomizer { - - public MyServletContainerCustomizationBean() { - - } - - @Override - public void customize(ConfigurableEmbeddedServletContainer container) { - container.setPort(8084); - container.setContextPath("/springbootapp"); - - container.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400")); - container.addErrorPages(new ErrorPage("/errorHeaven")); - } - -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java b/spring-custom-aop/src/main/java/org/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java deleted file mode 100644 index 07f57ec1ef..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.common.resources; - -import java.util.Objects; -import java.util.concurrent.ExecutorService; - -import org.springframework.boot.ExitCodeGenerator; - -public class ExecutorServiceExitCodeGenerator implements ExitCodeGenerator { - - private ExecutorService executorService; - - public ExecutorServiceExitCodeGenerator(ExecutorService executorService) { - } - - @Override - public int getExitCode() { - int returnCode = 0; - try { - if (!Objects.isNull(executorService)) { - executorService.shutdownNow(); - returnCode = 1; - } - } catch (SecurityException ex) { - returnCode = 0; - } - return returnCode; - } - -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/config/WebConfig.java b/spring-custom-aop/src/main/java/org/baeldung/config/WebConfig.java deleted file mode 100644 index 4ef407823e..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/config/WebConfig.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.config; - -import org.baeldung.web.resolver.HeaderVersionArgumentResolver; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.method.support.HandlerMethodArgumentResolver; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -import java.util.List; - -@Configuration -public class WebConfig extends WebMvcConfigurerAdapter { - - @Override - public void addArgumentResolvers(final List argumentResolvers) { - argumentResolvers.add(new HeaderVersionArgumentResolver()); - } -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/controller/GenericEntityController.java b/spring-custom-aop/src/main/java/org/baeldung/controller/GenericEntityController.java deleted file mode 100644 index 7d1ad7d899..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/controller/GenericEntityController.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.baeldung.controller; - -import org.baeldung.domain.GenericEntity; -import org.baeldung.domain.Modes; -import org.baeldung.web.resolver.Version; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.List; - -@RestController -public class GenericEntityController { - private List entityList = new ArrayList<>(); - - { - entityList.add(new GenericEntity(1l, "entity_1")); - entityList.add(new GenericEntity(2l, "entity_2")); - entityList.add(new GenericEntity(3l, "entity_3")); - entityList.add(new GenericEntity(4l, "entity_4")); - } - - @RequestMapping("/entity/all") - public List findAll() { - return entityList; - } - - @RequestMapping(value = "/entity", method = RequestMethod.POST) - public GenericEntity addEntity(GenericEntity entity) { - entityList.add(entity); - return entity; - } - - @RequestMapping("/entity/findby/{id}") - public GenericEntity findById(@PathVariable Long id) { - return entityList.stream().filter(entity -> entity.getId().equals(id)).findFirst().get(); - } - - @GetMapping("/entity/findbydate/{date}") - public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) { - return entityList.stream().findFirst().get(); - } - - @GetMapping("/entity/findbymode/{mode}") - public GenericEntity findByEnum(@PathVariable("mode") Modes mode) { - return entityList.stream().findFirst().get(); - } - - @GetMapping("/entity/findbyversion") - public ResponseEntity findByVersion(@Version String version) { - return version != null ? new ResponseEntity(entityList.stream().findFirst().get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND); - } -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/controller/servlet/HelloWorldServlet.java b/spring-custom-aop/src/main/java/org/baeldung/controller/servlet/HelloWorldServlet.java deleted file mode 100644 index fc8fefd77e..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/controller/servlet/HelloWorldServlet.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.baeldung.controller.servlet; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Objects; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -public class HelloWorldServlet extends HttpServlet { - private static final long serialVersionUID = 1L; - - public HelloWorldServlet() { - super(); - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - PrintWriter out = null; - try { - out = response.getWriter(); - out.println("HelloWorldServlet: GET METHOD"); - out.flush(); - } finally { - if (!Objects.isNull(out)) - out.close(); - } - } - - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - PrintWriter out = null; - try { - out = response.getWriter(); - out.println("HelloWorldServlet: POST METHOD"); - out.flush(); - } finally { - if (!Objects.isNull(out)) - out.close(); - } - } - -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/controller/servlet/SpringHelloWorldServlet.java b/spring-custom-aop/src/main/java/org/baeldung/controller/servlet/SpringHelloWorldServlet.java deleted file mode 100644 index 16cff5b1fa..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/controller/servlet/SpringHelloWorldServlet.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.baeldung.controller.servlet; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Objects; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -public class SpringHelloWorldServlet extends HttpServlet { - private static final long serialVersionUID = 1L; - - public SpringHelloWorldServlet() { - super(); - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - PrintWriter out = null; - try { - out = response.getWriter(); - out.println("SpringHelloWorldServlet: GET METHOD"); - out.flush(); - } finally { - if (!Objects.isNull(out)) - out.close(); - } - } - - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - PrintWriter out = null; - try { - out = response.getWriter(); - out.println("SpringHelloWorldServlet: POST METHOD"); - out.flush(); - } finally { - if (!Objects.isNull(out)) - out.close(); - } - } - -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/converter/StringToEnumConverterFactory.java b/spring-custom-aop/src/main/java/org/baeldung/converter/StringToEnumConverterFactory.java deleted file mode 100644 index 17c6fd06de..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/converter/StringToEnumConverterFactory.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.baeldung.converter; - -import org.springframework.core.convert.converter.Converter; -import org.springframework.core.convert.converter.ConverterFactory; -import org.springframework.stereotype.Component; - -@Component -public class StringToEnumConverterFactory implements ConverterFactory { - - private static class StringToEnumConverter implements Converter { - - private Class enumType; - - public StringToEnumConverter(Class enumType) { - this.enumType = enumType; - } - - public T convert(String source) { - return (T) Enum.valueOf(this.enumType, source.trim()); - } - } - - @Override - public Converter getConverter(final Class targetType) { - return new StringToEnumConverter(targetType); - } -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/converter/StringToLocalDateTimeConverter.java b/spring-custom-aop/src/main/java/org/baeldung/converter/StringToLocalDateTimeConverter.java deleted file mode 100644 index cbb9e6ddb4..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/converter/StringToLocalDateTimeConverter.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.converter; - -import org.springframework.core.convert.converter.Converter; -import org.springframework.stereotype.Component; - -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; - -@Component -public class StringToLocalDateTimeConverter implements Converter { - - @Override - public LocalDateTime convert(final String source) { - return LocalDateTime.parse(source, DateTimeFormatter.ISO_LOCAL_DATE_TIME); - } -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/domain/GenericEntity.java b/spring-custom-aop/src/main/java/org/baeldung/domain/GenericEntity.java deleted file mode 100644 index 7b1d27cb66..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/domain/GenericEntity.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.baeldung.domain; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class GenericEntity { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - private String value; - - public GenericEntity() { - } - - public GenericEntity(String value) { - this.value = value; - } - - public GenericEntity(Long id, String value) { - this.id = id; - this.value = value; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/domain/Modes.java b/spring-custom-aop/src/main/java/org/baeldung/domain/Modes.java deleted file mode 100644 index 473406ef26..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/domain/Modes.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.baeldung.domain; - -public enum Modes { - - ALPHA, BETA; -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/endpoints/CustomEndpoint.java b/spring-custom-aop/src/main/java/org/baeldung/endpoints/CustomEndpoint.java deleted file mode 100644 index 222a54c6ef..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/endpoints/CustomEndpoint.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.endpoints; - -import java.util.ArrayList; -import java.util.List; - -import org.springframework.boot.actuate.endpoint.Endpoint; -import org.springframework.stereotype.Component; - -@Component -public class CustomEndpoint implements Endpoint> { - - public CustomEndpoint() { - - } - - public String getId() { - return "customEndpoint"; - } - - public boolean isEnabled() { - return true; - } - - public boolean isSensitive() { - return true; - } - - public List invoke() { - // Your logic to display the output - List messages = new ArrayList(); - messages.add("This is message 1"); - messages.add("This is message 2"); - return messages; - } -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/endpoints/EndpointDTO.java b/spring-custom-aop/src/main/java/org/baeldung/endpoints/EndpointDTO.java deleted file mode 100644 index d12d6419e1..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/endpoints/EndpointDTO.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.baeldung.endpoints; - -public class EndpointDTO { - private String id; - private boolean enabled; - private boolean sensitive; - - public EndpointDTO(String id, boolean enabled, boolean sensitive) { - super(); - this.id = id; - this.enabled = enabled; - this.sensitive = sensitive; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public boolean isSensitive() { - return sensitive; - } - - public void setSensitive(boolean sensitive) { - this.sensitive = sensitive; - } - -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/endpoints/ListEndpoints.java b/spring-custom-aop/src/main/java/org/baeldung/endpoints/ListEndpoints.java deleted file mode 100644 index f434351a51..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/endpoints/ListEndpoints.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.baeldung.endpoints; - -import java.util.List; -import java.util.stream.Collectors; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.endpoint.AbstractEndpoint; -import org.springframework.boot.actuate.endpoint.Endpoint; -import org.springframework.stereotype.Component; - -@Component -public class ListEndpoints extends AbstractEndpoint> { - private List endpointDTOs; - - @Autowired - public ListEndpoints(List endpoints) { - super("listEndpoints"); - this.endpointDTOs = endpoints.stream().map(endpoint -> new EndpointDTO(endpoint.getId(), endpoint.isEnabled(), endpoint.isSensitive())).collect(Collectors.toList()); - } - - public List invoke() { - return this.endpointDTOs; - } -} \ No newline at end of file diff --git a/spring-custom-aop/src/main/java/org/baeldung/endpoints/MyHealthCheck.java b/spring-custom-aop/src/main/java/org/baeldung/endpoints/MyHealthCheck.java deleted file mode 100644 index 4410a02d47..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/endpoints/MyHealthCheck.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.endpoints; - -import org.springframework.boot.actuate.health.Health; -import org.springframework.boot.actuate.health.HealthIndicator; -import org.springframework.stereotype.Component; - -@Component -public class MyHealthCheck implements HealthIndicator { - - public Health health() { - int errorCode = check(); // perform some specific health check - if (errorCode != 0) { - return Health.down().withDetail("Error Code", errorCode).withDetail("Description", "You custom MyHealthCheck endpoint is down").build(); - } - return Health.up().build(); - } - - public int check() { - // Your logic to check health - return 1; - } -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/main/SpringBootApplication.java b/spring-custom-aop/src/main/java/org/baeldung/main/SpringBootApplication.java deleted file mode 100644 index b828a5b841..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/main/SpringBootApplication.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.baeldung.main; - -import org.baeldung.common.error.SpringHelloServletRegistrationBean; -import org.baeldung.common.resources.ExecutorServiceExitCodeGenerator; -import org.baeldung.controller.servlet.HelloWorldServlet; -import org.baeldung.controller.servlet.SpringHelloWorldServlet; -import org.baeldung.service.LoginService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -@RestController -@EnableAutoConfiguration -@ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.service" }) -public class SpringBootApplication { - - private static ApplicationContext applicationContext; - - @Autowired - private LoginService service; - - @RequestMapping("/") - String home() { - service.login("admin", "admin".toCharArray()); - return "TADA!!! You are in Spring Boot Actuator test application."; - } - - public static void main(String[] args) { - applicationContext = SpringApplication.run(SpringBootApplication.class, args); - } - - @Bean - public ExecutorService executorService() { - return Executors.newFixedThreadPool(10); - } - - @Bean - public HelloWorldServlet helloWorldServlet() { - return new HelloWorldServlet(); - } - - @Bean - public SpringHelloServletRegistrationBean servletRegistrationBean() { - SpringHelloServletRegistrationBean bean = new SpringHelloServletRegistrationBean(new SpringHelloWorldServlet(), "/springHelloWorld/*"); - bean.setLoadOnStartup(1); - bean.addInitParameter("message", "SpringHelloWorldServlet special message"); - return bean; - } - - @Bean - @Autowired - public ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator(ExecutorService executorService) { - return new ExecutorServiceExitCodeGenerator(executorService); - } - - public void shutDown(ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator) { - SpringApplication.exit(applicationContext, executorServiceExitCodeGenerator); - } - -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java b/spring-custom-aop/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java deleted file mode 100644 index febe3336eb..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.monitor.jmx; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.codahale.metrics.JmxReporter; -import com.codahale.metrics.MetricRegistry; - -@Configuration -public class MonitoringConfig { - @Autowired - private MetricRegistry registry; - - @Bean - public JmxReporter jmxReporter() { - JmxReporter reporter = JmxReporter.forRegistry(registry).build(); - reporter.start(); - return reporter; - } -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/repository/GenericEntityRepository.java b/spring-custom-aop/src/main/java/org/baeldung/repository/GenericEntityRepository.java deleted file mode 100644 index 7bb1e6dcdc..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/repository/GenericEntityRepository.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.baeldung.repository; - -import org.baeldung.domain.GenericEntity; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface GenericEntityRepository extends JpaRepository { -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/service/LoginService.java b/spring-custom-aop/src/main/java/org/baeldung/service/LoginService.java deleted file mode 100644 index 34840fad67..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/service/LoginService.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.service; - -public interface LoginService { - public boolean login(String userName, char[] password); -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/service/LoginServiceImpl.java b/spring-custom-aop/src/main/java/org/baeldung/service/LoginServiceImpl.java deleted file mode 100644 index 2e5ef89c48..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/service/LoginServiceImpl.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.service; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.metrics.CounterService; -import org.springframework.stereotype.Service; - -@Service -public class LoginServiceImpl implements LoginService { - - private CounterService counterService; - - @Autowired - public LoginServiceImpl(CounterService counterService) { - this.counterService = counterService; - } - - public boolean login(String userName, char[] password) { - boolean success; - if (userName.equals("admin") && "secret".toCharArray().equals(password)) { - counterService.increment("counter.login.success"); - success = true; - } else { - counterService.increment("counter.login.failure"); - success = false; - } - return success; - } - -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/session/exception/Application.java b/spring-custom-aop/src/main/java/org/baeldung/session/exception/Application.java deleted file mode 100644 index 23d741b98c..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/session/exception/Application.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.baeldung.session.exception; - -import org.baeldung.boot.model.Foo; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.context.annotation.Bean; -import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean; - -@EntityScan(basePackageClasses = Foo.class) -@SpringBootApplication -public class Application { - public static void main(String[] args) { - System.setProperty("spring.config.name", "exception"); - System.setProperty("spring.profiles.active", "exception"); - SpringApplication.run(Application.class, args); - } - - @Bean - public HibernateJpaSessionFactoryBean sessionFactory() { - return new HibernateJpaSessionFactoryBean(); - } -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/session/exception/repository/FooRepository.java b/spring-custom-aop/src/main/java/org/baeldung/session/exception/repository/FooRepository.java deleted file mode 100644 index 679d691b26..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/session/exception/repository/FooRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung.session.exception.repository; - -import org.baeldung.boot.model.Foo; - -public interface FooRepository { - - void save(Foo foo); - - Foo get(Integer id); -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java b/spring-custom-aop/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java deleted file mode 100644 index 83de888e5e..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.baeldung.session.exception.repository; - -import org.baeldung.boot.model.Foo; -import org.hibernate.SessionFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Profile; -import org.springframework.stereotype.Repository; - -@Profile("exception") -@Repository -public class FooRepositoryImpl implements FooRepository { - @Autowired - private SessionFactory sessionFactory; - - @Override - public void save(Foo foo) { - sessionFactory.getCurrentSession().saveOrUpdate(foo); - } - - @Override - public Foo get(Integer id) { - return sessionFactory.getCurrentSession().get(Foo.class, id); - } - -} \ No newline at end of file diff --git a/spring-custom-aop/src/main/java/org/baeldung/web/resolver/HeaderVersionArgumentResolver.java b/spring-custom-aop/src/main/java/org/baeldung/web/resolver/HeaderVersionArgumentResolver.java deleted file mode 100644 index 89a77f38d1..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/web/resolver/HeaderVersionArgumentResolver.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.baeldung.web.resolver; - -import org.springframework.core.MethodParameter; -import org.springframework.stereotype.Component; -import org.springframework.web.bind.support.WebDataBinderFactory; -import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.method.support.HandlerMethodArgumentResolver; -import org.springframework.web.method.support.ModelAndViewContainer; - -import javax.servlet.http.HttpServletRequest; - -@Component -public class HeaderVersionArgumentResolver implements HandlerMethodArgumentResolver { - - @Override - public boolean supportsParameter(final MethodParameter methodParameter) { - return methodParameter.getParameterAnnotation(Version.class) != null; - } - - @Override - public Object resolveArgument(final MethodParameter methodParameter, final ModelAndViewContainer modelAndViewContainer, final NativeWebRequest nativeWebRequest, final WebDataBinderFactory webDataBinderFactory) throws Exception { - HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest(); - - return request.getHeader("Version"); - } -} diff --git a/spring-custom-aop/src/main/java/org/baeldung/web/resolver/Version.java b/spring-custom-aop/src/main/java/org/baeldung/web/resolver/Version.java deleted file mode 100644 index 2a9e6e60b3..0000000000 --- a/spring-custom-aop/src/main/java/org/baeldung/web/resolver/Version.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.baeldung.web.resolver; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.PARAMETER) -public @interface Version { -} diff --git a/spring-custom-aop/src/main/resources/application.properties b/spring-custom-aop/src/main/resources/application.properties deleted file mode 100644 index 72ed8795c9..0000000000 --- a/spring-custom-aop/src/main/resources/application.properties +++ /dev/null @@ -1,43 +0,0 @@ -server.port=8080 -server.contextPath=/springbootapp -management.port=8081 -management.address=127.0.0.1 - -endpoints.shutdown.enabled=true - -endpoints.jmx.domain=Spring Sample Application -endpoints.jmx.uniqueNames=true - -##jolokia.config.debug=true -##endpoints.jolokia.enabled=true -##endpoints.jolokia.path=jolokia - -spring.jmx.enabled=true -endpoints.jmx.enabled=true - -## for pretty printing of json when endpoints accessed over HTTP -http.mappers.jsonPrettyPrint=true - -## Configuring info endpoint -info.app.name=Spring Sample Application -info.app.description=This is my first spring boot application G1 -info.app.version=1.0.0 - -## Spring Security Configurations -security.user.name=admin1 -security.user.password=secret1 -management.security.role=SUPERUSER - -logging.level.org.springframework=INFO - -#Servlet Configuration -servlet.name=dispatcherExample -servlet.mapping=/dispatcherExampleURL - -#banner.charset=UTF-8 -#banner.location=classpath:banner.txt -#banner.image.location=classpath:banner.gif -#banner.image.width= //TODO -#banner.image.height= //TODO -#banner.image.margin= //TODO -#banner.image.invert= //TODO \ No newline at end of file diff --git a/spring-custom-aop/src/main/resources/banner.txt b/spring-custom-aop/src/main/resources/banner.txt deleted file mode 100644 index abfa666eb6..0000000000 --- a/spring-custom-aop/src/main/resources/banner.txt +++ /dev/null @@ -1,14 +0,0 @@ -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@@@@@@@@@@@@@@@@@@@@@@@@@#@@@@@########@@@@@@@@@@@@@@@@@@@@@@@@...@@@@@@@@@:..@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@@@@@@@@@@@@@@@@@@@@@@#. @@@@@* *@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@@@@@@@@@@@@@@@@@#o @@@@@* @@@@@* @@@:*.*@@@@@@@: *8@@@ @@@@&:.#@. @o**@@@@**:@o*o@@:.:@@@@@:.o#@&*:@@@@ -@@@@@@@@@@@@* @@@@@* 8888 8@ @@@8 #@o 8@# .@ @@* :. @* @@@@ @. : &@ ** .@@@@ -@@@@@@@@@@. @ o@@@@@* *@@@o::& .* 8@@@@. @@ 8@@@@. @* @@@@ @. @@@& * @@@@# .@@@@ -@@@@@@@@@& @ @@@@@@* @@@@@@ 8 @@@@ .. o&&&&&&& @@ #@@@@. @* @@@@ @. @@@# * @@@@@ .@@@@ -@@@@@@@@@ @@o @@@@@@@* oooo* 8 @@@& @* @@@ # 88. 88. *& o#: @. @@@# *@ &#& .@@@@ -@@@@@@@@# @@@8 @@@@@@@* .*@@@#. *@@ @@@& :#@@@o .@@: *&@8 @o o@@: @. @@@# *@@#. :8# .@@@@ -@@@@@@@@@ @@@@ &@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@# o@@@@ @@@@@ -@@@@@& &@@@@ 8@@@@@@@@@8&8@@@@@#8#@@@o8@#&@@o&@@@&@@8@@&@@@@88@@8#@8&@@##@@@@@@#8@@#8@@88@@@@@ *@@@@@@@ -@@@# #@@@@#. @@@@@@@@@@@@@8@@8#o@&#@@@@o.@o*@@*.@@@.@&:8o8*@@@8&@@#@@@8@@@@8@#@@@8&@@@@@@#@@@@@@@@@@@@@@@@@@@ -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \ No newline at end of file diff --git a/spring-custom-aop/src/main/resources/custom.properties b/spring-custom-aop/src/main/resources/custom.properties deleted file mode 100644 index 34f31bcd50..0000000000 --- a/spring-custom-aop/src/main/resources/custom.properties +++ /dev/null @@ -1,4 +0,0 @@ -dispatcher.servlet.name=dispatcherExample -dispatcher.servlet.mapping=/dispatcherExampleURL -example.servlet.name=dispatcherExample -example.servlet.mapping=/dispatcherExampleURL \ No newline at end of file diff --git a/spring-custom-aop/src/main/resources/demo.properties b/spring-custom-aop/src/main/resources/demo.properties deleted file mode 100644 index 649b64f59b..0000000000 --- a/spring-custom-aop/src/main/resources/demo.properties +++ /dev/null @@ -1,6 +0,0 @@ -spring.output.ansi.enabled=never -server.port=7070 - -# Security -security.user.name=admin -security.user.password=password \ No newline at end of file diff --git a/spring-custom-aop/src/main/resources/messages.properties b/spring-custom-aop/src/main/resources/messages.properties deleted file mode 100644 index e4dbc44c3f..0000000000 --- a/spring-custom-aop/src/main/resources/messages.properties +++ /dev/null @@ -1,4 +0,0 @@ -greeting=Hello! Welcome to our website! -lang.change=Change the language -lang.eng=English -lang.fr=French \ No newline at end of file diff --git a/spring-custom-aop/src/main/resources/messages_fr.properties b/spring-custom-aop/src/main/resources/messages_fr.properties deleted file mode 100644 index ac5853717d..0000000000 --- a/spring-custom-aop/src/main/resources/messages_fr.properties +++ /dev/null @@ -1,4 +0,0 @@ -greeting=Bonjour! Bienvenue sur notre site! -lang.change=Changez la langue -lang.eng=Anglais -lang.fr=Francais \ No newline at end of file diff --git a/spring-custom-aop/src/main/resources/public/error/404.html b/spring-custom-aop/src/main/resources/public/error/404.html deleted file mode 100644 index df83ce219b..0000000000 --- a/spring-custom-aop/src/main/resources/public/error/404.html +++ /dev/null @@ -1,8 +0,0 @@ - - - RESOURCE NOT FOUND - - -

404 RESOURCE NOT FOUND

- - \ No newline at end of file diff --git a/spring-custom-aop/src/main/resources/templates/index.html b/spring-custom-aop/src/main/resources/templates/index.html deleted file mode 100644 index 2c4387ed10..0000000000 --- a/spring-custom-aop/src/main/resources/templates/index.html +++ /dev/null @@ -1,19 +0,0 @@ - - - WebJars Demo - - - - -

-
- × - Success! It is working as we expected. -
-
- - - - - - diff --git a/spring-custom-aop/src/main/resources/templates/international.html b/spring-custom-aop/src/main/resources/templates/international.html deleted file mode 100644 index a2a5fbb591..0000000000 --- a/spring-custom-aop/src/main/resources/templates/international.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - -Home - - - - -

- -

-: - - - \ No newline at end of file diff --git a/spring-custom-aop/src/main/resources/templates/other.html b/spring-custom-aop/src/main/resources/templates/other.html deleted file mode 100644 index d13373f9fe..0000000000 --- a/spring-custom-aop/src/main/resources/templates/other.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - -Spring Utils Demo - - - - Parameter set by you:

- - \ No newline at end of file diff --git a/spring-custom-aop/src/main/resources/templates/utils.html b/spring-custom-aop/src/main/resources/templates/utils.html deleted file mode 100644 index 93030f424f..0000000000 --- a/spring-custom-aop/src/main/resources/templates/utils.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - -Spring Utils Demo - - - -

-

Set Parameter:

-

- - -

-
-Another Page - - \ No newline at end of file diff --git a/spring-custom-aop/src/main/webapp/WEB-INF/context.xml b/spring-custom-aop/src/main/webapp/WEB-INF/context.xml deleted file mode 100644 index 263bed4430..0000000000 --- a/spring-custom-aop/src/main/webapp/WEB-INF/context.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/spring-custom-aop/src/main/webapp/WEB-INF/dispatcher.xml b/spring-custom-aop/src/main/webapp/WEB-INF/dispatcher.xml deleted file mode 100644 index ade8e66777..0000000000 --- a/spring-custom-aop/src/main/webapp/WEB-INF/dispatcher.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/spring-custom-aop/src/main/webapp/WEB-INF/web.xml b/spring-custom-aop/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 60a4b079de..0000000000 --- a/spring-custom-aop/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - JSP - - index.html - index.htm - index.jsp - - - - - EEWebXmlServlet - com.baeldung.servlets.javaee.EEWebXmlServlet - - - - EEWebXmlServlet - /eewebxmlservlet - - - - - SpringBootWebXmlServlet - org.springframework.web.servlet.DispatcherServlet - - contextConfigLocation - /WEB-INF/dispatcher.xml - - 1 - - - - SpringBootWebXmlServlet - / - - - - diff --git a/spring-custom-aop/src/main/webapp/annotationservlet.jsp b/spring-custom-aop/src/main/webapp/annotationservlet.jsp deleted file mode 100644 index f21748df50..0000000000 --- a/spring-custom-aop/src/main/webapp/annotationservlet.jsp +++ /dev/null @@ -1 +0,0 @@ -

Annotation Servlet!

\ No newline at end of file diff --git a/spring-custom-aop/src/main/webapp/index.jsp b/spring-custom-aop/src/main/webapp/index.jsp deleted file mode 100644 index e534282777..0000000000 --- a/spring-custom-aop/src/main/webapp/index.jsp +++ /dev/null @@ -1 +0,0 @@ -

Hello!

\ No newline at end of file diff --git a/spring-custom-aop/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java b/spring-custom-aop/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java deleted file mode 100644 index f6d2a8c465..0000000000 --- a/spring-custom-aop/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.annotation.servletcomponentscan; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; - -import javax.servlet.FilterRegistration; -import javax.servlet.ServletContext; - -import static org.junit.Assert.*; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = SpringBootAnnotatedApp.class) -@AutoConfigureMockMvc -@TestPropertySource(properties = { "security.basic.enabled=false" }) -public class SpringBootWithServletComponentIntegrationTest { - - @Autowired - private ServletContext servletContext; - - @Test - public void givenServletContext_whenAccessAttrs_thenFoundAttrsPutInServletListner() { - assertNotNull(servletContext); - assertNotNull(servletContext.getAttribute("servlet-context-attr")); - assertEquals("test", servletContext.getAttribute("servlet-context-attr")); - } - - @Test - public void givenServletContext_whenCheckHelloFilterMappings_thenCorrect() { - assertNotNull(servletContext); - FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter"); - - assertNotNull(filterRegistration); - assertTrue(filterRegistration.getServletNameMappings().contains("echo servlet")); - } - - @Autowired - private TestRestTemplate restTemplate; - - @Test - public void givenServletFilter_whenGetHello_thenRequestFiltered() { - ResponseEntity responseEntity = this.restTemplate.getForEntity("/hello", String.class); - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - assertEquals("filtering hello", responseEntity.getBody()); - } - - @Test - public void givenFilterAndServlet_whenPostEcho_thenEchoFiltered() { - ResponseEntity responseEntity = this.restTemplate.postForEntity("/echo", "echo", String.class); - assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - assertEquals("filtering echo", responseEntity.getBody()); - } - -} diff --git a/spring-custom-aop/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java b/spring-custom-aop/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java deleted file mode 100644 index e7e1d5486c..0000000000 --- a/spring-custom-aop/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.baeldung.annotation.servletcomponentscan; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import javax.servlet.FilterRegistration; -import javax.servlet.ServletContext; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = SpringBootPlainApp.class) -@AutoConfigureMockMvc -@TestPropertySource(properties = { "security.basic.enabled=false" }) -public class SpringBootWithoutServletComponentIntegrationTest { - - @Autowired - private ServletContext servletContext; - - @Autowired - private TestRestTemplate restTemplate; - - @Test - public void givenServletContext_whenAccessAttrs_thenNotFound() { - assertNull(servletContext.getAttribute("servlet-context-attr")); - } - - @Test - public void givenServletFilter_whenGetHello_thenEndpointNotFound() { - ResponseEntity responseEntity = this.restTemplate.getForEntity("/hello", String.class); - assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); - } - - @Test - public void givenServletContext_whenCheckFilterMappings_thenEmpty() { - assertNotNull(servletContext); - FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter"); - - assertNull(filterRegistration); - } - -} diff --git a/spring-custom-aop/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java b/spring-custom-aop/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java deleted file mode 100644 index 348d594c05..0000000000 --- a/spring-custom-aop/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.git; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringRunner.class) -@ContextConfiguration(classes = CommitIdApplication.class) -public class CommitIdIntegrationTest { - - private static final Logger LOG = LoggerFactory.getLogger(CommitIdIntegrationTest.class); - - @Value("${git.commit.message.short:UNKNOWN}") - private String commitMessage; - - @Value("${git.branch:UNKNOWN}") - private String branch; - - @Value("${git.commit.id:UNKNOWN}") - private String commitId; - - @Test - public void whenInjecting_shouldDisplay() throws Exception { - - LOG.info(commitId); - LOG.info(commitMessage); - LOG.info(branch); - - assertThat(commitMessage).isNotEqualTo("UNKNOWN"); - - assertThat(branch).isNotEqualTo("UNKNOWN"); - - assertThat(commitId).isNotEqualTo("UNKNOWN"); - } -} \ No newline at end of file diff --git a/spring-custom-aop/src/test/java/com/baeldung/intro/AppLiveTest.java b/spring-custom-aop/src/test/java/com/baeldung/intro/AppLiveTest.java deleted file mode 100644 index 83b893ae5c..0000000000 --- a/spring-custom-aop/src/test/java/com/baeldung/intro/AppLiveTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.intro; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.MediaType; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; - -import static org.hamcrest.Matchers.equalTo; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) -@AutoConfigureMockMvc -@TestPropertySource(properties = { "security.basic.enabled=false" }) -public class AppLiveTest { - - @Autowired - private MockMvc mvc; - - @Test - public void getIndex() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("Index Page"))); - } - - @Test - public void getLocal() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("/local"))); - } - -} \ No newline at end of file diff --git a/spring-custom-aop/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java b/spring-custom-aop/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java deleted file mode 100644 index 99e719d7e9..0000000000 --- a/spring-custom-aop/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.utils; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.MockitoAnnotations; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import com.baeldung.utils.controller.UtilsController; - -public class UtilsControllerIntegrationTest { - - @InjectMocks - private UtilsController utilsController; - - private MockMvc mockMvc; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController).build(); - - } - - @Test - public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception { - String param = "testparam"; - this.mockMvc.perform(post("/setParam").param("param", param).sessionAttr("parameter", param)).andExpect(status().isOk()); - } - -} diff --git a/spring-custom-aop/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java b/spring-custom-aop/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java deleted file mode 100644 index d6e71dcf6b..0000000000 --- a/spring-custom-aop/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.webjar; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = WebjarsdemoApplication.class) -@WebAppConfiguration -public class WebjarsdemoApplicationIntegrationTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-custom-aop/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java deleted file mode 100644 index 87c59a4662..0000000000 --- a/spring-custom-aop/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.baeldung; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; - -import org.baeldung.domain.Modes; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import java.nio.charset.Charset; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = Application.class) -@WebAppConfiguration -public class SpringBootApplicationIntegrationTest { - @Autowired - private WebApplicationContext webApplicationContext; - private MockMvc mockMvc; - - @Before - public void setupMockMvc() { - mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); - } - - @Test - public void givenRequestHasBeenMade_whenMeetsAllOfGivenConditions_thenCorrect() throws Exception { - MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - - mockMvc.perform(MockMvcRequestBuilders.get("/entity/all")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$", hasSize(4))); - } - - @Test - public void givenRequestHasBeenMade_whenMeetsFindByDateOfGivenConditions_thenCorrect() throws Exception { - MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - - mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbydate/{date}", "2011-12-03T10:15:30")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)) - .andExpect(jsonPath("$.id", equalTo(1))); - } - - @Test - public void givenRequestHasBeenMade_whenMeetsFindByModeOfGivenConditions_thenCorrect() throws Exception { - MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - - mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbymode/{mode}", Modes.ALPHA.name())).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)).andExpect(jsonPath("$.id", equalTo(1))); - } - - @Test - public void givenRequestHasBeenMade_whenMeetsFindByVersionOfGivenConditions_thenCorrect() throws Exception { - MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); - - mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion").header("Version", "1.0.0")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType)) - .andExpect(jsonPath("$.id", equalTo(1))); - } -} diff --git a/spring-custom-aop/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java deleted file mode 100644 index d4b19e6a1d..0000000000 --- a/spring-custom-aop/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.baeldung; - -import org.baeldung.domain.GenericEntity; -import org.baeldung.repository.GenericEntityRepository; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = Application.class) -public class SpringBootJPAIntegrationTest { - @Autowired - private GenericEntityRepository genericEntityRepository; - - @Test - public void givenGenericEntityRepository_whenSaveAndRetreiveEntity_thenOK() { - GenericEntity genericEntity = genericEntityRepository.save(new GenericEntity("test")); - GenericEntity foundedEntity = genericEntityRepository.findOne(genericEntity.getId()); - assertNotNull(foundedEntity); - assertEquals(genericEntity.getValue(), foundedEntity.getValue()); - } -} diff --git a/spring-custom-aop/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java deleted file mode 100644 index 14386d73c1..0000000000 --- a/spring-custom-aop/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.baeldung; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.mail.SimpleMailMessage; -import org.springframework.mail.javamail.JavaMailSender; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.subethamail.wiser.Wiser; -import org.subethamail.wiser.WiserMessage; - -import javax.mail.MessagingException; -import java.io.IOException; -import java.util.List; - -import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = Application.class) -public class SpringBootMailIntegrationTest { - @Autowired - private JavaMailSender javaMailSender; - - private Wiser wiser; - - private String userTo = "user2@localhost"; - private String userFrom = "user1@localhost"; - private String subject = "Test subject"; - private String textMail = "Text subject mail"; - - @Before - public void setUp() throws Exception { - final int TEST_PORT = 8025; - wiser = new Wiser(TEST_PORT); - wiser.start(); - } - - @After - public void tearDown() throws Exception { - wiser.stop(); - } - - @Test - public void givenMail_whenSendAndReceived_thenCorrect() throws Exception { - SimpleMailMessage message = composeEmailMessage(); - javaMailSender.send(message); - List messages = wiser.getMessages(); - - assertThat(messages, hasSize(1)); - WiserMessage wiserMessage = messages.get(0); - assertEquals(userFrom, wiserMessage.getEnvelopeSender()); - assertEquals(userTo, wiserMessage.getEnvelopeReceiver()); - assertEquals(subject, getSubject(wiserMessage)); - assertEquals(textMail, getMessage(wiserMessage)); - } - - private String getMessage(WiserMessage wiserMessage) throws MessagingException, IOException { - return wiserMessage.getMimeMessage().getContent().toString().trim(); - } - - private String getSubject(WiserMessage wiserMessage) throws MessagingException { - return wiserMessage.getMimeMessage().getSubject(); - } - - private SimpleMailMessage composeEmailMessage() { - SimpleMailMessage mailMessage = new SimpleMailMessage(); - mailMessage.setTo(userTo); - mailMessage.setReplyTo(userFrom); - mailMessage.setFrom(userFrom); - mailMessage.setSubject(subject); - mailMessage.setText(textMail); - return mailMessage; - } -} diff --git a/spring-custom-aop/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/SpringContextIntegrationTest.java deleted file mode 100644 index 0384c67e26..0000000000 --- a/spring-custom-aop/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.annotation.servletcomponentscan.SpringBootAnnotatedApp; -import com.baeldung.annotation.servletcomponentscan.SpringBootPlainApp; -import com.baeldung.git.CommitIdApplication; -import com.baeldung.internationalization.InternationalizationApp; -import com.baeldung.intro.App; -import com.baeldung.servlets.ApplicationMain; -import com.baeldung.webjar.WebjarsdemoApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = { SpringBootAnnotatedApp.class, SpringBootPlainApp.class, CommitIdApplication.class, - InternationalizationApp.class, App.class, ApplicationMain.class, Application.class, - WebjarsdemoApplication.class }) -public class SpringContextIntegrationTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-custom-aop/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java deleted file mode 100644 index 57a8abc1ee..0000000000 --- a/spring-custom-aop/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.boot; - -import org.baeldung.session.exception.Application; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = Application.class) -@TestPropertySource("classpath:exception.properties") -public class ApplicationIntegrationTest { - @Test - public void contextLoads() { - } -} diff --git a/spring-custom-aop/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java deleted file mode 100644 index 4fcea35b4a..0000000000 --- a/spring-custom-aop/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.boot; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = DemoApplication.class) -@WebAppConfiguration -public class DemoApplicationIntegrationTest { - - @Test - public void contextLoads() { - } -} diff --git a/spring-custom-aop/src/test/java/org/baeldung/boot/FooComponentIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/boot/FooComponentIntegrationTest.java deleted file mode 100644 index 07a5495e8a..0000000000 --- a/spring-custom-aop/src/test/java/org/baeldung/boot/FooComponentIntegrationTest.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.baeldung.boot; - -import org.baeldung.boot.components.FooService; -import org.baeldung.boot.model.Foo; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.mock.mockito.SpyBean; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Mockito.doReturn; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = DemoApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class FooComponentIntegrationTest { - - @Autowired - private TestRestTemplate testRestTemplate; - - @SpyBean - private FooService fooService; - - @Before - public void init() throws Exception { - Foo foo = new Foo(); - foo.setId(5); - foo.setName("MOCKED_FOO"); - - doReturn(foo).when(fooService).getFooWithId(anyInt()); - - // doCallRealMethod().when(fooComponent).getFooWithName(anyString()); - } - - @Test - public void givenInquiryingFooWithId_whenFooComponentIsMocked_thenAssertMockedResult() { - Map pathVariables = new HashMap<>(); - pathVariables.put("id", "1"); - ResponseEntity fooResponse = testRestTemplate.getForEntity("/{id}", Foo.class, pathVariables); - - assertNotNull(fooResponse); - assertEquals(HttpStatus.OK, fooResponse.getStatusCode()); - assertEquals(5, fooResponse.getBody().getId().longValue()); - assertEquals("MOCKED_FOO", fooResponse.getBody().getName()); - } - - @Test - public void givenInquiryingFooWithName_whenFooComponentIsMocked_thenAssertMockedResult() { - Map pathVariables = new HashMap<>(); - pathVariables.put("name", "Foo_Name"); - ResponseEntity fooResponse = testRestTemplate.getForEntity("/?name={name}", Foo.class, pathVariables); - - assertNotNull(fooResponse); - assertEquals(HttpStatus.OK, fooResponse.getStatusCode()); - assertEquals(1, fooResponse.getBody().getId().longValue()); - } -} \ No newline at end of file diff --git a/spring-custom-aop/src/test/java/org/baeldung/boot/FooIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/boot/FooIntegrationTest.java deleted file mode 100644 index 52728fbb5b..0000000000 --- a/spring-custom-aop/src/test/java/org/baeldung/boot/FooIntegrationTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.baeldung.boot; - -import java.util.HashMap; -import java.util.Map; - -import org.baeldung.boot.DemoApplication; -import org.baeldung.boot.model.Foo; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = DemoApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class FooIntegrationTest { - - @Autowired - private TestRestTemplate testRestTemplate; - - @Test - public void givenInquiryingFooWithId_whenIdIsValid_thenHttpStatusOK() { - Map pathVariables = new HashMap(); - pathVariables.put("id", "1"); - ResponseEntity fooResponse = testRestTemplate.getForEntity("/{id}", Foo.class, pathVariables); - Assert.assertNotNull(fooResponse); - Assert.assertEquals(HttpStatus.OK, fooResponse.getStatusCode()); - } - - @Test - public void givenInquiryingFooWithName_whenNameIsValid_thenHttpStatusOK() { - Map pathVariables = new HashMap(); - pathVariables.put("name", "Foo_Name"); - ResponseEntity fooResponse = testRestTemplate.getForEntity("/?name={name}", Foo.class, pathVariables); - Assert.assertNotNull(fooResponse); - Assert.assertEquals(HttpStatus.OK, fooResponse.getStatusCode()); - } -} \ No newline at end of file diff --git a/spring-custom-aop/src/test/java/org/baeldung/boot/FooJPAIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/boot/FooJPAIntegrationTest.java deleted file mode 100644 index 40f1892be8..0000000000 --- a/spring-custom-aop/src/test/java/org/baeldung/boot/FooJPAIntegrationTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.baeldung.boot; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.baeldung.boot.model.Foo; -import org.baeldung.boot.repository.FooRepository; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@DataJpaTest -public class FooJPAIntegrationTest { - - @Autowired - private TestEntityManager entityManager; - - @Autowired - private FooRepository repository; - - @Test - public void findFooByName() { - this.entityManager.persist(new Foo("Foo_Name_2")); - Foo foo = this.repository.findByName("Foo_Name_2"); - assertNotNull(foo); - assertEquals("Foo_Name_2", foo.getName()); - // Due to having Insert query for Foo with Id 1, so TestEntityManager generates new Id of 2 - assertEquals(2l, foo.getId().longValue()); - } -} \ No newline at end of file diff --git a/spring-custom-aop/src/test/java/org/baeldung/boot/FooJsonIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/boot/FooJsonIntegrationTest.java deleted file mode 100644 index 939e66f356..0000000000 --- a/spring-custom-aop/src/test/java/org/baeldung/boot/FooJsonIntegrationTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.baeldung.boot; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.baeldung.boot.model.Foo; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.json.JsonTest; -import org.springframework.boot.test.json.JacksonTester; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@JsonTest -public class FooJsonIntegrationTest { - - @Autowired - private JacksonTester json; - - @Test - public void testSerialize() throws Exception { - Foo foo = new Foo(3, "Foo_Name_3"); - assertThat(this.json.write(foo)).isEqualToJson("expected.json"); - assertThat(this.json.write(foo)).hasJsonPathStringValue("@.name"); - assertThat(this.json.write(foo)).extractingJsonPathStringValue("@.name").isEqualTo("Foo_Name_3"); - } - - @Test - public void testDeserialize() throws Exception { - String content = "{\"id\":4,\"name\":\"Foo_Name_4\"}"; - assertThat(this.json.parseObject(content).getName()).isEqualTo("Foo_Name_4"); - assertThat(this.json.parseObject(content).getId() == 4); - } -} \ No newline at end of file diff --git a/spring-custom-aop/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java deleted file mode 100644 index a844b26b2d..0000000000 --- a/spring-custom-aop/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.baeldung.boot.repository; - -import static org.junit.Assert.assertThat; - -import org.baeldung.boot.DemoApplicationIntegrationTest; -import org.baeldung.boot.model.Foo; - -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.is; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class FooRepositoryIntegrationTest extends DemoApplicationIntegrationTest { - @Autowired - private FooRepository fooRepository; - - @Before - public void setUp() { - fooRepository.save(new Foo("Foo")); - fooRepository.save(new Foo("Bar")); - } - - @Test - public void testFindByName() { - Foo foo = fooRepository.findByName("Bar"); - assertThat(foo, notNullValue()); - assertThat(foo.getId(), is(2)); - } - -} diff --git a/spring-custom-aop/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java deleted file mode 100644 index be992bcc36..0000000000 --- a/spring-custom-aop/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.baeldung.boot.repository; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.junit.Assert.assertThat; - -import org.baeldung.boot.ApplicationIntegrationTest; -import org.baeldung.boot.model.Foo; -import org.baeldung.session.exception.repository.FooRepository; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.TestPropertySource; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -@TestPropertySource("classpath:exception-hibernate.properties") -public class HibernateSessionIntegrationTest extends ApplicationIntegrationTest { - @Autowired - private FooRepository fooRepository; - - @Test - public void whenSavingWithCurrentSession_thenThrowNoException() { - Foo foo = new Foo("Exception Solved"); - fooRepository.save(foo); - foo = null; - foo = fooRepository.get(1); - - assertThat(foo, notNullValue()); - assertThat(foo.getId(), is(1)); - assertThat(foo.getName(), is("Exception Solved")); - } -} diff --git a/spring-custom-aop/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java deleted file mode 100644 index 55b7fa7216..0000000000 --- a/spring-custom-aop/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.boot.repository; - -import org.baeldung.boot.ApplicationIntegrationTest; -import org.baeldung.boot.model.Foo; -import org.baeldung.session.exception.repository.FooRepository; -import org.hibernate.HibernateException; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class NoHibernateSessionIntegrationTest extends ApplicationIntegrationTest { - @Autowired - private FooRepository fooRepository; - - @Test(expected = HibernateException.class) - public void whenSavingWithoutCurrentSession_thenThrowException() { - Foo foo = new Foo("Exception Thrown"); - fooRepository.save(foo); - } -} diff --git a/spring-custom-aop/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java deleted file mode 100644 index 5627855aa3..0000000000 --- a/spring-custom-aop/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.baeldung.client; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.client.MockRestServiceServer; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; -import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; - -@RunWith(SpringRunner.class) -@RestClientTest(DetailsServiceClient.class) -public class DetailsServiceClientIntegrationTest { - - @Autowired - private DetailsServiceClient client; - - @Autowired - private MockRestServiceServer server; - - @Autowired - private ObjectMapper objectMapper; - - @Before - public void setUp() throws Exception { - String detailsString = objectMapper.writeValueAsString(new Details("John Smith", "john")); - this.server.expect(requestTo("/john/details")).andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON)); - } - - @Test - public void whenCallingGetUserDetails_thenClientExecutesCorrectCall() throws Exception { - - Details details = this.client.getUserDetails("john"); - - assertThat(details.getLogin()).isEqualTo("john"); - assertThat(details.getName()).isEqualTo("John Smith"); - - } - -} diff --git a/spring-custom-aop/src/test/resources/application.properties b/spring-custom-aop/src/test/resources/application.properties deleted file mode 100644 index 0e6cb86bc5..0000000000 --- a/spring-custom-aop/src/test/resources/application.properties +++ /dev/null @@ -1,5 +0,0 @@ -spring.mail.host=localhost -spring.mail.port=8025 -spring.mail.properties.mail.smtp.auth=false - -security.basic.enabled=false \ No newline at end of file diff --git a/spring-custom-aop/src/test/resources/exception-hibernate.properties b/spring-custom-aop/src/test/resources/exception-hibernate.properties deleted file mode 100644 index cde746acb9..0000000000 --- a/spring-custom-aop/src/test/resources/exception-hibernate.properties +++ /dev/null @@ -1,2 +0,0 @@ -spring.profiles.active=exception -spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext diff --git a/spring-custom-aop/src/test/resources/exception.properties b/spring-custom-aop/src/test/resources/exception.properties deleted file mode 100644 index c55e415a3a..0000000000 --- a/spring-custom-aop/src/test/resources/exception.properties +++ /dev/null @@ -1,6 +0,0 @@ -# Security -security.user.name=admin -security.user.password=password - -spring.dao.exceptiontranslation.enabled=false -spring.profiles.active=exception \ No newline at end of file diff --git a/spring-custom-aop/src/test/resources/import.sql b/spring-custom-aop/src/test/resources/import.sql deleted file mode 100644 index a382410271..0000000000 --- a/spring-custom-aop/src/test/resources/import.sql +++ /dev/null @@ -1 +0,0 @@ -Insert into Foo values(1,'Foo_Name'); \ No newline at end of file diff --git a/spring-custom-aop/src/test/resources/org/baeldung/boot/expected.json b/spring-custom-aop/src/test/resources/org/baeldung/boot/expected.json deleted file mode 100644 index f5409421a6..0000000000 --- a/spring-custom-aop/src/test/resources/org/baeldung/boot/expected.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "id":3, - "name":"Foo_Name_3" -} \ No newline at end of file diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 3a580202cf..c7fcbd400b 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -32,3 +32,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Using Spring @ResponseStatus to Set HTTP Status Code](http://www.baeldung.com/spring-response-status) - [Bootstrap a Web Application with Spring 5](https://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration) - [Spring MVC Tutorial](https://www.baeldung.com/spring-mvc-tutorial) +- [Working with Date Parameters in Spring](https://www.baeldung.com/spring-date-parameters) diff --git a/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java index c7b9f8358e..7be37c7155 100644 --- a/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java +++ b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/MyUserPredicatesBuilder.java @@ -1,10 +1,14 @@ package org.baeldung.persistence.dao; -import com.querydsl.core.types.dsl.BooleanExpression; -import org.baeldung.web.util.SearchCriteria; - import java.util.ArrayList; import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import org.baeldung.web.util.SearchCriteria; + +import com.querydsl.core.types.dsl.BooleanExpression; +import com.querydsl.core.types.dsl.Expressions; public final class MyUserPredicatesBuilder { private final List params; @@ -22,21 +26,34 @@ public final class MyUserPredicatesBuilder { if (params.size() == 0) { return null; } - - final List predicates = new ArrayList<>(); - MyUserPredicate predicate; - for (final SearchCriteria param : params) { - predicate = new MyUserPredicate(param); - final BooleanExpression exp = predicate.getPredicate(); - if (exp != null) { - predicates.add(exp); - } - } - - BooleanExpression result = predicates.get(0); - for (int i = 1; i < predicates.size(); i++) { - result = result.and(predicates.get(i)); + + final List predicates = params.stream().map(param -> { + MyUserPredicate predicate = new MyUserPredicate(param); + return predicate.getPredicate(); + }).filter(Objects::nonNull).collect(Collectors.toList()); + + BooleanExpression result = Expressions.asBoolean(true).isTrue(); + for (BooleanExpression predicate : predicates) { + result = result.and(predicate); } + return result; } + + static class BooleanExpressionWrapper { + + private BooleanExpression result; + + public BooleanExpressionWrapper(final BooleanExpression result) { + super(); + this.result = result; + } + + public BooleanExpression getResult() { + return result; + } + public void setResult(BooleanExpression result) { + this.result = result; + } + } } diff --git a/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserDAO.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserDAO.java index 8a01f8c97c..4f2f6003e4 100644 --- a/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserDAO.java +++ b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserDAO.java @@ -1,8 +1,6 @@ package org.baeldung.persistence.dao; -import org.baeldung.persistence.model.User; -import org.baeldung.web.util.SearchCriteria; -import org.springframework.stereotype.Repository; +import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @@ -10,7 +8,10 @@ import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; -import java.util.List; + +import org.baeldung.persistence.model.User; +import org.baeldung.web.util.SearchCriteria; +import org.springframework.stereotype.Repository; @Repository public class UserDAO implements IUserDAO { @@ -25,20 +26,9 @@ public class UserDAO implements IUserDAO { final Root r = query.from(User.class); Predicate predicate = builder.conjunction(); - - for (final SearchCriteria param : params) { - if (param.getOperation().equalsIgnoreCase(">")) { - predicate = builder.and(predicate, builder.greaterThanOrEqualTo(r.get(param.getKey()), param.getValue().toString())); - } else if (param.getOperation().equalsIgnoreCase("<")) { - predicate = builder.and(predicate, builder.lessThanOrEqualTo(r.get(param.getKey()), param.getValue().toString())); - } else if (param.getOperation().equalsIgnoreCase(":")) { - if (r.get(param.getKey()).getJavaType() == String.class) { - predicate = builder.and(predicate, builder.like(r.get(param.getKey()), "%" + param.getValue() + "%")); - } else { - predicate = builder.and(predicate, builder.equal(r.get(param.getKey()), param.getValue())); - } - } - } + UserSearchQueryCriteriaConsumer searchConsumer = new UserSearchQueryCriteriaConsumer(predicate, builder, r); + params.stream().forEach(searchConsumer); + predicate = searchConsumer.getPredicate(); query.where(predicate); return entityManager.createQuery(query).getResultList(); diff --git a/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserSearchQueryCriteriaConsumer.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserSearchQueryCriteriaConsumer.java new file mode 100644 index 0000000000..8b15ef1605 --- /dev/null +++ b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserSearchQueryCriteriaConsumer.java @@ -0,0 +1,43 @@ +package org.baeldung.persistence.dao; + +import java.util.function.Consumer; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +import org.baeldung.web.util.SearchCriteria; + +public class UserSearchQueryCriteriaConsumer implements Consumer{ + + private Predicate predicate; + private CriteriaBuilder builder; + private Root r; + + public UserSearchQueryCriteriaConsumer(Predicate predicate, CriteriaBuilder builder, Root r) { + super(); + this.predicate = predicate; + this.builder = builder; + this.r= r; + } + + @Override + public void accept(SearchCriteria param) { + + if (param.getOperation().equalsIgnoreCase(">")) { + predicate = builder.and(predicate, builder.greaterThanOrEqualTo(r.get(param.getKey()), param.getValue().toString())); + } else if (param.getOperation().equalsIgnoreCase("<")) { + predicate = builder.and(predicate, builder.lessThanOrEqualTo(r.get(param.getKey()), param.getValue().toString())); + } else if (param.getOperation().equalsIgnoreCase(":")) { + if (r.get(param.getKey()).getJavaType() == String.class) { + predicate = builder.and(predicate, builder.like(r.get(param.getKey()), "%" + param.getValue() + "%")); + } else { + predicate = builder.and(predicate, builder.equal(r.get(param.getKey()), param.getValue())); + } + } + } + + public Predicate getPredicate() { + return predicate; + } +} \ No newline at end of file diff --git a/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserSpecificationsBuilder.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserSpecificationsBuilder.java index 918e77720f..28097d500a 100644 --- a/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserSpecificationsBuilder.java +++ b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/UserSpecificationsBuilder.java @@ -1,14 +1,15 @@ package org.baeldung.persistence.dao; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + import org.baeldung.persistence.model.User; import org.baeldung.web.util.SearchOperation; import org.baeldung.web.util.SpecSearchCriteria; import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specifications; -import java.util.ArrayList; -import java.util.List; - public final class UserSpecificationsBuilder { private final List params; @@ -44,22 +45,17 @@ public final class UserSpecificationsBuilder { } public Specification build() { - if (params.size() == 0) return null; Specification result = new UserSpecification(params.get(0)); - + for (int i = 1; i < params.size(); i++) { - result = params.get(i) - .isOrPredicate() - ? Specifications.where(result) - .or(new UserSpecification(params.get(i))) - : Specifications.where(result) - .and(new UserSpecification(params.get(i))); - + result = params.get(i).isOrPredicate() + ? Specifications.where(result).or(new UserSpecification(params.get(i))) + : Specifications.where(result).and(new UserSpecification(params.get(i))); } - + return result; } diff --git a/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecBuilder.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecBuilder.java index 4efec00ed6..ce5a4410b9 100644 --- a/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecBuilder.java +++ b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecBuilder.java @@ -1,13 +1,15 @@ package org.baeldung.persistence.dao.rsql; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import org.springframework.data.jpa.domain.Specifications; + import cz.jirutka.rsql.parser.ast.ComparisonNode; import cz.jirutka.rsql.parser.ast.LogicalNode; import cz.jirutka.rsql.parser.ast.LogicalOperator; import cz.jirutka.rsql.parser.ast.Node; -import org.springframework.data.jpa.domain.Specifications; - -import java.util.ArrayList; -import java.util.List; public class GenericRsqlSpecBuilder { @@ -22,29 +24,25 @@ public class GenericRsqlSpecBuilder { } public Specifications createSpecification(final LogicalNode logicalNode) { - final List> specs = new ArrayList>(); - Specifications temp; - for (final Node node : logicalNode.getChildren()) { - temp = createSpecification(node); - if (temp != null) { - specs.add(temp); - } - } - + + List> specs = logicalNode.getChildren() + .stream() + .map(node -> createSpecification(node)) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + Specifications result = specs.get(0); - if (logicalNode.getOperator() == LogicalOperator.AND) { - for (int i = 1; i < specs.size(); i++) { - result = Specifications.where(result).and(specs.get(i)); - } + for (int i = 1; i < specs.size(); i++) { + result = Specifications.where(result).and(specs.get(i)); + } } - else if (logicalNode.getOperator() == LogicalOperator.OR) { - for (int i = 1; i < specs.size(); i++) { - result = Specifications.where(result).or(specs.get(i)); - } + for (int i = 1; i < specs.size(); i++) { + result = Specifications.where(result).or(specs.get(i)); + } } - + return result; } diff --git a/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecification.java b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecification.java index 937c6d953c..8055e959a6 100644 --- a/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecification.java +++ b/spring-rest-query-language/src/main/java/org/baeldung/persistence/dao/rsql/GenericRsqlSpecification.java @@ -1,14 +1,16 @@ package org.baeldung.persistence.dao.rsql; -import cz.jirutka.rsql.parser.ast.ComparisonOperator; -import org.springframework.data.jpa.domain.Specification; +import java.util.List; +import java.util.stream.Collectors; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; -import java.util.ArrayList; -import java.util.List; + +import org.springframework.data.jpa.domain.Specification; + +import cz.jirutka.rsql.parser.ast.ComparisonOperator; public class GenericRsqlSpecification implements Specification { @@ -71,18 +73,18 @@ public class GenericRsqlSpecification implements Specification { // === private private List castArguments(final Root root) { - final List args = new ArrayList(); + final Class type = root.get(property).getJavaType(); - - for (final String argument : arguments) { + + final List args = arguments.stream().map(arg -> { if (type.equals(Integer.class)) { - args.add(Integer.parseInt(argument)); + return Integer.parseInt(arg); } else if (type.equals(Long.class)) { - args.add(Long.parseLong(argument)); + return Long.parseLong(arg); } else { - args.add(argument); - } - } + return arg; + } + }).collect(Collectors.toList()); return args; } diff --git a/spring-rest-query-language/src/main/java/org/baeldung/web/util/CriteriaParser.java b/spring-rest-query-language/src/main/java/org/baeldung/web/util/CriteriaParser.java index eabc938bce..a72d07f440 100644 --- a/spring-rest-query-language/src/main/java/org/baeldung/web/util/CriteriaParser.java +++ b/spring-rest-query-language/src/main/java/org/baeldung/web/util/CriteriaParser.java @@ -1,5 +1,6 @@ package org.baeldung.web.util; +import java.util.Arrays; import java.util.Collections; import java.util.Deque; import java.util.HashMap; @@ -45,7 +46,7 @@ public class CriteriaParser { Deque output = new LinkedList<>(); Deque stack = new LinkedList<>(); - for (String token : searchParam.split("\\s+")) { + Arrays.stream(searchParam.split("\\s+")).forEach(token -> { if (ops.containsKey(token)) { while (!stack.isEmpty() && isHigerPrecedenceOperator(token, stack.peek())) output.push(stack.pop() @@ -65,7 +66,7 @@ public class CriteriaParser { output.push(new SpecSearchCriteria(matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4), matcher.group(5))); } } - } + }); while (!stack.isEmpty()) output.push(stack.pop()); diff --git a/spring-security-mvc-boot/pom.xml b/spring-security-mvc-boot/pom.xml index d2316ddca5..2427d0de1a 100644 --- a/spring-security-mvc-boot/pom.xml +++ b/spring-security-mvc-boot/pom.xml @@ -220,7 +220,7 @@ - org.baeldung.Application + org.baeldung.custom.Application diff --git a/spring-zuul/pom.xml b/spring-zuul/pom.xml index 35e419cdc7..266c20adee 100644 --- a/spring-zuul/pom.xml +++ b/spring-zuul/pom.xml @@ -38,7 +38,7 @@ - 1.2.3.RELEASE + 1.2.7.RELEASE 3.5