diff --git a/README.md b/README.md index 6dff78aa7a..62d2d5b55e 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,3 @@ This tutorials project is being built **[>> HERE](https://rest-security.ci.cloud - [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure) - [Apache Maven Tutorial](http://www.baeldung.com/maven) -- [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library) -- [Java Service Provider Interface](http://www.baeldung.com/java-spi) -- [Java Streams vs Vavr Streams](http://www.baeldung.com/vavr-java-streams) diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java index 8b47fa0fdf..5ca2d626f1 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java @@ -148,7 +148,7 @@ public class Board { System.out.println("Game Draw"); break; case IN_PROGRESS: - System.out.println("Game In rogress"); + System.out.println("Game In Progress"); break; } } diff --git a/algorithms/src/test/java/algorithms/HillClimbingAlgorithmTest.java b/algorithms/src/test/java/algorithms/HillClimbingAlgorithmUnitTest.java similarity index 97% rename from algorithms/src/test/java/algorithms/HillClimbingAlgorithmTest.java rename to algorithms/src/test/java/algorithms/HillClimbingAlgorithmUnitTest.java index 666adbb180..e4746b521c 100644 --- a/algorithms/src/test/java/algorithms/HillClimbingAlgorithmTest.java +++ b/algorithms/src/test/java/algorithms/HillClimbingAlgorithmUnitTest.java @@ -13,7 +13,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -public class HillClimbingAlgorithmTest { +public class HillClimbingAlgorithmUnitTest { private Stack initStack; private Stack goalStack; diff --git a/algorithms/src/test/java/algorithms/StringSearchAlgorithmsTest.java b/algorithms/src/test/java/algorithms/StringSearchAlgorithmsUnitTest.java similarity index 93% rename from algorithms/src/test/java/algorithms/StringSearchAlgorithmsTest.java rename to algorithms/src/test/java/algorithms/StringSearchAlgorithmsUnitTest.java index e260cd7e5b..c98a8a53f3 100755 --- a/algorithms/src/test/java/algorithms/StringSearchAlgorithmsTest.java +++ b/algorithms/src/test/java/algorithms/StringSearchAlgorithmsUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import com.baeldung.algorithms.string.search.StringSearchAlgorithms; -public class StringSearchAlgorithmsTest { +public class StringSearchAlgorithmsUnitTest { @Test diff --git a/algorithms/src/test/java/algorithms/binarysearch/BinarySearchTest.java b/algorithms/src/test/java/algorithms/binarysearch/BinarySearchUnitTest.java similarity index 95% rename from algorithms/src/test/java/algorithms/binarysearch/BinarySearchTest.java rename to algorithms/src/test/java/algorithms/binarysearch/BinarySearchUnitTest.java index 959f47a275..74db4236b9 100644 --- a/algorithms/src/test/java/algorithms/binarysearch/BinarySearchTest.java +++ b/algorithms/src/test/java/algorithms/binarysearch/BinarySearchUnitTest.java @@ -7,7 +7,7 @@ import org.junit.Assert; import org.junit.Test; import com.baeldung.algorithms.binarysearch.BinarySearch; -public class BinarySearchTest { +public class BinarySearchUnitTest { int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; int key = 6; diff --git a/algorithms/src/test/java/algorithms/mcts/MCTSTest.java b/algorithms/src/test/java/algorithms/mcts/MCTSUnitTest.java similarity index 99% rename from algorithms/src/test/java/algorithms/mcts/MCTSTest.java rename to algorithms/src/test/java/algorithms/mcts/MCTSUnitTest.java index 375f66ab6f..edbf21390d 100644 --- a/algorithms/src/test/java/algorithms/mcts/MCTSTest.java +++ b/algorithms/src/test/java/algorithms/mcts/MCTSUnitTest.java @@ -15,7 +15,7 @@ import com.baeldung.algorithms.mcts.tictactoe.Board; import com.baeldung.algorithms.mcts.tictactoe.Position; import com.baeldung.algorithms.mcts.tree.Tree; -public class MCTSTest { +public class MCTSUnitTest { private Tree gameTree; private MonteCarloTreeSearch mcts; diff --git a/algorithms/src/test/java/algorithms/minimax/MinimaxTest.java b/algorithms/src/test/java/algorithms/minimax/MinimaxUnitTest.java similarity index 96% rename from algorithms/src/test/java/algorithms/minimax/MinimaxTest.java rename to algorithms/src/test/java/algorithms/minimax/MinimaxUnitTest.java index b29c16386c..c07975bca0 100644 --- a/algorithms/src/test/java/algorithms/minimax/MinimaxTest.java +++ b/algorithms/src/test/java/algorithms/minimax/MinimaxUnitTest.java @@ -7,7 +7,7 @@ import static org.junit.Assert.*; import com.baeldung.algorithms.minimax.MiniMax; import com.baeldung.algorithms.minimax.Tree; -public class MinimaxTest { +public class MinimaxUnitTest { private Tree gameTree; private MiniMax miniMax; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortTest.java b/algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java similarity index 92% rename from algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java index 7774eb3e67..c7f3f7dc38 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java @@ -4,7 +4,7 @@ import static org.junit.Assert.*; import org.junit.Test; -public class BubbleSortTest { +public class BubbleSortUnitTest { @Test public void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() { diff --git a/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceTest.java b/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java similarity index 80% rename from algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java index bab2f480a5..0df4715b80 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java @@ -7,13 +7,13 @@ import org.junit.runners.Parameterized; import static org.junit.Assert.assertEquals; @RunWith(Parameterized.class) -public class EditDistanceTest extends EditDistanceDataProvider { +public class EditDistanceUnitTest extends EditDistanceDataProvider { private String x; private String y; private int result; - public EditDistanceTest(String a, String b, int res) { + public EditDistanceUnitTest(String a, String b, int res) { super(); x = a; y = b; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java similarity index 72% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java index 7f9b8acdbd..af2430ec55 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java @@ -6,11 +6,11 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class CycleDetectionBruteForceTest extends CycleDetectionTestBase { +public class CycleDetectionBruteForceUnitTest extends CycleDetectionTestBase { boolean cycleExists; Node head; - public CycleDetectionBruteForceTest(Node head, boolean cycleExists) { + public CycleDetectionBruteForceUnitTest(Node head, boolean cycleExists) { super(); this.cycleExists = cycleExists; this.head = head; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java similarity index 70% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java index 17d339bc33..ce31c84067 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java @@ -6,11 +6,11 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class CycleDetectionByFastAndSlowIteratorsTest extends CycleDetectionTestBase { +public class CycleDetectionByFastAndSlowIteratorsUnitTest extends CycleDetectionTestBase { boolean cycleExists; Node head; - public CycleDetectionByFastAndSlowIteratorsTest(Node head, boolean cycleExists) { + public CycleDetectionByFastAndSlowIteratorsUnitTest(Node head, boolean cycleExists) { super(); this.cycleExists = cycleExists; this.head = head; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java similarity index 72% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java index 73a2cc7861..4451c3d3c9 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java @@ -6,11 +6,11 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class CycleDetectionByHashingTest extends CycleDetectionTestBase { +public class CycleDetectionByHashingUnitTest extends CycleDetectionTestBase { boolean cycleExists; Node head; - public CycleDetectionByHashingTest(Node head, boolean cycleExists) { + public CycleDetectionByHashingUnitTest(Node head, boolean cycleExists) { super(); this.cycleExists = cycleExists; this.head = head; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java similarity index 76% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java index 6484c9988e..f69e3c35ba 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java @@ -6,11 +6,11 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class CycleRemovalBruteForceTest extends CycleDetectionTestBase { +public class CycleRemovalBruteForceUnitTest extends CycleDetectionTestBase { boolean cycleExists; Node head; - public CycleRemovalBruteForceTest(Node head, boolean cycleExists) { + public CycleRemovalBruteForceUnitTest(Node head, boolean cycleExists) { super(); this.cycleExists = cycleExists; this.head = head; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java similarity index 75% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java index 7bfd89c502..c17aa6eeab 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java @@ -6,11 +6,11 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class CycleRemovalByCountingLoopNodesTest extends CycleDetectionTestBase { +public class CycleRemovalByCountingLoopNodesUnitTest extends CycleDetectionTestBase { boolean cycleExists; Node head; - public CycleRemovalByCountingLoopNodesTest(Node head, boolean cycleExists) { + public CycleRemovalByCountingLoopNodesUnitTest(Node head, boolean cycleExists) { super(); this.cycleExists = cycleExists; this.head = head; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java similarity index 74% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java index c77efb3e3e..06ff840a59 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java @@ -6,11 +6,11 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class CycleRemovalWithoutCountingLoopNodesTest extends CycleDetectionTestBase { +public class CycleRemovalWithoutCountingLoopNodesUnitTest extends CycleDetectionTestBase { boolean cycleExists; Node head; - public CycleRemovalWithoutCountingLoopNodesTest(Node head, boolean cycleExists) { + public CycleRemovalWithoutCountingLoopNodesUnitTest(Node head, boolean cycleExists) { super(); this.cycleExists = cycleExists; this.head = head; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterTest.java b/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java similarity index 98% rename from algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java index a4a169f158..26643e9c1e 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import com.baeldung.algorithms.numberwordconverter.NumberWordConverter; -public class NumberWordConverterTest { +public class NumberWordConverterUnitTest { @Test public void whenMoneyNegative_thenReturnInvalidInput() { diff --git a/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java b/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorUnitTest.java similarity index 93% rename from algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorUnitTest.java index 4995e938b7..ffa1404eac 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorUnitTest.java @@ -7,7 +7,7 @@ import java.util.List; import org.junit.Test; import static org.junit.Assert.*; -public class PrimeGeneratorTest { +public class PrimeGeneratorUnitTest { @Test public void whenBruteForced_returnsSuccessfully() { final List primeNumbers = primeNumbersBruteForce(20); diff --git a/algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java b/algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java similarity index 97% rename from algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java rename to algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java index c085d54689..0b0d6ae822 100644 --- a/algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java +++ b/algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java @@ -12,7 +12,7 @@ import org.jgrapht.graph.SimpleWeightedGraph; import org.junit.Before; import org.junit.Test; -public class CompleteGraphTest { +public class CompleteGraphUnitTest { static SimpleWeightedGraph completeGraph; static int size = 10; diff --git a/algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java b/algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java similarity index 99% rename from algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java rename to algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java index 7f4cc99715..3aebaf49a2 100644 --- a/algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java +++ b/algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java @@ -24,7 +24,7 @@ import org.jgrapht.traverse.DepthFirstIterator; import org.junit.Before; import org.junit.Test; -public class DirectedGraphTests { +public class DirectedGraphUnitTest { DirectedGraph directedGraph; @Before diff --git a/algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java b/algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java similarity index 97% rename from algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java rename to algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java index 6f0fb92ab7..8cf1b70898 100644 --- a/algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java +++ b/algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java @@ -12,7 +12,7 @@ import org.jgrapht.graph.SimpleWeightedGraph; import org.junit.Before; import org.junit.Test; -public class EulerianCircuitTest { +public class EulerianCircuitUnitTest { SimpleWeightedGraph simpleGraph; @Before diff --git a/animal-sniffer-mvn-plugin/pom.xml b/animal-sniffer-mvn-plugin/pom.xml index ab7b38f6e0..9ccc7354af 100644 --- a/animal-sniffer-mvn-plugin/pom.xml +++ b/animal-sniffer-mvn-plugin/pom.xml @@ -5,7 +5,7 @@ animal-sniffer-mvn-plugin jar 1.0-SNAPSHOT - example-animal-sniffer-mvn-plugin + animal-sniffer-mvn-plugin http://maven.apache.org diff --git a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationIntegrationTest.java b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationLiveTest.java similarity index 99% rename from apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationIntegrationTest.java rename to apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationLiveTest.java index 546b8fe45c..b54b62ca02 100644 --- a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationIntegrationTest.java +++ b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationLiveTest.java @@ -19,7 +19,7 @@ import java.util.List; import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -public class CayenneAdvancedOperationIntegrationTest { +public class CayenneAdvancedOperationLiveTest { private static ObjectContext context = null; @BeforeClass diff --git a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationIntegrationTest.java b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationLiveTest.java similarity index 98% rename from apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationIntegrationTest.java rename to apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationLiveTest.java index 85f06d5538..e6ca4a3634 100644 --- a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationIntegrationTest.java +++ b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationLiveTest.java @@ -16,7 +16,7 @@ import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertNull; -public class CayenneOperationIntegrationTest { +public class CayenneOperationLiveTest { private static ObjectContext context = null; @BeforeClass diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/BaseTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/BaseManualTest.java similarity index 94% rename from apache-curator/src/test/java/com/baeldung/apache/curator/BaseTest.java rename to apache-curator/src/test/java/com/baeldung/apache/curator/BaseManualTest.java index cfac3ee3f2..5722228b26 100644 --- a/apache-curator/src/test/java/com/baeldung/apache/curator/BaseTest.java +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/BaseManualTest.java @@ -6,7 +6,7 @@ import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryNTimes; import org.junit.Before; -public abstract class BaseTest { +public abstract class BaseManualTest { @Before public void setup() { diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java index d02ef8131d..1a6fe6ccd0 100644 --- a/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java @@ -12,9 +12,9 @@ import org.apache.curator.framework.CuratorFramework; import org.apache.curator.x.async.AsyncCuratorFramework; import org.junit.Test; -import com.baeldung.apache.curator.BaseTest; +import com.baeldung.apache.curator.BaseManualTest; -public class ConfigurationManagementManualTest extends BaseTest { +public class ConfigurationManagementManualTest extends BaseManualTest { private static final String KEY_FORMAT = "/%s"; diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java index 4400c1d1aa..d7caa18ce9 100644 --- a/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java @@ -11,9 +11,9 @@ import org.apache.curator.x.async.modeled.ModeledFramework; import org.apache.curator.x.async.modeled.ZPath; import org.junit.Test; -import com.baeldung.apache.curator.BaseTest; +import com.baeldung.apache.curator.BaseManualTest; -public class ModelTypedExamplesManualTest extends BaseTest { +public class ModelTypedExamplesManualTest extends BaseManualTest { @Test public void givenPath_whenStoreAModel_thenNodesAreCreated() diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java index 04f4104e6b..0c5890ad59 100644 --- a/apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java @@ -10,9 +10,9 @@ import org.apache.curator.framework.recipes.shared.SharedCount; import org.apache.curator.framework.state.ConnectionState; import org.junit.Test; -import com.baeldung.apache.curator.BaseTest; +import com.baeldung.apache.curator.BaseManualTest; -public class RecipesManualTest extends BaseTest { +public class RecipesManualTest extends BaseManualTest { @Test public void givenRunningZookeeper_whenUsingLeaderElection_thenNoErrors() { diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/ChunkerTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/ChunkerUnitTest.java similarity index 97% rename from apache-opennlp/src/test/java/com/baeldung/apache/opennlp/ChunkerTest.java rename to apache-opennlp/src/test/java/com/baeldung/apache/opennlp/ChunkerUnitTest.java index cc3abb422b..91dde8a2d1 100644 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/ChunkerTest.java +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/ChunkerUnitTest.java @@ -10,7 +10,7 @@ import opennlp.tools.tokenize.SimpleTokenizer; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; -public class ChunkerTest { +public class ChunkerUnitTest { @Test public void givenChunkerModel_whenChunk_thenChunksAreDetected() throws Exception { diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LanguageDetectorAndTrainingDataTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LanguageDetectorAndTrainingDataUnitTest.java similarity index 97% rename from apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LanguageDetectorAndTrainingDataTest.java rename to apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LanguageDetectorAndTrainingDataUnitTest.java index 5eb649dae1..82732809a5 100644 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LanguageDetectorAndTrainingDataTest.java +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LanguageDetectorAndTrainingDataUnitTest.java @@ -19,7 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import org.junit.Test; -public class LanguageDetectorAndTrainingDataTest { +public class LanguageDetectorAndTrainingDataUnitTest { @Test public void givenLanguageDictionary_whenLanguageDetect_thenLanguageIsDetected() throws FileNotFoundException, IOException { diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LemmetizerTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LemmetizerUnitTest.java similarity index 97% rename from apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LemmetizerTest.java rename to apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LemmetizerUnitTest.java index bb681fb8d8..05bc6242b2 100644 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LemmetizerTest.java +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LemmetizerUnitTest.java @@ -8,7 +8,7 @@ import opennlp.tools.tokenize.SimpleTokenizer; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; -public class LemmetizerTest { +public class LemmetizerUnitTest { @Test public void givenEnglishDictionary_whenLemmatize_thenLemmasAreDetected() throws Exception { diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/NamedEntityRecognitionTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/NamedEntityRecognitionUnitTest.java similarity index 97% rename from apache-opennlp/src/test/java/com/baeldung/apache/opennlp/NamedEntityRecognitionTest.java rename to apache-opennlp/src/test/java/com/baeldung/apache/opennlp/NamedEntityRecognitionUnitTest.java index 94224409d6..6965498e12 100644 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/NamedEntityRecognitionTest.java +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/NamedEntityRecognitionUnitTest.java @@ -11,7 +11,7 @@ import opennlp.tools.util.Span; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; -public class NamedEntityRecognitionTest { +public class NamedEntityRecognitionUnitTest { @Test public void givenEnglishPersonModel_whenNER_thenPersonsAreDetected() throws Exception { diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/POSTaggerTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/POSTaggerUnitTest.java similarity index 96% rename from apache-opennlp/src/test/java/com/baeldung/apache/opennlp/POSTaggerTest.java rename to apache-opennlp/src/test/java/com/baeldung/apache/opennlp/POSTaggerUnitTest.java index 1bfebe208c..c084dcc1f2 100644 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/POSTaggerTest.java +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/POSTaggerUnitTest.java @@ -7,7 +7,7 @@ import opennlp.tools.tokenize.SimpleTokenizer; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; -public class POSTaggerTest { +public class POSTaggerUnitTest { @Test public void givenPOSModel_whenPOSTagging_thenPOSAreDetected() throws Exception { diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/SentenceDetectionTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/SentenceDetectionUnitTest.java similarity index 96% rename from apache-opennlp/src/test/java/com/baeldung/apache/opennlp/SentenceDetectionTest.java rename to apache-opennlp/src/test/java/com/baeldung/apache/opennlp/SentenceDetectionUnitTest.java index 0250b12cbf..60ee51e7ca 100644 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/SentenceDetectionTest.java +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/SentenceDetectionUnitTest.java @@ -6,7 +6,7 @@ import opennlp.tools.sentdetect.SentenceModel; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; -public class SentenceDetectionTest { +public class SentenceDetectionUnitTest { @Test public void givenEnglishModel_whenDetect_thenSentencesAreDetected() throws Exception { diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/TokenizerTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/TokenizerUnitTest.java similarity index 97% rename from apache-opennlp/src/test/java/com/baeldung/apache/opennlp/TokenizerTest.java rename to apache-opennlp/src/test/java/com/baeldung/apache/opennlp/TokenizerUnitTest.java index a4dea57cc3..6aa18b3bee 100644 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/TokenizerTest.java +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/TokenizerUnitTest.java @@ -8,7 +8,7 @@ import opennlp.tools.tokenize.WhitespaceTokenizer; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; -public class TokenizerTest { +public class TokenizerUnitTest { @Test public void givenEnglishModel_whenTokenize_thenTokensAreDetected() throws Exception { diff --git a/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java index 5319208e85..7253238e80 100644 --- a/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java +++ b/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java @@ -1,25 +1,30 @@ package com.baeldung.poi.powerpoint; +import java.io.File; +import java.util.List; + import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xslf.usermodel.XSLFShape; import org.apache.poi.xslf.usermodel.XSLFSlide; import org.junit.After; import org.junit.Assert; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; - -import java.io.File; -import java.util.List; +import org.junit.rules.TemporaryFolder; public class PowerPointIntegrationTest { private PowerPointHelper pph; private String fileLocation; private static final String FILE_NAME = "presentation.pptx"; + + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); @Before public void setUp() throws Exception { - File currDir = new File("."); + File currDir = tempFolder.newFolder(); String path = currDir.getAbsolutePath(); fileLocation = path.substring(0, path.length() - 1) + FILE_NAME; diff --git a/azure/README.md b/azure/README.md index d51172c186..c60186e1ce 100644 --- a/azure/README.md +++ b/azure/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: -- [Deploy Spring Boot App to Azure]() +- [Deploy Spring Boot App to Azure](http://www.baeldung.com/spring-boot-azure) + diff --git a/azure/src/test/java/com/baeldung/springboot/azure/AzureApplicationTests.java b/azure/src/test/java/com/baeldung/springboot/azure/AzureApplicationIntegrationTest.java similarity index 86% rename from azure/src/test/java/com/baeldung/springboot/azure/AzureApplicationTests.java rename to azure/src/test/java/com/baeldung/springboot/azure/AzureApplicationIntegrationTest.java index 91632be11a..7c3084446f 100644 --- a/azure/src/test/java/com/baeldung/springboot/azure/AzureApplicationTests.java +++ b/azure/src/test/java/com/baeldung/springboot/azure/AzureApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class AzureApplicationTests { +public class AzureApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/bootique/src/test/java/com/baeldung/bootique/AppTest.java b/bootique/src/test/java/com/baeldung/bootique/AppUnitTest.java similarity index 96% rename from bootique/src/test/java/com/baeldung/bootique/AppTest.java rename to bootique/src/test/java/com/baeldung/bootique/AppUnitTest.java index 8856780ed4..2a113cd1ee 100644 --- a/bootique/src/test/java/com/baeldung/bootique/AppTest.java +++ b/bootique/src/test/java/com/baeldung/bootique/AppUnitTest.java @@ -9,7 +9,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; -public class AppTest { +public class AppUnitTest { @Rule public BQTestFactory bqTestFactory = new BQTestFactory(); diff --git a/camel-api/pom.xml b/camel-api/pom.xml index 86f6713cd6..4e50828b96 100644 --- a/camel-api/pom.xml +++ b/camel-api/pom.xml @@ -5,7 +5,6 @@ com.example spring-boot-camel 0.0.1-SNAPSHOT - Spring-Boot - Camel API com.baeldung diff --git a/cas/cas-secured-app/pom.xml b/cas/cas-secured-app/pom.xml index 1a9176ff3e..332ee912b6 100644 --- a/cas/cas-secured-app/pom.xml +++ b/cas/cas-secured-app/pom.xml @@ -12,7 +12,7 @@ org.springframework.boot spring-boot-starter-parent - 2.0.0.M7 + 1.5.13.RELEASE @@ -60,28 +60,6 @@ - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - UTF-8 UTF-8 diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java index 7faccbb125..2c88b74a83 100644 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java @@ -1,7 +1,7 @@ package com.baeldung.cassecuredapp.controllers; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler; diff --git a/cas/cas-server/.factorypath b/cas/cas-server/.factorypath new file mode 100644 index 0000000000..006c761796 --- /dev/null +++ b/cas/cas-server/.factorypath @@ -0,0 +1,228 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cas/cas-server/README.md b/cas/cas-server/README.md index bae8b648e5..bacf45a2a1 100644 --- a/cas/cas-server/README.md +++ b/cas/cas-server/README.md @@ -6,10 +6,11 @@ Generic CAS WAR overlay to exercise the latest versions of CAS. This overlay cou # Versions ```xml -5.1.x +5.3.x ``` # Requirements + * JDK 1.8+ # Configuration @@ -64,20 +65,23 @@ Run the CAS web application as an executable WAR via Spring Boot. This is most u ### Warning! -Be careful with this method of deployment. `bootRun` is not designed to work with already executable WAR artifacts such that CAS server web application. YMMV. Today, uses of this mode ONLY work when there is **NO OTHER** dependency added to the build script and the `cas-server-webapp` is the only present module. See [this issue](https://github.com/apereo/cas/issues/2334) and [this issue](https://github.com/spring-projects/spring-boot/issues/8320) for more info. +Be careful with this method of deployment. `bootRun` is not designed to work with already executable WAR artifacts such that CAS server web application. YMMV. Today, uses of this mode ONLY work when there is **NO OTHER** dependency added to the build script and the `cas-server-webapp` is the only present module. See [this issue](https://github.com/spring-projects/spring-boot/issues/8320) for more info. ## Spring Boot App Server Selection -There is an app.server property in the pom.xml that can be used to select a spring boot application server. -It defaults to "-tomcat" but "-jetty" and "-undertow" are supported. -It can also be set to an empty value (nothing) if you want to deploy CAS to an external application server of your choice and you don't want the spring boot libraries included. + +There is an app.server property in the `pom.xml` that can be used to select a spring boot application server. +It defaults to `-tomcat` but `-jetty` and `-undertow` are supported. + +It can also be set to an empty value (nothing) if you want to deploy CAS to an external application server of your choice. ```xml -tomcat ``` ## Windows Build -If you are building on windows, try build.cmd instead of build.sh. Arguments are similar but for usage, run: + +If you are building on windows, try `build.cmd` instead of `build.sh`. Arguments are similar but for usage, run: ``` build.cmd help @@ -86,3 +90,12 @@ build.cmd help ## External Deploy resultant `target/cas.war` to a servlet container of choice. + + +## Command Line Shell + +Invokes the CAS Command Line Shell. For a list of commands either use no arguments or use `-h`. To enter the interactive shell use `-sh`. + +```bash +./build.sh cli +``` \ No newline at end of file diff --git a/cas/cas-server/build.cmd b/cas/cas-server/build.cmd index f907dcb388..2cf9262afe 100644 --- a/cas/cas-server/build.cmd +++ b/cas/cas-server/build.cmd @@ -23,8 +23,10 @@ @if "%1" == "bootrun" call:bootrun %2 %3 %4 @if "%1" == "debug" call:debug %2 %3 %4 @if "%1" == "run" call:run %2 %3 %4 +@if "%1" == "runalone" call:runalone %2 %3 %4 @if "%1" == "help" call:help @if "%1" == "gencert" call:gencert +@if "%1" == "cli" call:runcli %2 %3 %4 @rem function section starts here @goto:eof @@ -38,7 +40,7 @@ @goto:eof :help - @echo "Usage: build.bat [copy|clean|package|run|debug|bootrun|gencert] [optional extra args for maven]" + @echo "Usage: build.bat [copy|clean|package|run|debug|bootrun|gencert|cli] [optional extra args for maven or cli]" @echo "To get started on a clean system, run "build.bat copy" and "build.bat gencert", then "build.bat run" @echo "Note that using the copy or gencert arguments will create and/or overwrite the %CAS_DIR% which is outside this project" @goto:eof @@ -66,6 +68,10 @@ call:package %1 %2 %3 & java %JAVA_ARGS% -jar target/cas.war @goto:eof +:runalone + call:package %1 %2 %3 & target/cas.war +@goto:eof + :gencert where /q keytool if ERRORLEVEL 1 ( @@ -80,3 +86,17 @@ keytool -exportcert -alias cas -storepass changeit -keystore %CAS_DIR%\thekeystore -file %CAS_DIR%\cas.cer ) @goto:eof + +:runcli + for /f %%i in ('call %MAVEN_CMD% -q --non-recursive "-Dexec.executable=cmd" "-Dexec.args=/C echo ${cas.version}" "org.codehaus.mojo:exec-maven-plugin:1.3.1:exec"') do set CAS_VERSION=%%i + @set CAS_VERSION=%CAS_VERSION: =% + @set DOWNLOAD_DIR=target + @set COMMAND_FILE=cas-server-support-shell-%CAS_VERSION%.jar + @if not exist %DOWNLOAD_DIR% mkdir %DOWNLOAD_DIR% + @if not exist %DOWNLOAD_DIR%\%COMMAND_FILE% ( + @call mvn org.apache.maven.plugins:maven-dependency-plugin:3.0.2:get -DgroupId=org.apereo.cas -DartifactId=cas-server-support-shell -Dversion=%CAS_VERSION% -Dpackaging=jar -DartifactItem.outputDirectory=%DOWNLOAD_DIR% -DartifactItem.destFileName=%COMMAND_FILE% -DremoteRepositories=central::default::http://repo1.maven.apache.org/maven2,snapshots::::https://oss.sonatype.org/content/repositories/snapshots -Dtransitive=false + @call mvn org.apache.maven.plugins:maven-dependency-plugin:3.0.2:copy -Dmdep.useBaseVersion=true -Dartifact=org.apereo.cas:cas-server-support-shell:%CAS_VERSION%:jar -DoutputDirectory=%DOWNLOAD_DIR% + ) + @call java %JAVA_ARGS% -jar %DOWNLOAD_DIR%\%COMMAND_FILE% %1 %2 %3 + +@goto:eof \ No newline at end of file diff --git a/cas/cas-server/build.sh b/cas/cas-server/build.sh index e33f7de854..4d80aa2593 100644 --- a/cas/cas-server/build.sh +++ b/cas/cas-server/build.sh @@ -13,24 +13,31 @@ function help() { echo "Usage: build.sh [copy|clean|package|run|debug|bootrun|gencert]" echo " copy: Copy config from ./etc/cas/config to /etc/cas/config" echo " clean: Clean Maven build directory" - echo " package: Clean and build CAS war, also call copy" - echo " run: Build and run CAS.war via spring boot (java -jar target/cas.war)" + echo " package: Clean and build CAS war" + echo " run: Build and run cas.war via Java (i.e. java -jar target/cas.war)" + echo " runalone: Build and run cas.war on its own as a standalone executable (target/cas.war)" echo " debug: Run CAS.war and listen for Java debugger on port 5000" - echo " bootrun: Run with maven spring boot plugin, doesn't work with multiple dependencies" + echo " bootrun: Run with maven spring boot plugin" + echo " listviews: List all CAS views that ship with the web application and can be customized in the overlay" + echo " getview: Ask for a view name to be included in the overlay for customizations" echo " gencert: Create keystore with SSL certificate in location where CAS looks by default" + echo " cli: Run the CAS command line shell and pass commands" } function clean() { + shift ./mvnw clean "$@" } function package() { + shift ./mvnw clean package -T 5 "$@" - copy + # copy } function bootrun() { - ./mvnw clean package spring-boot:run -T 5 "$@" + shift + ./mvnw clean package spring-boot:run -P bootiful -T 5 "$@" } function debug() { @@ -41,14 +48,59 @@ function run() { package && java -jar target/cas.war } +function runalone() { + shift + ./mvnw clean package -P default,exec "$@" + chmod +x target/cas.war + target/cas.war +} + +function listviews() { + shift + explodeapp + find $PWD/target/cas -type f -name "*.html" | xargs -n 1 basename | sort | more +} + +function explodeapp() { + if [ ! -d $PWD/target/cas ];then + echo "Building the CAS web application and exploding the final war file..." + ./mvnw clean package war:exploded "$@" + fi + echo "Exploded the CAS web application file." +} + +function getview() { + shift + explodeapp + echo "Searching for view name $@..." + results=`find $PWD/target/cas -type f -name "*.html" | grep -i "$@"` + echo -e "Found view(s): \n$results" + count=`wc -w <<< "$results"` + if [ "$count" -eq 1 ];then + # echo "Found view $results to include in the overlay" + firststring="target/cas/WEB-INF/classes" + secondstring="src/main/resources" + overlayfile=`echo "${results/$firststring/$secondstring}"` + overlaypath=`dirname "${overlayfile}"` + # echo "Overlay file is $overlayfile to be created at $overlaypath" + mkdir -p $overlaypath + cp $results $overlaypath + echo "Created view at $overlayfile" + ls $overlayfile + else + echo "More than one view file is found. Narrow down the search query..." + fi +} + + function gencert() { - if [[ ! -d /etc/cas ]] ; then + if [[ ! -d /etc/cas ]] ; then copy fi which keytool if [[ $? -ne 0 ]] ; then - echo Error: Java JDK \'keytool\' is not installed or is not in the path - exit 1 + echo Error: Java JDK \'keytool\' is not installed or is not in the path + exit 1 fi # override DNAME and CERT_SUBJ_ALT_NAMES before calling or use dummy values DNAME="${DNAME:-CN=cas.example.org,OU=Example,OU=Org,C=US}" @@ -58,21 +110,49 @@ function gencert() { keytool -exportcert -alias cas -storepass changeit -keystore /etc/cas/thekeystore -file /etc/cas/cas.cer } +function cli() { + + CAS_VERSION=$(./mvnw -q -Dexec.executable="echo" -Dexec.args='${cas.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec 2>/dev/null) + # echo "CAS version: $CAS_VERSION" + JAR_FILE_NAME="cas-server-support-shell-${CAS_VERSION}.jar" + # echo "JAR name: $JAR_FILE_NAME" + JAR_PATH="org/apereo/cas/cas-server-support-shell/${CAS_VERSION}/${JAR_FILE_NAME}" + # echo "JAR path: $JAR_PATH" + + JAR_FILE_LOCAL="$HOME/.m2/repository/$JAR_PATH"; + # echo "Local JAR file path: $JAR_FILE_LOCAL"; + if [ -f "$JAR_FILE_LOCAL" ]; then + # echo "Using JAR file locally at $JAR_FILE_LOCAL" + java -jar $JAR_FILE_LOCAL "$@" + exit 0; + fi + + DOWNLOAD_DIR=./target + COMMAND_FILE="${DOWNLOAD_DIR}/${JAR_FILE_NAME}" + if [ ! -f "$COMMAND_FILE" ]; then + mkdir -p $DOWNLOAD_DIR + ./mvnw org.apache.maven.plugins:maven-dependency-plugin:3.0.2:get -DgroupId=org.apereo.cas -DartifactId=cas-server-support-shell -Dversion=$CAS_VERSION -Dpackaging=jar -DartifactItem.outputDirectory=$DOWNLOAD_DIR -DremoteRepositories=central::default::http://repo1.maven.apache.org/maven2,snapshots::::https://oss.sonatype.org/content/repositories/snapshots -Dtransitive=false + ./mvnw org.apache.maven.plugins:maven-dependency-plugin:3.0.2:copy -Dmdep.useBaseVersion=true -Dartifact=org.apereo.cas:cas-server-support-shell:$CAS_VERSION:jar -DoutputDirectory=$DOWNLOAD_DIR + fi + java -jar $COMMAND_FILE "$@" + exit 0; + +} + if [ $# -eq 0 ]; then echo -e "No commands provided. Defaulting to [run]\n" run exit 0 fi - case "$1" in "copy") - copy + copy ;; "clean") shift clean "$@" - ;; + ;; "package") shift package "$@" @@ -87,11 +167,23 @@ case "$1" in "run") run "$@" ;; +"runalone") + runalone "$@" + ;; +"listviews") + listviews "$@" + ;; "gencert") gencert "$@" ;; +"getview") + getview "$@" + ;; +"cli") + shift + cli "$@" + ;; *) help ;; esac - diff --git a/cas/cas-server/etc/cas/config/log4j2.xml b/cas/cas-server/etc/cas/config/log4j2.xml index 53b30b4228..e688cc0350 100644 --- a/cas/cas-server/etc/cas/config/log4j2.xml +++ b/cas/cas-server/etc/cas/config/log4j2.xml @@ -92,7 +92,7 @@ - + diff --git a/cas/cas-server/maven/maven-wrapper.jar b/cas/cas-server/maven/maven-wrapper.jar new file mode 100644 index 0000000000..18ba302c65 Binary files /dev/null and b/cas/cas-server/maven/maven-wrapper.jar differ diff --git a/cas/cas-server/maven/maven-wrapper.properties b/cas/cas-server/maven/maven-wrapper.properties index b368e4609a..97a946225a 100644 --- a/cas/cas-server/maven/maven-wrapper.properties +++ b/cas/cas-server/maven/maven-wrapper.properties @@ -1 +1,3 @@ -distributionUrl=https\://repository.apache.org/content/repositories/releases/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip +#Maven download properties +#Fri Dec 01 21:35:11 MST 2017 +distributionUrl=https\://repository.apache.org/content/repositories/releases/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip diff --git a/cas/cas-server/pom.xml b/cas/cas-server/pom.xml index 30e29b155f..52ddba1a68 100644 --- a/cas/cas-server/pom.xml +++ b/cas/cas-server/pom.xml @@ -7,37 +7,23 @@ cas-server war 1.0 - - - org.springframework.boot - spring-boot-starter-parent - ${org.springframework.boot.spring-boot-starter-parent.version} - - - + - org.apereo.cas - cas-server-webapp${app.server} - ${cas.version} - war - runtime - - - org.apereo.cas - cas-server-support-json-service-registry - ${cas.version} - - - org.apereo.cas - cas-server-support-jdbc - ${cas.version} - - - org.apereo.cas - cas-server-support-jdbc-drivers - ${cas.version} - + org.apereo.cas + cas-server-support-json-service-registry + ${cas.version} + + + org.apereo.cas + cas-server-support-jdbc + ${cas.version} + + + org.apereo.cas + cas-server-support-jdbc-drivers + ${cas.version} + @@ -45,7 +31,7 @@ com.rimerosolutions.maven.plugins wrapper-maven-plugin - ${wrapper-maven-plugin.version} + 0.0.4 true MD5 @@ -56,22 +42,30 @@ spring-boot-maven-plugin ${springboot.version} - org.springframework.boot.loader.WarLauncher + ${mainClassName} true + ${isExecutable} + WAR + + + + repackage + + + org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} + 2.6 cas false false false - ${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF - + ${manifestFileToUse} @@ -84,47 +78,26 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - + 3.3 cas - - - - false - - pgp - - - - com.github.s4u.plugins - pgpverify-maven-plugin - ${pgpverify-maven-plugin.version} - - - - check - - - - - hkp://pool.sks-keyservers.net - ${settings.localRepository}/pgpkeys-cache - test - true - false - - - - - - + + 5.3.0-SNAPSHOT + 1.5.13.RELEASE + + -tomcat + + org.springframework.boot.loader.WarLauncher + false + ${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF + + 1.8 + 1.8 + UTF-8 + @@ -151,25 +124,110 @@ shibboleth-releases https://build.shibboleth.net/nexus/content/repositories/releases - - spring-milestones - https://repo.spring.io/milestone - - - 5.1.4 - 1.5.3.RELEASE - - -tomcat - 1.8 - 1.8 - UTF-8 - 2.0.0.M7 - 0.0.4 - 2.6 - 3.7.0 - 1.1.0 - + + + + true + + default + + + org.apereo.cas + cas-server-webapp${app.server} + ${cas.version} + war + runtime + + + + - \ No newline at end of file + + + false + + exec + + org.apereo.cas.web.CasWebApplication + true + + + + + + com.soebes.maven.plugins + echo-maven-plugin + 0.3.0 + + + prepare-package + + echo + + + + + + Executable profile to make the generated CAS web application executable. + + + + + + + + + + false + + bootiful + + -tomcat + false + + + + org.apereo.cas + cas-server-webapp${app.server} + ${cas.version} + war + runtime + + + + + + + false + + pgp + + + + com.github.s4u.plugins + pgpverify-maven-plugin + 1.1.0 + + + + check + + + + + hkp://pool.sks-keyservers.net + ${settings.localRepository}/pgpkeys-cache + test + true + false + + + + + + + diff --git a/cas/cas-server/src/main/resources/application.properties b/cas/cas-server/src/main/resources/application.properties index 018fd351ff..7735fcabdc 100644 --- a/cas/cas-server/src/main/resources/application.properties +++ b/cas/cas-server/src/main/resources/application.properties @@ -43,7 +43,7 @@ spring.http.encoding.force=true ## #CAS CONFIG LOCATION # -cas.standalone.config=classpath:/etc/cas/config +standalone.config=classpath:/etc/cas/config ## @@ -109,7 +109,7 @@ cas.authn.jdbc.query[0].sql=SELECT * FROM users WHERE email = ? cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect cas.authn.jdbc.query[0].user=root -cas.authn.jdbc.query[0].password=root +cas.authn.jdbc.query[0].password=1234 cas.authn.jdbc.query[0].ddlAuto=none #cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver diff --git a/cas/cas-server/src/main/resources/cas.properties b/cas/cas-server/src/main/resources/cas.properties index f80f22fc11..e39d68f312 100644 --- a/cas/cas-server/src/main/resources/cas.properties +++ b/cas/cas-server/src/main/resources/cas.properties @@ -3,38 +3,7 @@ cas.server.prefix: https://localhost:643/cas cas.adminPagesSecurity.ip=127\.0\.0\.1 +logging.config: file:/etc/cas/config/log4j2.xml + cas.serviceRegistry.initFromJson=true -cas.serviceRegistry.config.location=classpath:/services - -cas.authn.accept.users= -cas.authn.accept.name= - - -#CAS Database Authentication Property - -# cas.authn.jdbc.query[0].healthQuery= -# cas.authn.jdbc.query[0].isolateInternalQueries=false -# cas.authn.jdbc.query[0].failFast=true -# cas.authn.jdbc.query[0].isolationLevelName=ISOLATION_READ_COMMITTED -# cas.authn.jdbc.query[0].leakThreshold=10 -# cas.authn.jdbc.query[0].propagationBehaviorName=PROPAGATION_REQUIRED -# cas.authn.jdbc.query[0].batchSize=1 -# cas.authn.jdbc.query[0].maxAgeDays=180 -# cas.authn.jdbc.query[0].autocommit=false -# cas.authn.jdbc.query[0].idleTimeout=5000 -# cas.authn.jdbc.query[0].credentialCriteria= -# cas.authn.jdbc.query[0].name= -# cas.authn.jdbc.query[0].order=0 -# cas.authn.jdbc.query[0].dataSourceName= -# cas.authn.jdbc.query[0].dataSourceProxy=false -# cas.authn.jdbc.query[0].fieldExpired= -# cas.authn.jdbc.query[0].fieldDisabled= -# cas.authn.jdbc.query[0].principalAttributeList=sn,cn:commonName,givenName -# cas.authn.jdbc.query[0].passwordEncoder.type=NONE|DEFAULT|STANDARD|BCRYPT|SCRYPT|PBKDF2|com.example.CustomPasswordEncoder -# cas.authn.jdbc.query[0].passwordEncoder.characterEncoding= -# cas.authn.jdbc.query[0].passwordEncoder.encodingAlgorithm= -# cas.authn.jdbc.query[0].passwordEncoder.secret= -# cas.authn.jdbc.query[0].passwordEncoder.strength=16 -# cas.authn.jdbc.query[0].principalTransformation.suffix= -# cas.authn.jdbc.query[0].principalTransformation.caseConversion=NONE|UPPERCASE|LOWERCASE -# cas.authn.jdbc.query[0].principalTransformation.prefix= \ No newline at end of file +cas.serviceRegistry.config.location=classpath:/services \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml b/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml index 53b30b4228..e688cc0350 100644 --- a/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml +++ b/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml @@ -92,7 +92,7 @@ - + diff --git a/cas/cas-server/src/main/resources/etc/cas/thekeystore b/cas/cas-server/src/main/resources/etc/cas/thekeystore index 86170dff16..77bf895249 100644 Binary files a/cas/cas-server/src/main/resources/etc/cas/thekeystore and b/cas/cas-server/src/main/resources/etc/cas/thekeystore differ diff --git a/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt b/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt index 5bd9d5baba..12ef688a08 100644 Binary files a/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt and b/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt differ diff --git a/cas/cas-server/src/main/resources/log4j2.xml b/cas/cas-server/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..e688cc0350 --- /dev/null +++ b/cas/cas-server/src/main/resources/log4j2.xml @@ -0,0 +1,117 @@ + + + + + + . + + warn + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cas/cas-server/src/main/resources/services/casSecuredApp.json b/cas/cas-server/src/main/resources/services/casSecuredApp-19991.json similarity index 100% rename from cas/cas-server/src/main/resources/services/casSecuredApp.json rename to cas/cas-server/src/main/resources/services/casSecuredApp-19991.json diff --git a/cdi/pom.xml b/cdi/pom.xml index 00cc96a7ed..0c14df6e73 100644 --- a/cdi/pom.xml +++ b/cdi/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -38,7 +38,6 @@ - 4.3.4.RELEASE 1.8.9 2.4.1.Final diff --git a/core-java-10/README.md b/core-java-10/README.md new file mode 100644 index 0000000000..863448c194 --- /dev/null +++ b/core-java-10/README.md @@ -0,0 +1,5 @@ + +### Relevant Articles: + +- [Java 10 LocalVariable Type-Inference](http://www.baeldung.com/java-10-local-variable-type-inference) +- [Guide to Java 10](http://www.baeldung.com/java-10-overview) diff --git a/core-java-8/README.md b/core-java-8/README.md index f0d7818f5b..df6d50ad30 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -50,4 +50,6 @@ - [Filtering Kotlin Collections](http://www.baeldung.com/kotlin-filter-collection) - [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java) - [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time) +- [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get) +- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table) diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index aab349781a..20db1e1146 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -195,6 +195,16 @@ + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + -parameters + + org.springframework.boot spring-boot-maven-plugin diff --git a/core-java-8/src/main/java/com/baeldung/reflect/Person.java b/core-java-8/src/main/java/com/baeldung/reflect/Person.java new file mode 100644 index 0000000000..fba25aca8b --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reflect/Person.java @@ -0,0 +1,18 @@ +package com.baeldung.reflect; + +public class Person { + + private String fullName; + + public Person(String fullName) { + this.fullName = fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getFullName() { + return fullName; + } +} diff --git a/core-java-8/src/test/java/com/baeldung/counter/CounterTest.java b/core-java-8/src/test/java/com/baeldung/counter/CounterUnitTest.java similarity index 94% rename from core-java-8/src/test/java/com/baeldung/counter/CounterTest.java rename to core-java-8/src/test/java/com/baeldung/counter/CounterUnitTest.java index 657b510452..ef57fc2c6e 100644 --- a/core-java-8/src/test/java/com/baeldung/counter/CounterTest.java +++ b/core-java-8/src/test/java/com/baeldung/counter/CounterUnitTest.java @@ -9,7 +9,7 @@ import org.junit.Test; import com.baeldung.counter.CounterUtil.MutableInteger; -public class CounterTest { +public class CounterUnitTest { @Test public void whenMapWithWrapperAsCounter_runsSuccessfully() { diff --git a/core-java-8/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListTest.java b/core-java-8/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java similarity index 99% rename from core-java-8/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListTest.java rename to core-java-8/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java index 45ee6eda33..3c96cf1392 100644 --- a/core-java-8/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListTest.java +++ b/core-java-8/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java @@ -7,7 +7,7 @@ import java.util.List; import org.junit.Test; -public class FindACustomerInGivenListTest { +public class FindACustomerInGivenListUnitTest { private static List customers = new ArrayList<>(); diff --git a/core-java-8/src/test/java/com/baeldung/iterators/IteratorsTest.java b/core-java-8/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java similarity index 96% rename from core-java-8/src/test/java/com/baeldung/iterators/IteratorsTest.java rename to core-java-8/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java index 73793da7ae..36e1f4a83c 100644 --- a/core-java-8/src/test/java/com/baeldung/iterators/IteratorsTest.java +++ b/core-java-8/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java @@ -16,7 +16,7 @@ import org.junit.Test; * @author Santosh Thakur */ -public class IteratorsTest { +public class IteratorsUnitTest { @Test public void whenFailFast_ThenThrowsException() { diff --git a/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java new file mode 100644 index 0000000000..e79c90b684 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.java8; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.junit.Assert.assertEquals; + +public class UnsignedArithmeticUnitTest { + @Test + public void whenDoublingALargeByteNumber_thenOverflow() { + byte b1 = 100; + byte b2 = (byte) (b1 << 1); + + assertEquals(-56, b2); + } + + @Test + public void whenComparingNumbers_thenNegativeIsInterpretedAsUnsigned() { + int positive = Integer.MAX_VALUE; + int negative = Integer.MIN_VALUE; + + int signedComparison = Integer.compare(positive, negative); + assertEquals(1, signedComparison); + + int unsignedComparison = Integer.compareUnsigned(positive, negative); + assertEquals(-1, unsignedComparison); + + assertEquals(negative, positive + 1); + } + + @Test + public void whenDividingNumbers_thenNegativeIsInterpretedAsUnsigned() { + int positive = Integer.MAX_VALUE; + int negative = Integer.MIN_VALUE; + + assertEquals(-1, negative / positive); + assertEquals(1, Integer.divideUnsigned(negative, positive)); + + assertEquals(-1, negative % positive); + assertEquals(1, Integer.divideUnsigned(negative, positive)); + } + + @Test + public void whenParsingNumbers_thenNegativeIsInterpretedAsUnsigned() { + Throwable thrown = catchThrowable(() -> Integer.parseInt("2147483648")); + assertThat(thrown).isInstanceOf(NumberFormatException.class); + + assertEquals(Integer.MAX_VALUE + 1, Integer.parseUnsignedInt("2147483648")); + } + + @Test + public void whenFormattingNumbers_thenNegativeIsInterpretedAsUnsigned() { + String signedString = Integer.toString(Integer.MIN_VALUE); + assertEquals("-2147483648", signedString); + + String unsignedString = Integer.toUnsignedString(Integer.MIN_VALUE); + assertEquals("2147483648", unsignedString); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetTest.java b/core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetUnitTest.java similarity index 95% rename from core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetTest.java rename to core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetUnitTest.java index 2519a77f1f..c8a631d9f0 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetUnitTest.java @@ -8,11 +8,11 @@ import static org.junit.Assert.*; import com.baeldung.optional.OrElseAndOrElseGet; -public class OrElseAndOrElseGetTest { +public class OrElseAndOrElseGetUnitTest { private OrElseAndOrElseGet orElsevsOrElseGet = new OrElseAndOrElseGet(); - private static final Logger LOG = LoggerFactory.getLogger(OrElseAndOrElseGetTest.class); + private static final Logger LOG = LoggerFactory.getLogger(OrElseAndOrElseGetUnitTest.class); @Test public void givenNonEmptyOptional_whenOrElseUsed_thenGivenStringReturned() { diff --git a/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java b/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorUnitTest.java similarity index 93% rename from core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java rename to core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorUnitTest.java index e53e1c183e..0e7396c9dd 100644 --- a/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java +++ b/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorUnitTest.java @@ -7,7 +7,7 @@ import java.util.List; import org.junit.Test; import static org.junit.Assert.*; -public class PrimeGeneratorTest { +public class PrimeGeneratorUnitTest { @Test public void whenBruteForced_returnsSuccessfully() { final List primeNumbers = primeNumbersBruteForce(20); diff --git a/core-java-8/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java b/core-java-8/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java new file mode 100644 index 0000000000..b191c94826 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.reflect; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.lang.reflect.Parameter; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import org.junit.Test; + +public class MethodParamNameUnitTest { + + @Test + public void whenGetConstructorParams_thenOk() + throws NoSuchMethodException, SecurityException { + List parameters + = Arrays.asList(Person.class.getConstructor(String.class).getParameters()); + Optional parameter + = parameters.stream().filter(Parameter::isNamePresent).findFirst(); + assertThat(parameter.get().getName()).isEqualTo("fullName"); + } + + @Test + public void whenGetMethodParams_thenOk() + throws NoSuchMethodException, SecurityException { + List parameters + = Arrays.asList( + Person.class.getMethod("setFullName", String.class).getParameters()); + Optional parameter + = parameters.stream().filter(Parameter::isNamePresent).findFirst(); + assertThat(parameter.get().getName()).isEqualTo("fullName"); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorTest.java b/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorUnitTest.java similarity index 95% rename from core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorTest.java rename to core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorUnitTest.java index 64dd65cf5e..81fad12eb0 100644 --- a/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorTest.java +++ b/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorUnitTest.java @@ -9,7 +9,7 @@ import static org.assertj.core.api.Assertions.*; import org.junit.Before; import org.junit.Test; -public class ExecutorTest { +public class ExecutorUnitTest { Article article; Stream stream; Spliterator spliterator; diff --git a/core-java-8/src/test/java/com/baeldung/stream/StreamApiTest.java b/core-java-8/src/test/java/com/baeldung/stream/StreamApiUnitTest.java similarity index 97% rename from core-java-8/src/test/java/com/baeldung/stream/StreamApiTest.java rename to core-java-8/src/test/java/com/baeldung/stream/StreamApiUnitTest.java index f4d0ac6b08..71569a1c82 100644 --- a/core-java-8/src/test/java/com/baeldung/stream/StreamApiTest.java +++ b/core-java-8/src/test/java/com/baeldung/stream/StreamApiUnitTest.java @@ -7,7 +7,7 @@ import java.util.List; import static org.junit.Assert.assertEquals; -public class StreamApiTest { +public class StreamApiUnitTest { @Test public void givenList_whenGetLastElementUsingReduce_thenReturnLastElement() { diff --git a/core-java-8/src/test/java/com/baeldung/stream/StreamIndicesTest.java b/core-java-8/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java similarity index 98% rename from core-java-8/src/test/java/com/baeldung/stream/StreamIndicesTest.java rename to core-java-8/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java index a02ef4031e..36a609f536 100644 --- a/core-java-8/src/test/java/com/baeldung/stream/StreamIndicesTest.java +++ b/core-java-8/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java @@ -8,7 +8,7 @@ import java.util.List; import static org.junit.Assert.assertEquals; -public class StreamIndicesTest { +public class StreamIndicesUnitTest { @Test public void whenCalled_thenReturnListOfEvenIndexedStrings() { diff --git a/core-java-8/src/test/java/com/baeldung/stream/StreamToImmutableTest.java b/core-java-8/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java similarity index 98% rename from core-java-8/src/test/java/com/baeldung/stream/StreamToImmutableTest.java rename to core-java-8/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java index 69b0b6d3ef..bd540201d2 100644 --- a/core-java-8/src/test/java/com/baeldung/stream/StreamToImmutableTest.java +++ b/core-java-8/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java @@ -16,7 +16,7 @@ import org.junit.Test; import com.baeldung.stream.mycollectors.MyImmutableListCollector; import com.google.common.collect.ImmutableList; -public class StreamToImmutableTest { +public class StreamToImmutableUnitTest { @Test public void whenUsingCollectingToImmutableSet_thenSuccess() { diff --git a/core-java-8/src/test/java/com/baeldung/stream/SupplierStreamTest.java b/core-java-8/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java similarity index 93% rename from core-java-8/src/test/java/com/baeldung/stream/SupplierStreamTest.java rename to core-java-8/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java index d78c9fca35..a496e18b2d 100644 --- a/core-java-8/src/test/java/com/baeldung/stream/SupplierStreamTest.java +++ b/core-java-8/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java @@ -8,7 +8,7 @@ import java.util.stream.Stream; import org.junit.Test; -public class SupplierStreamTest { +public class SupplierStreamUnitTest { @Test(expected = IllegalStateException.class) public void givenStream_whenStreamUsedTwice_thenThrowException() { diff --git a/core-java-8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java b/core-java-8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java similarity index 96% rename from core-java-8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java rename to core-java-8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java index 513f163da8..5ea0e840a2 100644 --- a/core-java-8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java +++ b/core-java-8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java @@ -9,7 +9,7 @@ import java.time.temporal.TemporalAdjuster; import static org.junit.Assert.assertEquals; -public class CustomTemporalAdjusterTest { +public class CustomTemporalAdjusterUnitTest { private static final TemporalAdjuster NEXT_WORKING_DAY = new CustomTemporalAdjuster(); diff --git a/core-java-8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersTest.java b/core-java-8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java similarity index 92% rename from core-java-8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersTest.java rename to core-java-8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java index d06da5a782..175964dd21 100644 --- a/core-java-8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersTest.java +++ b/core-java-8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java @@ -7,7 +7,7 @@ import java.time.temporal.TemporalAdjusters; import org.junit.Assert; import org.junit.Test; -public class TemporalAdjustersTest { +public class TemporalAdjustersUnitTest { @Test public void whenAdjust_thenNextSunday() { diff --git a/core-java-8/src/test/java/com/baeldung/typeinference/TypeInferenceUnitTest.java b/core-java-8/src/test/java/com/baeldung/typeinference/TypeInferenceUnitTest.java new file mode 100644 index 0000000000..b9600a18cb --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/typeinference/TypeInferenceUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.typeinference; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; + +public class TypeInferenceUnitTest { + + @Test + public void givenNoTypeInference_whenInvokingGenericMethodsWithTypeParameters_ObjectsAreCreated() { + // Without type inference. code is verbose. + Map> mapOfMaps = new HashMap>(); + List strList = Collections. emptyList(); + List intList = Collections. emptyList(); + + assertTrue(mapOfMaps.isEmpty()); + assertTrue(strList.isEmpty()); + assertTrue(intList.isEmpty()); + } + + @Test + public void givenTypeInference_whenInvokingGenericMethodsWithoutTypeParameters_ObjectsAreCreated() { + // With type inference. code is concise. + List strListInferred = Collections.emptyList(); + List intListInferred = Collections.emptyList(); + + assertTrue(strListInferred.isEmpty()); + assertTrue(intListInferred.isEmpty()); + } + + @Test + public void givenJava7_whenInvokingCostructorWithoutTypeParameters_ObjectsAreCreated() { + // Type Inference for constructor using diamond operator. + Map> mapOfMapsInferred = new HashMap<>(); + + assertTrue(mapOfMapsInferred.isEmpty()); + assertEquals("public class java.util.HashMap", mapOfMapsInferred.getClass() + .toGenericString()); + } + + static List add(List list, T a, T b) { + list.add(a); + list.add(b); + return list; + } + + @Test + public void givenGenericMethod_WhenInvokedWithoutExplicitTypes_TypesAreInferred() { + // Generalized target-type inference + List strListGeneralized = add(new ArrayList<>(), "abc", "def"); + List intListGeneralized = add(new ArrayList<>(), 1, 2); + List numListGeneralized = add(new ArrayList<>(), 1, 2.0); + + assertEquals("public class java.util.ArrayList", strListGeneralized.getClass() + .toGenericString()); + assertFalse(intListGeneralized.isEmpty()); + assertEquals(2, numListGeneralized.size()); + } + + @Test + public void givenLambdaExpressions_whenParameterTypesNotSpecified_ParameterTypesAreInferred() { + // Type Inference and Lambda Expressions. + List intList = Arrays.asList(5, 3, 4, 2, 1); + Collections.sort(intList, (a, b) -> { + assertEquals("java.lang.Integer", a.getClass().getName()); + return a.compareTo(b); + }); + assertEquals("[1, 2, 3, 4, 5]", Arrays.toString(intList.toArray())); + + List strList = Arrays.asList("Red", "Blue", "Green"); + Collections.sort(strList, (a, b) -> { + assertEquals("java.lang.String", a.getClass().getName()); + return a.compareTo(b); + }); + assertEquals("[Blue, Green, Red]", Arrays.toString(strList.toArray())); + } + +} diff --git a/core-java-9/README.md b/core-java-9/README.md index 59b0929871..4223e57d4b 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -24,3 +24,4 @@ - [Method Handles in Java](http://www.baeldung.com/java-method-handles) - [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue) - [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity) +- [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional) diff --git a/core-java-9/pom.xml b/core-java-9/pom.xml index 1f92ee71f8..0662e1e9a2 100644 --- a/core-java-9/pom.xml +++ b/core-java-9/pom.xml @@ -47,6 +47,11 @@ ${awaitility.version} test + + com.google.guava + guava + ${guava.version} + @@ -89,6 +94,7 @@ 1.7.0 1.9 1.9 + 25.1-jre diff --git a/core-java-9/src/main/java/com/baeldung/optionals/Optionals.java b/core-java-9/src/main/java/com/baeldung/optionals/Optionals.java new file mode 100644 index 0000000000..5efa607f94 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/optionals/Optionals.java @@ -0,0 +1,26 @@ +package com.baeldung.optionals; + +import java.util.Optional; + +public class Optionals { + + public static Optional or(Optional optional, Optional fallback) { + return optional.isPresent() ? optional : fallback; + } + + public static Optional getName(Optional name) { + return name.or(() -> getCustomMessage()); + } + + public static com.google.common.base.Optional getOptionalGuavaName(com.google.common.base.Optional name) { + return name.or(getCustomMessageGuava()); + } + + private static Optional getCustomMessage() { + return Optional.of("Name not provided"); + } + + private static com.google.common.base.Optional getCustomMessageGuava() { + return com.google.common.base.Optional.of("Name not provided"); + } +} \ No newline at end of file diff --git a/core-java-9/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java new file mode 100644 index 0000000000..aa2fb34753 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java @@ -0,0 +1,199 @@ +package com.baeldung.java9.modules; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.collection.IsEmptyCollection.empty; +import static org.junit.Assert.*; + +import java.lang.module.ModuleDescriptor; +import java.lang.module.ModuleDescriptor.*; +import java.sql.Date; +import java.sql.Driver; +import java.util.HashMap; +import java.util.Set; +import java.util.stream.Collectors; + +import org.junit.Before; +import org.junit.Test; + +public class ModuleAPIUnitTest { + + public static final String JAVA_BASE_MODULE_NAME = "java.base"; + + private Module javaBaseModule; + private Module javaSqlModule; + private Module module; + + @Before + public void setUp() { + Class hashMapClass = HashMap.class; + javaBaseModule = hashMapClass.getModule(); + + Class dateClass = Date.class; + javaSqlModule = dateClass.getModule(); + + Class personClass = Person.class; + module = personClass.getModule(); + } + + @Test + public void whenCheckingIfNamed_thenModuleIsNamed() { + assertThat(javaBaseModule.isNamed(), is(true)); + assertThat(javaBaseModule.getName(), is(JAVA_BASE_MODULE_NAME)); + } + + @Test + public void whenCheckingIfNamed_thenModuleIsUnnamed() { + assertThat(module.isNamed(), is(false)); + assertThat(module.getName(), is(nullValue())); + } + + @Test + public void whenExtractingPackagesContainedInAModule_thenModuleContainsOnlyFewOfThem() { + assertTrue(javaBaseModule.getPackages().contains("java.lang.annotation")); + assertFalse(javaBaseModule.getPackages().contains("java.sql")); + } + + @Test + public void whenRetrievingClassLoader_thenClassLoaderIsReturned() { + assertThat( + module.getClassLoader().getClass().getName(), + is("jdk.internal.loader.ClassLoaders$AppClassLoader") + ); + } + + @Test + public void whenGettingAnnotationsPresentOnAModule_thenNoAnnotationsArePresent() { + assertThat(javaBaseModule.getAnnotations().length, is(0)); + } + + @Test + public void whenGettingLayerOfAModule_thenModuleLayerInformationAreAvailable() { + ModuleLayer javaBaseModuleLayer = javaBaseModule.getLayer(); + + assertTrue(javaBaseModuleLayer.configuration().findModule(JAVA_BASE_MODULE_NAME).isPresent()); + assertThat(javaBaseModuleLayer.configuration().modules().size(), is(78)); + assertTrue(javaBaseModuleLayer.parents().get(0).configuration().parents().isEmpty()); + } + + @Test + public void whenRetrievingModuleDescriptor_thenTypeOfModuleIsInferred() { + ModuleDescriptor javaBaseModuleDescriptor = javaBaseModule.getDescriptor(); + ModuleDescriptor javaSqlModuleDescriptor = javaSqlModule.getDescriptor(); + + assertFalse(javaBaseModuleDescriptor.isAutomatic()); + assertFalse(javaBaseModuleDescriptor.isOpen()); + assertFalse(javaSqlModuleDescriptor.isAutomatic()); + assertFalse(javaSqlModuleDescriptor.isOpen()); + } + + @Test + public void givenModuleName_whenBuildingModuleDescriptor_thenBuilt() { + Builder moduleBuilder = ModuleDescriptor.newModule("baeldung.base"); + + ModuleDescriptor moduleDescriptor = moduleBuilder.build(); + + assertThat(moduleDescriptor.name(), is("baeldung.base")); + } + + @Test + public void givenModules_whenAccessingModuleDescriptorRequires_thenRequiresAreReturned() { + Set javaBaseRequires = javaBaseModule.getDescriptor().requires(); + Set javaSqlRequires = javaSqlModule.getDescriptor().requires(); + + Set javaSqlRequiresNames = javaSqlRequires.stream() + .map(Requires::name) + .collect(Collectors.toSet()); + + assertThat(javaBaseRequires, empty()); + assertThat(javaSqlRequires.size(), is(3)); + assertThat(javaSqlRequiresNames, containsInAnyOrder("java.base", "java.xml", "java.logging")); + } + + @Test + public void givenModules_whenAccessingModuleDescriptorProvides_thenProvidesAreReturned() { + Set javaBaseProvides = javaBaseModule.getDescriptor().provides(); + Set javaSqlProvides = javaSqlModule.getDescriptor().provides(); + + Set javaBaseProvidesService = javaBaseProvides.stream() + .map(Provides::service) + .collect(Collectors.toSet()); + + assertThat(javaBaseProvidesService, contains("java.nio.file.spi.FileSystemProvider")); + assertThat(javaSqlProvides, empty()); + } + + @Test + public void givenModules_whenAccessingModuleDescriptorExports_thenExportsAreReturned() { + Set javaBaseExports = javaBaseModule.getDescriptor().exports(); + Set javaSqlExports = javaSqlModule.getDescriptor().exports(); + + Set javaSqlExportsSource = javaSqlExports.stream() + .map(Exports::source) + .collect(Collectors.toSet()); + + assertThat(javaBaseExports.size(), is(108)); + assertThat(javaSqlExports.size(), is(3)); + assertThat(javaSqlExportsSource, containsInAnyOrder("java.sql", "javax.transaction.xa", "javax.sql")); + } + + @Test + public void givenModules_whenAccessingModuleDescriptorUses_thenUsesAreReturned() { + Set javaBaseUses = javaBaseModule.getDescriptor().uses(); + Set javaSqlUses = javaSqlModule.getDescriptor().uses(); + + assertThat(javaBaseUses.size(), is(34)); + assertThat(javaSqlUses, contains("java.sql.Driver")); + } + + @Test + public void givenModules_whenAccessingModuleDescriptorOpen_thenOpenAreReturned() { + Set javaBaseUses = javaBaseModule.getDescriptor().opens(); + Set javaSqlUses = javaSqlModule.getDescriptor().opens(); + + assertThat(javaBaseUses, empty()); + assertThat(javaSqlUses, empty()); + } + + @Test + public void whenAddingReadsToAModule_thenModuleCanReadNewModule() { + Module updatedModule = module.addReads(javaSqlModule); + + assertTrue(updatedModule.canRead(javaSqlModule)); + } + + @Test + public void whenExportingPackage_thenPackageIsExported() { + Module updatedModule = module.addExports("com.baeldung.java9.modules", javaSqlModule); + + assertTrue(updatedModule.isExported("com.baeldung.java9.modules")); + } + + @Test + public void whenOpeningAModulePackage_thenPackagedIsOpened() { + Module updatedModule = module.addOpens("com.baeldung.java9.modules", javaSqlModule); + + assertTrue(updatedModule.isOpen("com.baeldung.java9.modules", javaSqlModule)); + } + + @Test + public void whenAddingUsesToModule_thenUsesIsAdded() { + Module updatedModule = module.addUses(Driver.class); + + assertTrue(updatedModule.canUse(Driver.class)); + } + + private class Person { + private String name; + + public Person(String name) { + this.name = name; + } + + public String getName() { + return name; + } + } +} diff --git a/core-java-9/src/test/java/com/baeldung/optionals/OptionalsTest.java b/core-java-9/src/test/java/com/baeldung/optionals/OptionalsTest.java new file mode 100644 index 0000000000..4e5f94c0db --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/optionals/OptionalsTest.java @@ -0,0 +1,51 @@ +package com.baeldung.optionals; + +import static org.junit.Assert.assertEquals; + +import java.util.Optional; + +import org.junit.Test; + +public class OptionalsTest { + + @Test + public void givenOptional_whenEmptyValue_thenCustomMessage() { + assertEquals(Optional.of("Name not provided"), Optionals.getName(Optional.ofNullable(null))); + } + + @Test + public void givenOptional_whenValue_thenOptional() { + String name = "Filan Fisteku"; + Optional optionalString = Optional.ofNullable(name); + assertEquals(optionalString, Optionals.getName(optionalString)); + } + + @Test + public void givenOptional_whenValue_thenOptionalGeneralMethod() { + String name = "Filan Fisteku"; + String missingOptional = "Name not provided"; + Optional optionalString = Optional.ofNullable(name); + Optional fallbackOptionalString = Optional.ofNullable(missingOptional); + assertEquals(optionalString, Optionals.or(optionalString, fallbackOptionalString)); + } + + @Test + public void givenEmptyOptional_whenValue_thenOptionalGeneralMethod() { + String missingOptional = "Name not provided"; + Optional optionalString = Optional.empty(); + Optional fallbackOptionalString = Optional.ofNullable(missingOptional); + assertEquals(fallbackOptionalString, Optionals.or(optionalString, fallbackOptionalString)); + } + + @Test + public void givenGuavaOptional_whenInvoke_thenOptional() { + String name = "Filan Fisteku"; + com.google.common.base.Optional stringOptional = com.google.common.base.Optional.of(name); + assertEquals(stringOptional, Optionals.getOptionalGuavaName(stringOptional)); + } + + @Test + public void givenGuavaOptional_whenNull_thenDefaultText() { + assertEquals(com.google.common.base.Optional.of("Name not provided"), Optionals.getOptionalGuavaName(com.google.common.base.Optional.fromNullable(null))); + } +} \ No newline at end of file diff --git a/core-java-collections/README.md b/core-java-collections/README.md index ba264d7b6a..510eac9dbc 100644 --- a/core-java-collections/README.md +++ b/core-java-collections/README.md @@ -29,3 +29,4 @@ - [Java TreeMap vs HashMap](http://www.baeldung.com/java-treemap-vs-hashmap) - [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list) - [How to Store Duplicate Keys in a Map in Java?](http://www.baeldung.com/java-map-duplicate-keys) +- [Getting the Size of an Iterable in Java](http://www.baeldung.com/java-iterable-size) diff --git a/core-java-collections/src/test/java/com/baeldung/array/converter/ArrayConvertToListTest.java b/core-java-collections/src/test/java/com/baeldung/array/converter/ArrayConvertToListUnitTest.java similarity index 98% rename from core-java-collections/src/test/java/com/baeldung/array/converter/ArrayConvertToListTest.java rename to core-java-collections/src/test/java/com/baeldung/array/converter/ArrayConvertToListUnitTest.java index a5db46a9b6..cf8710d8a4 100644 --- a/core-java-collections/src/test/java/com/baeldung/array/converter/ArrayConvertToListTest.java +++ b/core-java-collections/src/test/java/com/baeldung/array/converter/ArrayConvertToListUnitTest.java @@ -8,7 +8,7 @@ import java.util.List; import static org.junit.Assert.*; -public class ArrayConvertToListTest { +public class ArrayConvertToListUnitTest { @Test public void givenAnStringArray_whenConvertArrayToList_thenListCreated() { diff --git a/core-java-collections/src/test/java/com/baeldung/arraydeque/ArrayDequeTest.java b/core-java-collections/src/test/java/com/baeldung/arraydeque/ArrayDequeUnitTest.java similarity index 92% rename from core-java-collections/src/test/java/com/baeldung/arraydeque/ArrayDequeTest.java rename to core-java-collections/src/test/java/com/baeldung/arraydeque/ArrayDequeUnitTest.java index 50813a8601..71930eda97 100644 --- a/core-java-collections/src/test/java/com/baeldung/arraydeque/ArrayDequeTest.java +++ b/core-java-collections/src/test/java/com/baeldung/arraydeque/ArrayDequeUnitTest.java @@ -6,7 +6,7 @@ import java.util.Deque; import static org.junit.Assert.*; import org.junit.Test; -public class ArrayDequeTest { +public class ArrayDequeUnitTest { @Test public void whenOffer_addsAtLast() { diff --git a/core-java-collections/src/test/java/com/baeldung/java/iterable/IterableSizeTest.java b/core-java-collections/src/test/java/com/baeldung/java/iterable/IterableSizeUnitTest.java similarity index 97% rename from core-java-collections/src/test/java/com/baeldung/java/iterable/IterableSizeTest.java rename to core-java-collections/src/test/java/com/baeldung/java/iterable/IterableSizeUnitTest.java index d73e3a0eb5..4bc413dee0 100644 --- a/core-java-collections/src/test/java/com/baeldung/java/iterable/IterableSizeTest.java +++ b/core-java-collections/src/test/java/com/baeldung/java/iterable/IterableSizeUnitTest.java @@ -9,7 +9,7 @@ import org.junit.jupiter.api.Test; import com.google.common.collect.Lists; -class IterableSizeTest { +class IterableSizeUnitTest { private final List list = Lists.newArrayList("Apple", "Orange", "Banana"); diff --git a/core-java-collections/src/test/java/com/baeldung/java/map/MapMultipleValuesTest.java b/core-java-collections/src/test/java/com/baeldung/java/map/MapMultipleValuesUnitTest.java similarity index 98% rename from core-java-collections/src/test/java/com/baeldung/java/map/MapMultipleValuesTest.java rename to core-java-collections/src/test/java/com/baeldung/java/map/MapMultipleValuesUnitTest.java index 88f97f6c19..3a0affa6f3 100644 --- a/core-java-collections/src/test/java/com/baeldung/java/map/MapMultipleValuesTest.java +++ b/core-java-collections/src/test/java/com/baeldung/java/map/MapMultipleValuesUnitTest.java @@ -23,8 +23,8 @@ import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.TreeMultimap; -public class MapMultipleValuesTest { - private static final Logger LOG = LoggerFactory.getLogger(MapMultipleValuesTest.class); +public class MapMultipleValuesUnitTest { + private static final Logger LOG = LoggerFactory.getLogger(MapMultipleValuesUnitTest.class); @Test public void givenHashMap_whenPuttingTwice_thenReturningFirstValue() { diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java similarity index 93% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java index e9b2e164ae..4eead471f8 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java @@ -9,7 +9,7 @@ import java.util.stream.IntStream; import org.junit.Test; -public class ThreadSafeCounterTest { +public class ThreadSafeCounterIntegrationTest { @Test public void givenMultiThread_whenSafeCounterWithLockIncrement() throws InterruptedException { diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadUnitTest.java similarity index 95% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadUnitTest.java index 3ca69d8847..2d8b91d846 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/daemon/DaemonThreadUnitTest.java @@ -6,7 +6,7 @@ import static org.junit.Assert.assertTrue; import org.junit.Ignore; import org.junit.Test; -public class DaemonThreadTest { +public class DaemonThreadUnitTest { @Test @Ignore diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockUnitTest.java similarity index 96% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockUnitTest.java index 9c56fa64be..553b8c9906 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSychronizedBlockUnitTest.java @@ -9,7 +9,7 @@ import java.util.stream.IntStream; import static org.junit.Assert.assertEquals; -public class BaeldungSychronizedBlockTest { +public class BaeldungSychronizedBlockUnitTest { @Test public void givenMultiThread_whenBlockSync() throws InterruptedException { diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsUnitTest.java similarity index 97% rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsTest.java rename to core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsUnitTest.java index ba7c1f0a7b..32648729d5 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/synchronize/BaeldungSynchronizeMethodsUnitTest.java @@ -10,7 +10,7 @@ import java.util.stream.IntStream; import static org.junit.Assert.assertEquals; -public class BaeldungSynchronizeMethodsTest { +public class BaeldungSynchronizeMethodsUnitTest { @Test @Ignore diff --git a/core-java-io/README.md b/core-java-io/README.md index 1354854e1f..011282af12 100644 --- a/core-java-io/README.md +++ b/core-java-io/README.md @@ -27,3 +27,4 @@ - [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice) - [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels) - [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel) +- [Download a File From an URL in Java](http://www.baeldung.com/java-download-file) diff --git a/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierTest.java b/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierIntegrationTest.java similarity index 96% rename from core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierTest.java rename to core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierIntegrationTest.java index 6d96d2fc0b..4603644bf5 100644 --- a/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierTest.java +++ b/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierIntegrationTest.java @@ -18,7 +18,7 @@ import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.*; -public class FileCopierTest { +public class FileCopierIntegrationTest { File original = new File("src/test/resources/original.txt"); @Before diff --git a/core-java-io/src/test/java/com/baeldung/file/FilesTest.java b/core-java-io/src/test/java/com/baeldung/file/FilesManualTest.java similarity index 98% rename from core-java-io/src/test/java/com/baeldung/file/FilesTest.java rename to core-java-io/src/test/java/com/baeldung/file/FilesManualTest.java index a35cda8b23..f5c5c3dd3a 100644 --- a/core-java-io/src/test/java/com/baeldung/file/FilesTest.java +++ b/core-java-io/src/test/java/com/baeldung/file/FilesManualTest.java @@ -24,7 +24,7 @@ import org.junit.Test; import com.baeldung.util.StreamUtils; -public class FilesTest { +public class FilesManualTest { public static final String fileName = "src/main/resources/countries.properties"; @@ -77,6 +77,6 @@ public class FilesTest { bw.newLine(); bw.close(); - assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n"); + assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); } } \ No newline at end of file diff --git a/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java index b56841117e..a96232d66c 100644 --- a/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java +++ b/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java @@ -1,6 +1,7 @@ package org.baeldung.java.io; import org.junit.Test; +import org.junit.Ignore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -105,8 +106,9 @@ public class JavaReadFromFileUnitTest { } @Test + @Ignore // TODO public void whenReadUTFEncodedFile_thenCorrect() throws IOException { - final String expected_value = "é�’空"; + final String expected_value = "青空"; final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8")); final String currentLine = reader.readLine(); reader.close(); diff --git a/core-java/README.md b/core-java/README.md index 0dda0d0699..79f7b4169e 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -141,3 +141,18 @@ - [Java KeyStore API](http://www.baeldung.com/java-keystore) - [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking) - [Guide to Java Clock Class](http://www.baeldung.com/java-clock) +- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java) +- [Using Java Assertions](http://www.baeldung.com/java-assert) +- [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference) +- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number) +- [Variable and Method Hiding in Java](http://www.baeldung.com/java-variable-method-hiding) +- [Access Modifiers in Java](http://www.baeldung.com/java-access-modifiers) +- [NaN in Java](http://www.baeldung.com/java-not-a-number) +- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java) +- [Why Use char[] Array Over a String for Storing Passwords in Java?](http://www.baeldung.com/java-storing-passwords) +- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns) +- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns) +- [Singletons in Java](http://www.baeldung.com/java-singleton) +- [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight) +- [The Observer Pattern in Java](http://www.baeldung.com/java-observer-pattern) +- [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern) diff --git a/core-java/pom.xml b/core-java/pom.xml index 88fae5edea..f7a2139d99 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -198,6 +198,11 @@ mail ${javax.mail.version} + + javax.mail + mail + 1.5.0-b01 + diff --git a/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java b/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java index 977587a06a..f35064b783 100644 --- a/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java +++ b/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java @@ -9,7 +9,7 @@ public class ArrayBenchmarkRunner { public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() - .include(SearchArrayTest.class.getSimpleName()).threads(1) + .include(SearchArrayUnitTest.class.getSimpleName()).threads(1) .forks(1).shouldFailOnError(true).shouldDoGC(true) .jvmArgs("-server").build(); diff --git a/core-java/src/main/java/com/baeldung/array/JaggedArray.java b/core-java/src/main/java/com/baeldung/array/JaggedArray.java new file mode 100644 index 0000000000..36cfc88b95 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/array/JaggedArray.java @@ -0,0 +1,49 @@ +package com.baeldung.array; + +import java.util.Arrays; +import java.util.Scanner; + +public class JaggedArray { + + int[][] shortHandFormInitialization() { + int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + return jaggedArr; + } + + int[][] declarationAndThenInitialization() { + int[][] jaggedArr = new int[3][]; + jaggedArr[0] = new int[] { 1, 2 }; + jaggedArr[1] = new int[] { 3, 4, 5 }; + jaggedArr[2] = new int[] { 6, 7, 8, 9 }; + return jaggedArr; + } + + int[][] declarationAndThenInitializationUsingUserInputs() { + int[][] jaggedArr = new int[3][]; + jaggedArr[0] = new int[2]; + jaggedArr[1] = new int[3]; + jaggedArr[2] = new int[4]; + initializeElements(jaggedArr); + return jaggedArr; + } + + void initializeElements(int[][] jaggedArr) { + Scanner sc = new Scanner(System.in); + for (int outer = 0; outer < jaggedArr.length; outer++) { + for (int inner = 0; inner < jaggedArr[outer].length; inner++) { + jaggedArr[outer][inner] = sc.nextInt(); + } + } + } + + void printElements(int[][] jaggedArr) { + for (int index = 0; index < jaggedArr.length; index++) { + System.out.println(Arrays.toString(jaggedArr[index])); + } + } + + int[] getElementAtGivenIndex(int[][] jaggedArr, int index) { + return jaggedArr[index]; + } + +} diff --git a/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java b/core-java/src/main/java/com/baeldung/array/SearchArrayUnitTest.java similarity index 98% rename from core-java/src/main/java/com/baeldung/array/SearchArrayTest.java rename to core-java/src/main/java/com/baeldung/array/SearchArrayUnitTest.java index 199ebdf036..bed58356cb 100644 --- a/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java +++ b/core-java/src/main/java/com/baeldung/array/SearchArrayUnitTest.java @@ -8,7 +8,7 @@ import java.util.concurrent.TimeUnit; @BenchmarkMode(Mode.AverageTime) @Warmup(iterations = 5) @OutputTimeUnit(TimeUnit.MICROSECONDS) -public class SearchArrayTest { +public class SearchArrayUnitTest { @State(Scope.Benchmark) public static class SearchData { diff --git a/core-java/src/main/java/com/baeldung/keyword/KeywordDemo.java b/core-java/src/main/java/com/baeldung/keyword/KeywordDemo.java new file mode 100644 index 0000000000..fd608b424c --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keyword/KeywordDemo.java @@ -0,0 +1,16 @@ +package com.baeldung.keyword; + +import com.baeldung.keyword.superkeyword.SuperSub; +import com.baeldung.keyword.thiskeyword.KeywordUnitTest; + +/** + * Created by Gebruiker on 5/14/2018. + */ +public class KeywordDemo { + + public static void main(String[] args) { + KeywordUnitTest keyword = new KeywordUnitTest(); + + SuperSub child = new SuperSub("message from the child class"); + } +} diff --git a/core-java/src/main/java/com/baeldung/keyword/superkeyword/SuperBase.java b/core-java/src/main/java/com/baeldung/keyword/superkeyword/SuperBase.java new file mode 100644 index 0000000000..a5304fcef9 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keyword/superkeyword/SuperBase.java @@ -0,0 +1,20 @@ +package com.baeldung.keyword.superkeyword; + +/** + * Created by Gebruiker on 5/14/2018. + */ +public class SuperBase { + + String message = "super class"; + + public SuperBase() { + } + + public SuperBase(String message) { + this.message = message; + } + + public void printMessage() { + System.out.println(message); + } +} diff --git a/core-java/src/main/java/com/baeldung/keyword/superkeyword/SuperSub.java b/core-java/src/main/java/com/baeldung/keyword/superkeyword/SuperSub.java new file mode 100644 index 0000000000..83bc04ad0f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keyword/superkeyword/SuperSub.java @@ -0,0 +1,26 @@ +package com.baeldung.keyword.superkeyword; + +/** + * Created by Gebruiker on 5/15/2018. + */ +public class SuperSub extends SuperBase { + + String message = "child class"; + + public SuperSub(String message) { + super(message); + } + + public SuperSub() { + super.printMessage(); + printMessage(); + } + + public void getParentMessage() { + System.out.println(super.message); + } + + public void printMessage() { + System.out.println(message); + } +} diff --git a/core-java/src/main/java/com/baeldung/keyword/thiskeyword/KeywordUnitTest.java b/core-java/src/main/java/com/baeldung/keyword/thiskeyword/KeywordUnitTest.java new file mode 100644 index 0000000000..35fd7358af --- /dev/null +++ b/core-java/src/main/java/com/baeldung/keyword/thiskeyword/KeywordUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.keyword.thiskeyword; + +public class KeywordUnitTest { + + private String name; + private int age; + + public KeywordUnitTest() { + this("John", 27); + this.printMessage(); + printInstance(this); + } + + public KeywordUnitTest(String name, int age) { + this.name = name; + this.age = age; + } + + public void printMessage() { + System.out.println("invoked by this"); + } + + public void printInstance(KeywordUnitTest thisKeyword) { + System.out.println(thisKeyword); + } + + public KeywordUnitTest getCurrentInstance() { + return this; + } + + class ThisInnerClass { + + boolean isInnerClass = true; + + public ThisInnerClass() { + KeywordUnitTest thisKeyword = KeywordUnitTest.this; + String outerString = KeywordUnitTest.this.name; + System.out.println(this.isInnerClass); + } + } + + @Override + public String toString() { + return "KeywordTest{" + + "name='" + name + '\'' + + ", age=" + age + + '}'; + } +} diff --git a/core-java/src/main/java/com/baeldung/linkedlist/MiddleElementLookup.java b/core-java/src/main/java/com/baeldung/linkedlist/MiddleElementLookup.java new file mode 100644 index 0000000000..4cfa0d411b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/linkedlist/MiddleElementLookup.java @@ -0,0 +1,90 @@ +package com.baeldung.linkedlist; + +import java.util.LinkedList; +import java.util.Optional; + +import com.baeldung.linkedlist.Node; + +public class MiddleElementLookup { + + public static Optional findMiddleElementLinkedList(LinkedList linkedList) { + if (linkedList == null || linkedList.isEmpty()) { + return Optional.empty(); + } + + return Optional.ofNullable(linkedList.get((linkedList.size() - 1) / 2)); + } + + public static Optional findMiddleElementFromHead(Node head) { + if (head == null) { + return Optional.empty(); + } + + // calculate the size of the list + Node current = head; + int size = 1; + while (current.hasNext()) { + current = current.next(); + size++; + } + + // iterate till the middle element + current = head; + for (int i = 0; i < (size - 1) / 2; i++) { + current = current.next(); + } + + return Optional.ofNullable(current.data()); + } + + public static Optional findMiddleElementFromHead1PassRecursively(Node head) { + if (head == null) { + return Optional.empty(); + } + + MiddleAuxRecursion middleAux = new MiddleAuxRecursion(); + findMiddleRecursively(head, middleAux); + return Optional.ofNullable(middleAux.middle.data()); + } + + private static void findMiddleRecursively(Node node, MiddleAuxRecursion middleAux) { + if (node == null) { + // reached the end + middleAux.length = middleAux.length / 2; + return; + } + middleAux.length++; + findMiddleRecursively(node.next(), middleAux); + + if (middleAux.length == 0) { + // found the middle + middleAux.middle = node; + } + + middleAux.length--; + } + + public static Optional findMiddleElementFromHead1PassIteratively(Node head) { + if (head == null) { + return Optional.empty(); + } + + Node slowPointer = head; + Node fastPointer = head; + + while (fastPointer.hasNext() && fastPointer.next() + .hasNext()) { + fastPointer = fastPointer.next() + .next(); + slowPointer = slowPointer.next(); + } + + return Optional.ofNullable(slowPointer.data()); + } + + private static class MiddleAuxRecursion { + Node middle; + int length = 0; + } + +} diff --git a/core-java/src/main/java/com/baeldung/linkedlist/Node.java b/core-java/src/main/java/com/baeldung/linkedlist/Node.java new file mode 100644 index 0000000000..daceaffdcd --- /dev/null +++ b/core-java/src/main/java/com/baeldung/linkedlist/Node.java @@ -0,0 +1,34 @@ +package com.baeldung.linkedlist; + +public class Node { + private Node next; + private String data; + + public Node(String data) { + this.data = data; + } + + public String data() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public boolean hasNext() { + return next != null; + } + + public Node next() { + return next; + } + + public void setNext(Node next) { + this.next = next; + } + + public String toString() { + return this.data; + } +} diff --git a/core-java/src/test/java/com/baeldung/array/ArrayInitializerTest.java b/core-java/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/array/ArrayInitializerTest.java rename to core-java/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java index 7265fa20e5..5e764da174 100644 --- a/core-java/src/test/java/com/baeldung/array/ArrayInitializerTest.java +++ b/core-java/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java @@ -15,7 +15,7 @@ import static org.junit.Assert.assertArrayEquals; import org.junit.Test; -public class ArrayInitializerTest { +public class ArrayInitializerUnitTest { @Test public void whenInitializeArrayInLoop_thenCorrect() { diff --git a/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java b/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayUnitTest.java similarity index 90% rename from core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java rename to core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayUnitTest.java index ec916af092..4493f3fbf5 100644 --- a/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java +++ b/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.array; import org.junit.Assert; import org.junit.Test; -public class Find2ndLargestInArrayTest { +public class Find2ndLargestInArrayUnitTest { @Test public void givenAnIntArray_thenFind2ndLargestElement() { int[] array = { 1, 3, 24, 16, 87, 20 }; diff --git a/core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java b/core-java/src/test/java/com/baeldung/array/FindElementInArrayUnitTest.java similarity index 96% rename from core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java rename to core-java/src/test/java/com/baeldung/array/FindElementInArrayUnitTest.java index ba9188fa7b..887f50ebcc 100644 --- a/core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java +++ b/core-java/src/test/java/com/baeldung/array/FindElementInArrayUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.array; import org.junit.Assert; import org.junit.Test; -public class FindElementInArrayTest { +public class FindElementInArrayUnitTest { @Test public void givenAnIntArray_whenNotUsingStream_thenFindAnElement() { int[] array = { 1, 3, 4, 8, 19, 20 }; diff --git a/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java b/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java new file mode 100644 index 0000000000..a4dd7e25c3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.array; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.PrintStream; + +import org.junit.Test; + +public class JaggedArrayUnitTest { + + private JaggedArray obj = new JaggedArray(); + + @Test + public void whenInitializedUsingShortHandForm_thenCorrect() { + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.shortHandFormInitialization()); + } + + @Test + public void whenInitializedWithDeclarationAndThenInitalization_thenCorrect() { + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitialization()); + } + + @Test + public void whenInitializedWithDeclarationAndThenInitalizationUsingUserInputs_thenCorrect() { + InputStream is = new ByteArrayInputStream("1 2 3 4 5 6 7 8 9".getBytes()); + System.setIn(is); + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitializationUsingUserInputs()); + System.setIn(System.in); + } + + @Test + public void givenJaggedArrayAndAnIndex_thenReturnArrayAtGivenIndex() { + int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + assertArrayEquals(new int[] { 1, 2 }, obj.getElementAtGivenIndex(jaggedArr, 0)); + assertArrayEquals(new int[] { 3, 4, 5 }, obj.getElementAtGivenIndex(jaggedArr, 1)); + assertArrayEquals(new int[] { 6, 7, 8, 9 }, obj.getElementAtGivenIndex(jaggedArr, 2)); + } + + @Test + public void givenJaggedArray_whenUsingArraysAPI_thenVerifyPrintedElements() { + int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outContent)); + obj.printElements(jaggedArr); + assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", "")); + System.setOut(System.out); + } + +} diff --git a/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java b/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java rename to core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java index 208075cb57..0f38316ce3 100644 --- a/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java +++ b/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.array; import org.junit.Assert; import org.junit.Test; -public class SumAndAverageInArrayTest { +public class SumAndAverageInArrayUnitTest { @Test public void givenAnIntArray_whenNotUsingStream_thenFindSum() { int[] array = { 1, 3, 4, 8, 19, 20 }; diff --git a/core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java b/core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java new file mode 100644 index 0000000000..9e6d3d6131 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java @@ -0,0 +1,153 @@ +package com.baeldung.arrays; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Stream; + +public class ArraysUnitTest { + private String[] intro; + + @Rule + public final ExpectedException exception = ExpectedException.none(); + + @Before + public void setup() { + intro = new String[] { "once", "upon", "a", "time" }; + } + + @Test + public void whenCopyOfRange_thenAbridgedArray() { + String[] abridgement = Arrays.copyOfRange(intro, 0, 3); + + assertArrayEquals(new String[] { "once", "upon", "a" }, abridgement); + assertFalse(Arrays.equals(intro, abridgement)); + } + + @Test + public void whenCopyOf_thenNullElement() { + String[] revised = Arrays.copyOf(intro, 3); + String[] expanded = Arrays.copyOf(intro, 5); + + assertArrayEquals(Arrays.copyOfRange(intro, 0, 3), revised); + assertNull(expanded[4]); + } + + @Test + public void whenFill_thenAllMatch() { + String[] stutter = new String[3]; + Arrays.fill(stutter, "once"); + + assertTrue(Stream.of(stutter).allMatch(el -> "once".equals(el))); + } + + @Test + public void whenEqualsContent_thenMatch() { + assertTrue(Arrays.equals(new String[] { "once", "upon", "a", "time" }, intro)); + assertFalse(Arrays.equals(new String[] { "once", "upon", "a", null }, intro)); + } + + @Test + public void whenNestedArrays_thenDeepEqualsPass() { + String[] end = { "the", "end" }; + Object[] story = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end }; + Object[] copy = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end }; + + assertTrue(Arrays.deepEquals(story, copy)); + assertFalse(Arrays.equals(story, copy)); + } + + @Test + public void whenSort_thenArraySorted() { + String[] sorted = Arrays.copyOf(intro, 4); + Arrays.sort(sorted); + + assertArrayEquals(new String[] { "a", "once", "time", "upon" }, sorted); + } + + @Test + public void whenBinarySearch_thenFindElements() { + String[] sorted = Arrays.copyOf(intro, 4); + Arrays.sort(sorted); + int exact = Arrays.binarySearch(sorted, "time"); + int caseInsensitive = Arrays.binarySearch(sorted, "TiMe", String::compareToIgnoreCase); + + assertEquals("time", sorted[exact]); + assertEquals(2, exact); + assertEquals(exact, caseInsensitive); + } + + @Test + public void whenNullElement_thenArraysHashCodeNotEqual() { + int beforeChange = Arrays.hashCode(intro); + int before = intro.hashCode(); + intro[3] = null; + int after = intro.hashCode(); + int afterChange = Arrays.hashCode(intro); + + assertNotEquals(beforeChange, afterChange); + assertEquals(before, after); + } + + @Test + public void whenNestedArrayNullElement_thenEqualsFailDeepHashPass() { + Object[] looping = new Object[] { intro, intro }; + int deepHashBefore = Arrays.deepHashCode(looping); + int hashBefore = Arrays.hashCode(looping); + + intro[3] = null; + + int hashAfter = Arrays.hashCode(looping); + int deepHashAfter = Arrays.deepHashCode(looping); + + assertEquals(hashAfter, hashBefore); + assertNotEquals(deepHashAfter, deepHashBefore); + } + + @Test + public void whenStreamBadIndex_thenException() { + assertEquals(Arrays.stream(intro).count(), 4); + + exception.expect(ArrayIndexOutOfBoundsException.class); + Arrays.stream(intro, 2, 1).count(); + } + + @Test + public void whenSetAllToUpper_thenAppliedToAllElements() { + String[] longAgo = new String[4]; + Arrays.setAll(longAgo, i -> intro[i].toUpperCase()); + + assertArrayEquals(longAgo, new String[] { "ONCE", "UPON", "A", "TIME" }); + } + + @Test + public void whenToString_thenFormattedArrayString() { + assertEquals("[once, upon, a, time]", Arrays.toString(intro)); + } + + @Test + public void whenNestedArrayDeepString_thenFormattedArraysString() { + String[] end = { "the", "end" }; + Object[] story = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end }; + + assertEquals("[[once, upon, a, time], [chapter one, chapter two], [the, end]]", Arrays.deepToString(story)); + } + + @Test + public void whenAsList_thenImmutableArray() { + List rets = Arrays.asList(intro); + + assertTrue(rets.contains("upon")); + assertTrue(rets.contains("time")); + assertEquals(rets.size(), 4); + + exception.expect(UnsupportedOperationException.class); + rets.add("the"); + } +} diff --git a/core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java b/core-java/src/test/java/com/baeldung/asciiart/AsciiArtIntegrationTest.java similarity index 92% rename from core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java rename to core-java/src/test/java/com/baeldung/asciiart/AsciiArtIntegrationTest.java index 103681894e..8ab1695395 100644 --- a/core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java +++ b/core-java/src/test/java/com/baeldung/asciiart/AsciiArtIntegrationTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import com.baeldung.asciiart.AsciiArt.Settings; -public class AsciiArtTest { +public class AsciiArtIntegrationTest { @Test public void givenTextWithAsciiCharacterAndSettings_shouldPrintAsciiArt() { diff --git a/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueTest.java b/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueUnitTest.java similarity index 96% rename from core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueTest.java rename to core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueUnitTest.java index 1980497cd3..2a2f3be2a9 100644 --- a/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueTest.java +++ b/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueUnitTest.java @@ -9,7 +9,7 @@ import static org.junit.Assert.assertEquals; import org.junit.Test; -public class BreakContinueTest { +public class BreakContinueUnitTest { @Test public void whenUnlabeledBreak_ThenEqual() { diff --git a/core-java/src/test/java/com/baeldung/casting/CastingTest.java b/core-java/src/test/java/com/baeldung/casting/CastingUnitTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/casting/CastingTest.java rename to core-java/src/test/java/com/baeldung/casting/CastingUnitTest.java index dd95e0dd80..41eaa5dc1b 100644 --- a/core-java/src/test/java/com/baeldung/casting/CastingTest.java +++ b/core-java/src/test/java/com/baeldung/casting/CastingUnitTest.java @@ -5,7 +5,7 @@ import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; -public class CastingTest { +public class CastingUnitTest { @Test public void whenPrimitiveConverted_thenValueChanged() { diff --git a/core-java/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java b/core-java/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java index d28ad3a54c..d1cfe7df19 100644 --- a/core-java/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java +++ b/core-java/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java @@ -34,6 +34,19 @@ public class PasswordStoreExamplesUnitTest { assertThat(stringPassword).isEqualTo("password"); } + @Test + public void givenStringHashCode_WhenStringValueReplaced_ThenHashCodesEqualAndValesEqual() { + String originalHashCode = Integer.toHexString(stringPassword.hashCode()); + + String newString = "********"; + stringPassword.replace(stringPassword, newString); + + String hashCodeAfterReplace = Integer.toHexString(stringPassword.hashCode()); + + assertThat(originalHashCode).isEqualTo(hashCodeAfterReplace); + assertThat(stringPassword).isEqualTo("password"); + } + @Test public void givenCharArrayHashCode_WhenArrayElementsValueChanged_ThenHashCodesEqualAndValesNotEqual() { String originalHashCode = Integer.toHexString(charPassword.hashCode()); diff --git a/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderTest.java b/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java similarity index 93% rename from core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderTest.java rename to core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java index 9f3c751805..ec35885b84 100644 --- a/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderTest.java +++ b/core-java/src/test/java/com/baeldung/classloader/CustomClassLoaderUnitTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -public class CustomClassLoaderTest { +public class CustomClassLoaderUnitTest { @Test public void customLoader() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { diff --git a/core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderTest.java b/core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderUnitTest.java similarity index 93% rename from core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderTest.java rename to core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderUnitTest.java index f44a5cef09..f0d69f4326 100644 --- a/core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderTest.java +++ b/core-java/src/test/java/com/baeldung/classloader/PrintClassLoaderUnitTest.java @@ -4,7 +4,7 @@ import org.junit.Test; import static org.junit.Assert.*; -public class PrintClassLoaderTest { +public class PrintClassLoaderUnitTest { @Test(expected = ClassNotFoundException.class) public void givenAppClassLoader_whenParentClassLoader_thenClassNotFoundException() throws Exception { PrintClassLoader sampleClassLoader = (PrintClassLoader) Class.forName(PrintClassLoader.class.getName()).newInstance(); diff --git a/core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionTest.java b/core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionUnitTest.java similarity index 84% rename from core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionTest.java rename to core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionUnitTest.java index 8714d084ab..b076b0324a 100644 --- a/core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionTest.java +++ b/core-java/src/test/java/com/baeldung/classnotfoundexception/ClassNotFoundExceptionUnitTest.java @@ -2,7 +2,7 @@ package com.baeldung.classnotfoundexception; import org.junit.Test; -public class ClassNotFoundExceptionTest { +public class ClassNotFoundExceptionUnitTest { @Test(expected = ClassNotFoundException.class) public void givenNoDriversInClassPath_whenLoadDrivers_thenClassNotFoundException() throws ClassNotFoundException { diff --git a/core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesTest.java b/core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesUnitTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesTest.java rename to core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesUnitTest.java index 8acd4e023e..6c3393c254 100644 --- a/core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesTest.java +++ b/core-java/src/test/java/com/baeldung/decimalformat/DecimalFormatExamplesUnitTest.java @@ -11,7 +11,7 @@ import java.util.Locale; import org.junit.Test; -public class DecimalFormatExamplesTest { +public class DecimalFormatExamplesUnitTest { double d = 1234567.89; diff --git a/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesTest.java b/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesTest.java rename to core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java index 8fec58f111..77b38419a9 100644 --- a/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesTest.java +++ b/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeExamplesUnitTest.java @@ -13,7 +13,7 @@ import java.util.TimeZone; import org.junit.Ignore; import org.junit.Test; -public class DaylightSavingTimeExamplesTest { +public class DaylightSavingTimeExamplesUnitTest { @Test public void givenItalianTimeZone_WhenDSTHappens_ThenCorrectlyShiftTimeZone() throws ParseException { diff --git a/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesTest.java b/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesTest.java rename to core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java index 78847033ac..07ab859e09 100644 --- a/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesTest.java +++ b/core-java/src/test/java/com/baeldung/dst/DaylightSavingTimeJavaTimeExamplesUnitTest.java @@ -11,7 +11,7 @@ import java.util.TimeZone; import org.junit.Test; -public class DaylightSavingTimeJavaTimeExamplesTest { +public class DaylightSavingTimeJavaTimeExamplesUnitTest { @Test public void givenItalianTimeZone_WhenDSTHappens_ThenCorrectlyShiftTimeZone() throws ParseException { diff --git a/core-java/src/test/java/com/baeldung/extension/ExtensionTest.java b/core-java/src/test/java/com/baeldung/extension/ExtensionUnitTest.java similarity index 96% rename from core-java/src/test/java/com/baeldung/extension/ExtensionTest.java rename to core-java/src/test/java/com/baeldung/extension/ExtensionUnitTest.java index 97e9436b90..8c6e261c91 100644 --- a/core-java/src/test/java/com/baeldung/extension/ExtensionTest.java +++ b/core-java/src/test/java/com/baeldung/extension/ExtensionUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.extension; import org.junit.Assert; import org.junit.Test; -public class ExtensionTest { +public class ExtensionUnitTest { private Extension extension = new Extension(); @Test diff --git a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java rename to core-java/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.java index 60950fae7a..49857f355a 100644 --- a/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationTest.java +++ b/core-java/src/test/java/com/baeldung/hashcode/application/ApplicationUnitTest.java @@ -8,7 +8,7 @@ import java.util.Map; import static org.junit.Assert.assertTrue; -public class ApplicationTest { +public class ApplicationUnitTest { @Test public void main_NoInputState_TextPrintedToConsole() throws Exception { diff --git a/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java b/core-java/src/test/java/com/baeldung/hashcode/entities/UserUnitTest.java similarity index 96% rename from core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java rename to core-java/src/test/java/com/baeldung/hashcode/entities/UserUnitTest.java index e356b4beef..44ea7efed1 100644 --- a/core-java/src/test/java/com/baeldung/hashcode/entities/UserTest.java +++ b/core-java/src/test/java/com/baeldung/hashcode/entities/UserUnitTest.java @@ -5,7 +5,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class UserTest { +public class UserUnitTest { private User user; private User comparisonUser; diff --git a/core-java/src/test/java/com/baeldung/inheritance/AppTest.java b/core-java/src/test/java/com/baeldung/inheritance/AppUnitTest.java similarity index 85% rename from core-java/src/test/java/com/baeldung/inheritance/AppTest.java rename to core-java/src/test/java/com/baeldung/inheritance/AppUnitTest.java index 1235761aba..1c3c2fff35 100644 --- a/core-java/src/test/java/com/baeldung/inheritance/AppTest.java +++ b/core-java/src/test/java/com/baeldung/inheritance/AppUnitTest.java @@ -6,14 +6,14 @@ import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; -public class AppTest extends TestCase { +public class AppUnitTest extends TestCase { - public AppTest(String testName) { + public AppUnitTest(String testName) { super( testName ); } public static Test suite() { - return new TestSuite(AppTest.class); + return new TestSuite(AppUnitTest.class); } @SuppressWarnings("static-access") diff --git a/core-java/src/test/java/com/baeldung/initializationguide/UserTest.java b/core-java/src/test/java/com/baeldung/initializationguide/UserUnitTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/initializationguide/UserTest.java rename to core-java/src/test/java/com/baeldung/initializationguide/UserUnitTest.java index 8d352ba706..f74384e6f7 100644 --- a/core-java/src/test/java/com/baeldung/initializationguide/UserTest.java +++ b/core-java/src/test/java/com/baeldung/initializationguide/UserUnitTest.java @@ -6,7 +6,7 @@ import static org.assertj.core.api.Assertions.*; import java.lang.reflect.InvocationTargetException; -public class UserTest { +public class UserUnitTest { @Test public void givenUserInstance_whenIntializedWithNew_thenInstanceIsNotNull() { diff --git a/core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceTests.java b/core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceUnitTest.java similarity index 93% rename from core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceTests.java rename to core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceUnitTest.java index b19ed76189..65d7c860a8 100644 --- a/core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceTests.java +++ b/core-java/src/test/java/com/baeldung/interfaces/InnerInterfaceUnitTest.java @@ -7,7 +7,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) -public class InnerInterfaceTests { +public class InnerInterfaceUnitTest { @Test public void whenCustomerListJoined_thenReturnsJoinedNames() { Customer.List customerList = new CommaSeparatedCustomers(); diff --git a/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderTest.java b/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderUnitTest.java similarity index 96% rename from core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderTest.java rename to core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderUnitTest.java index 9a231a9a3d..43ebdee688 100644 --- a/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderTest.java +++ b/core-java/src/test/java/com/baeldung/java/currentmethod/CurrentlyExecutedMethodFinderUnitTest.java @@ -7,7 +7,7 @@ import static org.junit.Assert.assertEquals; /** * The class presents various ways of finding the name of currently executed method. */ -public class CurrentlyExecutedMethodFinderTest { +public class CurrentlyExecutedMethodFinderUnitTest { @Test public void givenCurrentThread_whenGetStackTrace_thenFindMethod() { diff --git a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoTest.java b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoLiveTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoTest.java rename to core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoLiveTest.java index c429039e3d..0c312ff613 100644 --- a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoTest.java +++ b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URIDemoLiveTest.java @@ -23,8 +23,8 @@ import org.slf4j.LoggerFactory; import com.baeldung.javanetworking.uriurl.URLDemo; @FixMethodOrder -public class URIDemoTest { - private final Logger log = LoggerFactory.getLogger(URIDemoTest.class); +public class URIDemoLiveTest { + private final Logger log = LoggerFactory.getLogger(URIDemoLiveTest.class); String URISTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484"; // parsed locator static String URISCHEME = "https"; diff --git a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoTest.java b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoLiveTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoTest.java rename to core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoLiveTest.java index 47cbf539a5..15f53ed878 100644 --- a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoTest.java +++ b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/test/URLDemoLiveTest.java @@ -21,8 +21,8 @@ import org.slf4j.LoggerFactory; import com.baeldung.javanetworking.uriurl.URLDemo; @FixMethodOrder -public class URLDemoTest { - private final Logger log = LoggerFactory.getLogger(URLDemoTest.class); +public class URLDemoLiveTest { + private final Logger log = LoggerFactory.getLogger(URLDemoLiveTest.class); static String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484"; // parsed locator static String URLPROTOCOL = "https"; diff --git a/core-java/src/test/java/com/baeldung/jdbc/BatchProcessingTest.java b/core-java/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/jdbc/BatchProcessingTest.java rename to core-java/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java index 90f2ea133f..c905482f55 100644 --- a/core-java/src/test/java/com/baeldung/jdbc/BatchProcessingTest.java +++ b/core-java/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java @@ -15,7 +15,7 @@ import java.sql.PreparedStatement; import java.sql.Statement; @RunWith(MockitoJUnitRunner.class) -public class BatchProcessingTest { +public class BatchProcessingLiveTest { @InjectMocks diff --git a/core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetTest.java b/core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java similarity index 99% rename from core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetTest.java rename to core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java index cb455c213a..ebfb4df102 100644 --- a/core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetTest.java +++ b/core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java @@ -24,7 +24,7 @@ import com.sun.rowset.JdbcRowSetImpl; import com.sun.rowset.JoinRowSetImpl; import com.sun.rowset.WebRowSetImpl; -public class JdbcRowSetTest { +public class JdbcRowSetLiveTest { Statement stmt = null; String username = "sa"; String password = ""; diff --git a/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java b/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteUnitTest.java similarity index 87% rename from core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java rename to core-java/src/test/java/com/baeldung/junit4vstestng/SuiteUnitTest.java index 5095217efc..3e02309636 100644 --- a/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteTest.java +++ b/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteUnitTest.java @@ -5,6 +5,6 @@ import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ RegistrationUnitTest.class, SignInUnitTest.class }) -public class SuiteTest { +public class SuiteUnitTest { } diff --git a/core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreTest.java b/core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreUnitTest.java similarity index 99% rename from core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreTest.java rename to core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreUnitTest.java index ff1d337597..cb2a9f1c49 100644 --- a/core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreTest.java +++ b/core-java/src/test/java/com/baeldung/keystore/JavaKeyStoreUnitTest.java @@ -33,7 +33,7 @@ import java.util.Date; /** * Created by adi on 4/14/18. */ -public class JavaKeyStoreTest { +public class JavaKeyStoreUnitTest { private JavaKeyStore keyStore; diff --git a/core-java/src/test/java/com/baeldung/linkedlist/MiddleElementLookupUnitTest.java b/core-java/src/test/java/com/baeldung/linkedlist/MiddleElementLookupUnitTest.java new file mode 100644 index 0000000000..2801bbfc9e --- /dev/null +++ b/core-java/src/test/java/com/baeldung/linkedlist/MiddleElementLookupUnitTest.java @@ -0,0 +1,116 @@ +package com.baeldung.linkedlist; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.util.LinkedList; + +import org.junit.Test; + +public class MiddleElementLookupUnitTest { + + @Test + public void whenFindingMiddleLinkedList_thenMiddleFound() { + assertEquals("3", MiddleElementLookup + .findMiddleElementLinkedList(createLinkedList(5)) + .get()); + assertEquals("2", MiddleElementLookup + .findMiddleElementLinkedList(createLinkedList(4)) + .get()); + } + + @Test + public void whenFindingMiddleFromHead_thenMiddleFound() { + assertEquals("3", MiddleElementLookup + .findMiddleElementFromHead(createNodesList(5)) + .get()); + assertEquals("2", MiddleElementLookup + .findMiddleElementFromHead(createNodesList(4)) + .get()); + } + + @Test + public void whenFindingMiddleFromHead1PassRecursively_thenMiddleFound() { + assertEquals("3", MiddleElementLookup + .findMiddleElementFromHead1PassRecursively(createNodesList(5)) + .get()); + assertEquals("2", MiddleElementLookup + .findMiddleElementFromHead1PassRecursively(createNodesList(4)) + .get()); + } + + @Test + public void whenFindingMiddleFromHead1PassIteratively_thenMiddleFound() { + assertEquals("3", MiddleElementLookup + .findMiddleElementFromHead1PassIteratively(createNodesList(5)) + .get()); + assertEquals("2", MiddleElementLookup + .findMiddleElementFromHead1PassIteratively(createNodesList(4)) + .get()); + } + + @Test + public void whenListEmptyOrNull_thenMiddleNotFound() { + // null list + assertFalse(MiddleElementLookup + .findMiddleElementLinkedList(null) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead(null) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead1PassIteratively(null) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead1PassRecursively(null) + .isPresent()); + + // empty LinkedList + assertFalse(MiddleElementLookup + .findMiddleElementLinkedList(new LinkedList<>()) + .isPresent()); + + // LinkedList with nulls + LinkedList nullsList = new LinkedList<>(); + nullsList.add(null); + nullsList.add(null); + assertFalse(MiddleElementLookup + .findMiddleElementLinkedList(nullsList) + .isPresent()); + + // nodes with null values + assertFalse(MiddleElementLookup + .findMiddleElementFromHead(new Node(null)) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead1PassIteratively(new Node(null)) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead1PassRecursively(new Node(null)) + .isPresent()); + } + + private static LinkedList createLinkedList(int n) { + LinkedList list = new LinkedList<>(); + + for (int i = 1; i <= n; i++) { + list.add(String.valueOf(i)); + } + + return list; + } + + private static Node createNodesList(int n) { + Node head = new Node("1"); + Node current = head; + + for (int i = 2; i <= n; i++) { + Node newNode = new Node(String.valueOf(i)); + current.setNext(newNode); + current = newNode; + } + + return head; + } + +} diff --git a/core-java/src/test/java/com/baeldung/maths/BigDecimalImplTest.java b/core-java/src/test/java/com/baeldung/maths/BigDecimalImplUnitTest.java similarity index 91% rename from core-java/src/test/java/com/baeldung/maths/BigDecimalImplTest.java rename to core-java/src/test/java/com/baeldung/maths/BigDecimalImplUnitTest.java index 788fbd7047..786e5af312 100644 --- a/core-java/src/test/java/com/baeldung/maths/BigDecimalImplTest.java +++ b/core-java/src/test/java/com/baeldung/maths/BigDecimalImplUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import java.math.BigDecimal; import java.math.RoundingMode; -public class BigDecimalImplTest { +public class BigDecimalImplUnitTest { @Test public void givenBigDecimalNumbers_whenAddedTogether_thenGetExpectedResult() { diff --git a/core-java/src/test/java/com/baeldung/maths/BigIntegerImplTest.java b/core-java/src/test/java/com/baeldung/maths/BigIntegerImplUnitTest.java similarity index 91% rename from core-java/src/test/java/com/baeldung/maths/BigIntegerImplTest.java rename to core-java/src/test/java/com/baeldung/maths/BigIntegerImplUnitTest.java index aa8eaa9909..4c45f69090 100644 --- a/core-java/src/test/java/com/baeldung/maths/BigIntegerImplTest.java +++ b/core-java/src/test/java/com/baeldung/maths/BigIntegerImplUnitTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import java.math.BigInteger; -public class BigIntegerImplTest { +public class BigIntegerImplUnitTest { @Test public void givenBigIntegerNumbers_whenAddedTogether_thenGetExpectedResult() { diff --git a/core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticTest.java b/core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticUnitTest.java similarity index 93% rename from core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticTest.java rename to core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticUnitTest.java index 2066f13c6d..6812a8f588 100644 --- a/core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticTest.java +++ b/core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticUnitTest.java @@ -5,7 +5,7 @@ import java.math.BigDecimal; import org.junit.Assert; import org.junit.Test; -public class FloatingPointArithmeticTest { +public class FloatingPointArithmeticUnitTest { @Test public void givenDecimalNumbers_whenAddedTogether_thenGetExpectedResult() { diff --git a/core-java/src/test/java/com/baeldung/maths/RoundTest.java b/core-java/src/test/java/com/baeldung/maths/RoundUnitTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/maths/RoundTest.java rename to core-java/src/test/java/com/baeldung/maths/RoundUnitTest.java index 5ce9523e21..f3c8e6e97a 100644 --- a/core-java/src/test/java/com/baeldung/maths/RoundTest.java +++ b/core-java/src/test/java/com/baeldung/maths/RoundUnitTest.java @@ -8,7 +8,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; -public class RoundTest { +public class RoundUnitTest { private double value = 2.03456d; private int places = 2; private double delta = 0.0d; diff --git a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java index fe2747bcee..04d2886a82 100644 --- a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java +++ b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java @@ -179,7 +179,7 @@ public class JavaMoneyUnitManualTest { MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder .of(Locale.US) .set(CurrencyStyle.NAME) - .set("pattern", "00000.00 �") + .set("pattern", "00000.00 US Dollar") .build()); String customFormatted = customFormat.format(oneDollar); diff --git a/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorTest.java b/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorUnitTest.java similarity index 85% rename from core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorTest.java rename to core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorUnitTest.java index aa11aaa788..ccc8c1f69c 100644 --- a/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorTest.java +++ b/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorUnitTest.java @@ -2,7 +2,7 @@ package com.baeldung.noclassdeffounderror; import org.junit.Test; -public class NoClassDefFoundErrorTest { +public class NoClassDefFoundErrorUnitTest { @Test(expected = NoClassDefFoundError.class) public void givenInitErrorInClass_whenloadClass_thenNoClassDefFoundError() { diff --git a/core-java/src/test/java/com/baeldung/recursion/RecursionExampleTest.java b/core-java/src/test/java/com/baeldung/recursion/RecursionExampleUnitTest.java similarity index 94% rename from core-java/src/test/java/com/baeldung/recursion/RecursionExampleTest.java rename to core-java/src/test/java/com/baeldung/recursion/RecursionExampleUnitTest.java index c65be24240..6c560c9c37 100644 --- a/core-java/src/test/java/com/baeldung/recursion/RecursionExampleTest.java +++ b/core-java/src/test/java/com/baeldung/recursion/RecursionExampleUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.recursion; import org.junit.Assert; import org.junit.Test; -public class RecursionExampleTest { +public class RecursionExampleUnitTest { RecursionExample recursion = new RecursionExample(); diff --git a/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsTest.java b/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsUnitTest.java similarity index 93% rename from core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsTest.java rename to core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsUnitTest.java index bba867f50f..77cdd0279d 100644 --- a/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsTest.java +++ b/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsUnitTest.java @@ -7,7 +7,7 @@ import java.util.List; import static org.junit.Assert.assertTrue; -public class BaeldungReflectionUtilsTest { +public class BaeldungReflectionUtilsUnitTest { @Test public void givenCustomer_whenAFieldIsNull_thenFieldNameInResult() throws Exception { diff --git a/core-java/src/test/java/com/baeldung/regexp/EscapingCharsTest.java b/core-java/src/test/java/com/baeldung/regexp/EscapingCharsUnitTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/regexp/EscapingCharsTest.java rename to core-java/src/test/java/com/baeldung/regexp/EscapingCharsUnitTest.java index 47c9cfc621..d903a02589 100644 --- a/core-java/src/test/java/com/baeldung/regexp/EscapingCharsTest.java +++ b/core-java/src/test/java/com/baeldung/regexp/EscapingCharsUnitTest.java @@ -10,7 +10,7 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; -public class EscapingCharsTest { +public class EscapingCharsUnitTest { @Test public void givenRegexWithDot_whenMatchingStr_thenMatches() { String strInput = "foof"; diff --git a/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java b/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java index 7f165cec86..9abe8a927c 100644 --- a/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java +++ b/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java @@ -104,7 +104,7 @@ public class NashornUnitTest { public void loadExamples() throws ScriptException { Object loadResult = engine.eval("load('classpath:js/script.js');" + "increment(5)"); - Assert.assertEquals(6.0, loadResult); + Assert.assertEquals(6, ((Double) loadResult).intValue()); Object math = engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.increment(5);"); diff --git a/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableTest.java b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableUnitTest.java similarity index 90% rename from core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableTest.java rename to core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableUnitTest.java index cd31f545b9..8d8e4f14fe 100644 --- a/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableTest.java +++ b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableUnitTest.java @@ -4,7 +4,7 @@ import org.junit.Test; import static junit.framework.TestCase.assertEquals; -public class SneakyRunnableTest { +public class SneakyRunnableUnitTest { @Test public void whenCallSneakyRunnableMethod_thenThrowException() { diff --git a/core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsTest.java b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsUnitTest.java similarity index 91% rename from core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsTest.java rename to core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsUnitTest.java index e033ca062d..da1b2e617b 100644 --- a/core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsTest.java +++ b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsUnitTest.java @@ -4,7 +4,7 @@ import org.junit.Test; import static junit.framework.TestCase.assertEquals; -public class SneakyThrowsTest { +public class SneakyThrowsUnitTest { @Test public void whenCallSneakyMethod_thenThrowSneakyException() { diff --git a/core-java/src/test/java/com/baeldung/string/PalindromeTest.java b/core-java/src/test/java/com/baeldung/string/PalindromeUnitTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/string/PalindromeTest.java rename to core-java/src/test/java/com/baeldung/string/PalindromeUnitTest.java index bc6fee2cd9..49f2542f39 100644 --- a/core-java/src/test/java/com/baeldung/string/PalindromeTest.java +++ b/core-java/src/test/java/com/baeldung/string/PalindromeUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.string; import static org.junit.Assert.*; import org.junit.Test; -public class PalindromeTest { +public class PalindromeUnitTest { private String[] words = { "Anna", diff --git a/core-java/src/test/java/com/baeldung/string/StringComparisonTest.java b/core-java/src/test/java/com/baeldung/string/StringComparisonUnitTest.java similarity index 99% rename from core-java/src/test/java/com/baeldung/string/StringComparisonTest.java rename to core-java/src/test/java/com/baeldung/string/StringComparisonUnitTest.java index 5869676004..539f66d9b4 100644 --- a/core-java/src/test/java/com/baeldung/string/StringComparisonTest.java +++ b/core-java/src/test/java/com/baeldung/string/StringComparisonUnitTest.java @@ -7,7 +7,7 @@ import java.util.Objects; import static org.assertj.core.api.Assertions.assertThat; -public class StringComparisonTest { +public class StringComparisonUnitTest { @Test public void whenUsingComparisonOperator_ThenComparingStrings(){ diff --git a/core-java/src/test/java/com/baeldung/string/StringTest.java b/core-java/src/test/java/com/baeldung/string/StringUnitTest.java similarity index 99% rename from core-java/src/test/java/com/baeldung/string/StringTest.java rename to core-java/src/test/java/com/baeldung/string/StringUnitTest.java index e88b2d7c2c..0d4fd6eff9 100644 --- a/core-java/src/test/java/com/baeldung/string/StringTest.java +++ b/core-java/src/test/java/com/baeldung/string/StringUnitTest.java @@ -12,7 +12,7 @@ import java.util.regex.PatternSyntaxException; import org.junit.Test; -public class StringTest { +public class StringUnitTest { @Test public void whenCallCodePointAt_thenDecimalUnicodeReturned() { diff --git a/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java b/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java similarity index 99% rename from core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java rename to core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java index ad4f5dce7e..648fdaf65a 100644 --- a/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java +++ b/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java @@ -8,7 +8,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; -public class StringFormatterExampleTests { +public class StringFormatterExampleUnitTest { @Test public void givenString_whenFormatSpecifierForCalendar_thenGotExpected() { diff --git a/core-java/src/test/java/com/baeldung/system/DateTimeServiceTest.java b/core-java/src/test/java/com/baeldung/system/DateTimeServiceUnitTest.java similarity index 90% rename from core-java/src/test/java/com/baeldung/system/DateTimeServiceTest.java rename to core-java/src/test/java/com/baeldung/system/DateTimeServiceUnitTest.java index 587cd4ef20..ef083dd25e 100644 --- a/core-java/src/test/java/com/baeldung/system/DateTimeServiceTest.java +++ b/core-java/src/test/java/com/baeldung/system/DateTimeServiceUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.system; import org.junit.Assert; import org.junit.Test; -public class DateTimeServiceTest { +public class DateTimeServiceUnitTest { @Test public void givenClass_whenCalledMethods_thenNotNullInResult() { diff --git a/core-java/src/test/java/com/baeldung/system/EnvironmentVariablesTest.java b/core-java/src/test/java/com/baeldung/system/EnvironmentVariablesUnitTest.java similarity index 87% rename from core-java/src/test/java/com/baeldung/system/EnvironmentVariablesTest.java rename to core-java/src/test/java/com/baeldung/system/EnvironmentVariablesUnitTest.java index 3722fea88f..5e4db747be 100644 --- a/core-java/src/test/java/com/baeldung/system/EnvironmentVariablesTest.java +++ b/core-java/src/test/java/com/baeldung/system/EnvironmentVariablesUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.system; import org.junit.Assert; import org.junit.Test; -public class EnvironmentVariablesTest { +public class EnvironmentVariablesUnitTest { @Test public void givenEnvVars_whenReadPath_thenGetValueinResult() { diff --git a/core-java/src/test/java/com/baeldung/system/SystemArrayCopyTest.java b/core-java/src/test/java/com/baeldung/system/SystemArrayCopyUnitTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/system/SystemArrayCopyTest.java rename to core-java/src/test/java/com/baeldung/system/SystemArrayCopyUnitTest.java index f54e3702c8..bf715f3ac3 100644 --- a/core-java/src/test/java/com/baeldung/system/SystemArrayCopyTest.java +++ b/core-java/src/test/java/com/baeldung/system/SystemArrayCopyUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.system; import org.junit.Assert; import org.junit.Test; -public class SystemArrayCopyTest { +public class SystemArrayCopyUnitTest { @Test public void givenTwoArraysAB_whenUseArrayCopy_thenArrayCopiedFromAToBInResult() { diff --git a/core-java/src/test/java/com/baeldung/system/SystemNanoTest.java b/core-java/src/test/java/com/baeldung/system/SystemNanoUnitTest.java similarity index 91% rename from core-java/src/test/java/com/baeldung/system/SystemNanoTest.java rename to core-java/src/test/java/com/baeldung/system/SystemNanoUnitTest.java index bf6590da0a..cd9543212e 100644 --- a/core-java/src/test/java/com/baeldung/system/SystemNanoTest.java +++ b/core-java/src/test/java/com/baeldung/system/SystemNanoUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.system; import org.junit.Assert; import org.junit.Test; -public class SystemNanoTest { +public class SystemNanoUnitTest { @Test public void givenSystem_whenCalledNanoTime_thenGivesTimeinResult() { diff --git a/core-java/src/test/java/com/baeldung/system/SystemPropertiesTest.java b/core-java/src/test/java/com/baeldung/system/SystemPropertiesUnitTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/system/SystemPropertiesTest.java rename to core-java/src/test/java/com/baeldung/system/SystemPropertiesUnitTest.java index 4fca27f96c..4940e39238 100644 --- a/core-java/src/test/java/com/baeldung/system/SystemPropertiesTest.java +++ b/core-java/src/test/java/com/baeldung/system/SystemPropertiesUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import java.util.Properties; -public class SystemPropertiesTest { +public class SystemPropertiesUnitTest { @Test public void givenSystem_whenCalledGetProperty_thenReturnPropertyinResult() { diff --git a/core-java/src/test/java/com/baeldung/system/WhenDetectingOSTest.java b/core-java/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java similarity index 93% rename from core-java/src/test/java/com/baeldung/system/WhenDetectingOSTest.java rename to core-java/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java index 77901f6524..27a6dd43c6 100644 --- a/core-java/src/test/java/com/baeldung/system/WhenDetectingOSTest.java +++ b/core-java/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java @@ -5,7 +5,7 @@ import org.junit.Ignore; import org.junit.Test; @Ignore -public class WhenDetectingOSTest { +public class WhenDetectingOSUnitTest { private DetectOS os = new DetectOS(); diff --git a/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java b/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomIntegrationTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java rename to core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomIntegrationTest.java index c75813baba..56c77f923f 100644 --- a/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java +++ b/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomIntegrationTest.java @@ -5,7 +5,7 @@ import java.util.concurrent.ThreadLocalRandom; import static org.junit.Assert.assertTrue; import org.junit.Test; -public class ThreadLocalRandomTest { +public class ThreadLocalRandomIntegrationTest { @Test public void givenUsingThreadLocalRandom_whenGeneratingRandomIntBounded_thenCorrect() { diff --git a/core-java/src/test/java/com/baeldung/util/PropertiesLoaderTest.java b/core-java/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java similarity index 96% rename from core-java/src/test/java/com/baeldung/util/PropertiesLoaderTest.java rename to core-java/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java index fa3c425156..eea3068253 100644 --- a/core-java/src/test/java/com/baeldung/util/PropertiesLoaderTest.java +++ b/core-java/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java @@ -7,7 +7,7 @@ import java.util.Properties; import static org.junit.Assert.assertEquals; -public class PropertiesLoaderTest { +public class PropertiesLoaderUnitTest { @Test public void loadProperties_whenPropertyReaded_thenSuccess() throws IOException { diff --git a/core-java/src/test/java/com/baeldung/varargs/FormatterTest.java b/core-java/src/test/java/com/baeldung/varargs/FormatterUnitTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/varargs/FormatterTest.java rename to core-java/src/test/java/com/baeldung/varargs/FormatterUnitTest.java index 509c8764d2..e9018afd62 100644 --- a/core-java/src/test/java/com/baeldung/varargs/FormatterTest.java +++ b/core-java/src/test/java/com/baeldung/varargs/FormatterUnitTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -public class FormatterTest { +public class FormatterUnitTest { private final static String FORMAT = "%s %s %s"; diff --git a/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesTest.java b/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesUnitTest.java similarity index 91% rename from core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesTest.java rename to core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesUnitTest.java index 2b36786abf..161c053cea 100644 --- a/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesTest.java +++ b/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesUnitTest.java @@ -5,7 +5,7 @@ import java.util.List; import org.junit.Test; -public class RawTypesTest { +public class RawTypesUnitTest { @Test public void shouldCreateListUsingRawTypes() { @SuppressWarnings("rawtypes") diff --git a/core-kotlin/README.md b/core-kotlin/README.md index d51c461101..7fcdc68429 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -27,3 +27,6 @@ - [Guide to Kotlin @JvmField](http://www.baeldung.com/kotlin-jvm-field-annotation) - [Filtering Kotlin Collections](http://www.baeldung.com/kotlin-filter-collection) - [Writing to a File in Kotlin](http://www.baeldung.com/kotlin-write-file) +- [Lambda Expressions in Kotlin](http://www.baeldung.com/kotlin-lambda-expressions) +- [Writing Specifications with Kotlin and Spek](http://www.baeldung.com/kotlin-spek) +- [Processing JSON with Kotlin and Klaxson](http://www.baeldung.com/kotlin-json-klaxson) diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml index 24bfb302cf..1dd804eedd 100644 --- a/core-kotlin/pom.xml +++ b/core-kotlin/pom.xml @@ -98,13 +98,18 @@ ${assertj.version} test + + com.beust + klaxon + ${klaxon.version} + - kotlin-maven-plugin org.jetbrains.kotlin + kotlin-maven-plugin ${kotlin-maven-plugin.version} @@ -200,20 +205,22 @@ UTF-8 - 1.2.31 - 1.2.31 - 1.2.31 - 1.2.31 - 0.15 + 1.2.41 + 1.2.41 + 1.2.41 + 1.2.41 + 0.22.5 1.5.0 4.1.0 + 3.0.4 + 2.21.0 0.1.0 3.6.1 - 5.0.0 - 1.0.0 - 4.12.0 + 5.2.0 + 1.2.0 + 5.2.0 4.12 - 3.9.1 + 3.10.0 1.8 1.8 diff --git a/core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt b/core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt new file mode 100644 index 0000000000..69cfce5601 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt @@ -0,0 +1,23 @@ +package com.baeldung.enums + +enum class CardType(val color: String) : ICardLimit { + SILVER("gray") { + override fun getCreditLimit() = 100000 + override fun calculateCashbackPercent() = 0.25f + }, + GOLD("yellow") { + override fun getCreditLimit() = 200000 + override fun calculateCashbackPercent(): Float = 0.5f + }, + PLATINUM("black") { + override fun getCreditLimit() = 300000 + override fun calculateCashbackPercent() = 0.75f + }; + + companion object { + fun getCardTypeByColor(color: String) = values().firstOrNull { it.color == color } + fun getCardTypeByName(name: String) = valueOf(name.toUpperCase()) + } + + abstract fun calculateCashbackPercent(): Float +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/enums/ICardLimit.kt b/core-kotlin/src/main/kotlin/com/baeldung/enums/ICardLimit.kt new file mode 100644 index 0000000000..7994822a52 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/enums/ICardLimit.kt @@ -0,0 +1,5 @@ +package com.baeldung.enums + +interface ICardLimit { + fun getCreditLimit(): Int +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt b/core-kotlin/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt new file mode 100644 index 0000000000..cc46c65f96 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt @@ -0,0 +1,9 @@ +package com.baeldung.klaxon + +import com.beust.klaxon.Json + +class CustomProduct( + @Json(name = "productName") + val name: String, + @Json(ignored = true) + val id: Int) \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/klaxon/Product.kt b/core-kotlin/src/main/kotlin/com/baeldung/klaxon/Product.kt new file mode 100644 index 0000000000..09bcbc8722 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/klaxon/Product.kt @@ -0,0 +1,3 @@ +package com.baeldung.klaxon + +class Product(val name: String) \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/klaxon/ProductData.kt b/core-kotlin/src/main/kotlin/com/baeldung/klaxon/ProductData.kt new file mode 100644 index 0000000000..1f30f26ce9 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/klaxon/ProductData.kt @@ -0,0 +1,3 @@ +package com.baeldung.klaxon + +data class ProductData(val name: String, val capacityInGb: Int) \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt new file mode 100644 index 0000000000..525faebd55 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt @@ -0,0 +1,84 @@ +package com.baeldung.enums + +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +internal class CardTypeUnitTest { + + @Test + fun givenSilverCardType_whenCalculateCashbackPercent_thenReturnCashbackValue() { + assertEquals(0.25f, CardType.SILVER.calculateCashbackPercent()) + } + + @Test + fun givenGoldCardType_whenCalculateCashbackPercent_thenReturnCashbackValue() { + assertEquals(0.5f, CardType.GOLD.calculateCashbackPercent()) + } + + @Test + fun givenPlatinumCardType_whenCalculateCashbackPercent_thenReturnCashbackValue() { + assertEquals(0.75f, CardType.PLATINUM.calculateCashbackPercent()) + } + + @Test + fun givenSilverCardType_whenGetCreditLimit_thenReturnCreditLimit() { + assertEquals(100000, CardType.SILVER.getCreditLimit()) + } + + @Test + fun givenGoldCardType_whenGetCreditLimit_thenReturnCreditLimit() { + assertEquals(200000, CardType.GOLD.getCreditLimit()) + } + + @Test + fun givenPlatinumCardType_whenGetCreditLimit_thenReturnCreditLimit() { + assertEquals(300000, CardType.PLATINUM.getCreditLimit()) + } + + @Test + fun givenSilverCardType_whenCheckColor_thenReturnColor() { + assertEquals("gray", CardType.SILVER.color) + } + + @Test + fun givenGoldCardType_whenCheckColor_thenReturnColor() { + assertEquals("yellow", CardType.GOLD.color) + } + + @Test + fun givenPlatinumCardType_whenCheckColor_thenReturnColor() { + assertEquals("black", CardType.PLATINUM.color) + } + + @Test + fun whenGetCardTypeByColor_thenSilverCardType() { + Assertions.assertEquals(CardType.SILVER, CardType.getCardTypeByColor("gray")) + } + + @Test + fun whenGetCardTypeByColor_thenGoldCardType() { + Assertions.assertEquals(CardType.GOLD, CardType.getCardTypeByColor("yellow")) + } + + @Test + fun whenGetCardTypeByColor_thenPlatinumCardType() { + Assertions.assertEquals(CardType.PLATINUM, CardType.getCardTypeByColor("black")) + } + + @Test + fun whenGetCardTypeByName_thenSilverCardType() { + Assertions.assertEquals(CardType.SILVER, CardType.getCardTypeByName("silver")) + } + + @Test + fun whenGetCardTypeByName_thenGoldCardType() { + Assertions.assertEquals(CardType.GOLD, CardType.getCardTypeByName("gold")) + } + + @Test + fun whenGetCardTypeByName_thenPlatinumCardType() { + Assertions.assertEquals(CardType.PLATINUM, CardType.getCardTypeByName("platinum")) + } + +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt new file mode 100644 index 0000000000..2a7d44a163 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt @@ -0,0 +1,163 @@ +package com.baeldung.klaxon + +import com.beust.klaxon.JsonArray +import com.beust.klaxon.JsonObject +import com.beust.klaxon.JsonReader +import com.beust.klaxon.Klaxon +import com.beust.klaxon.Parser +import com.beust.klaxon.PathMatcher +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.SoftAssertions.assertSoftly +import org.junit.Assert +import org.junit.jupiter.api.Test +import java.io.StringReader +import java.util.regex.Pattern + +class KlaxonUnitTest { + + @Test + fun giveProduct_whenSerialize_thenGetJsonString() { + val product = Product("HDD") + val result = Klaxon().toJsonString(product) + + assertThat(result).isEqualTo("""{"name" : "HDD"}""") + } + + @Test + fun giveJsonString_whenDeserialize_thenGetProduct() { + val result = Klaxon().parse(""" + { + "name" : "RAM" + } + """) + + assertThat(result?.name).isEqualTo("RAM") + } + + @Test + fun giveCustomProduct_whenSerialize_thenGetJsonString() { + val product = CustomProduct("HDD", 1) + val result = Klaxon().toJsonString(product) + + assertThat(result).isEqualTo("""{"productName" : "HDD"}""") + } + + @Test + fun giveJsonArray_whenStreaming_thenGetProductArray() { + val jsonArray = """ + [ + { "name" : "HDD", "capacityInGb" : 512 }, + { "name" : "RAM", "capacityInGb" : 16 } + ]""" + val expectedArray = arrayListOf(ProductData("HDD", 512), + ProductData("RAM", 16)) + val klaxon = Klaxon() + val productArray = arrayListOf() + JsonReader(StringReader(jsonArray)).use { reader -> + reader.beginArray { + while (reader.hasNext()) { + val product = klaxon.parse(reader) + productArray.add(product!!) + } + } + } + + assertThat(productArray).hasSize(2).isEqualTo(expectedArray) + } + + @Test + fun giveJsonString_whenParser_thenGetJsonObject() { + val jsonString = StringBuilder(""" + { + "name" : "HDD", + "capacityInGb" : 512, + "sizeInInch" : 2.5 + } + """) + val parser = Parser() + val json = parser.parse(jsonString) as JsonObject + + assertThat(json).hasSize(3).containsEntry("name", "HDD").containsEntry("capacityInGb", 512).containsEntry("sizeInInch", 2.5) + } + + @Suppress("UNCHECKED_CAST") + @Test + fun giveJsonStringArray_whenParser_thenGetJsonArray() { + val jsonString = StringBuilder(""" + [ + { "name" : "SDD" }, + { "madeIn" : "Taiwan" }, + { "warrantyInYears" : 5 } + ]""") + val parser = Parser() + val json = parser.parse(jsonString) as JsonArray + + assertSoftly({ softly -> + softly.assertThat(json).hasSize(3) + softly.assertThat(json[0]["name"]).isEqualTo("SDD") + softly.assertThat(json[1]["madeIn"]).isEqualTo("Taiwan") + softly.assertThat(json[2]["warrantyInYears"]).isEqualTo(5) + }) + } + + @Test + fun givenJsonString_whenStreaming_thenProcess() { + val jsonString = """ + { + "name" : "HDD", + "madeIn" : "Taiwan", + "warrantyInYears" : 5 + "hasStock" : true + "capacitiesInTb" : [ 1, 2 ], + "features" : { "cacheInMb" : 64, "speedInRpm" : 7200 } + }""" + + JsonReader(StringReader(jsonString)).use { reader -> + reader.beginObject { + while (reader.hasNext()) { + val readName = reader.nextName() + when (readName) { + "name" -> assertThat(reader.nextString()).isEqualTo("HDD") + "madeIn" -> assertThat(reader.nextString()).isEqualTo("Taiwan") + "warrantyInYears" -> assertThat(reader.nextInt()).isEqualTo(5) + "hasStock" -> assertThat(reader.nextBoolean()).isEqualTo(true) + "capacitiesInTb" -> assertThat(reader.nextArray()).contains(1, 2) + "features" -> assertThat(reader.nextObject()).containsEntry("cacheInMb", 64).containsEntry("speedInRpm", 7200) + else -> Assert.fail("Unexpected name: $readName") + } + } + } + } + + } + + @Test + fun givenDiskInventory_whenRegexMatches_thenGetTypes() { + val jsonString = """ + { + "inventory" : { + "disks" : [ + { + "type" : "HDD", + "sizeInGb" : 1000 + }, + { + "type" : "SDD", + "sizeInGb" : 512 + } + ] + } + }""" + val pathMatcher = object : PathMatcher { + override fun pathMatches(path: String) = Pattern.matches(".*inventory.*disks.*type.*", path) + + override fun onMatch(path: String, value: Any) { + when (path) { + "$.inventory.disks[0].type" -> assertThat(value).isEqualTo("HDD") + "$.inventory.disks[1].type" -> assertThat(value).isEqualTo("SDD") + } + } + } + Klaxon().pathMatcher(pathMatcher).parseJsonObject(StringReader(jsonString)) + } +} \ No newline at end of file diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java index e708922988..3100f0c70b 100644 --- a/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java +++ b/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java @@ -5,6 +5,7 @@ import java.util.concurrent.ConcurrentHashMap; import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.couchbase.client.java.Bucket; @@ -18,6 +19,11 @@ public class ClusterServiceImpl implements ClusterService { private Cluster cluster; private Map buckets = new ConcurrentHashMap<>(); + + @Autowired + public ClusterServiceImpl(Cluster cluster) { + this.cluster = cluster; + } @PostConstruct private void init() { diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java index 459585d995..75a196ff5d 100644 --- a/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java +++ b/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java @@ -18,6 +18,7 @@ public class TutorialBucketService extends AbstractBucketService { @Autowired public TutorialBucketService(ClusterService clusterService) { super(clusterService); + openBucket(); } @Override diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java new file mode 100644 index 0000000000..9e650752d2 --- /dev/null +++ b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java @@ -0,0 +1,24 @@ +package com.baeldung.couchbase.async.person; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +import com.couchbase.client.java.Cluster; +import com.couchbase.client.java.CouchbaseCluster; +import com.couchbase.client.java.env.CouchbaseEnvironment; +import com.couchbase.client.java.env.DefaultCouchbaseEnvironment; + +@Configuration +@ComponentScan(basePackages = {"com.baeldung.couchbase.async.service", "com.baeldung.couchbase.n1ql"}) +public class PersonCrudServiceIntegrationTestConfig { + + @Bean + public Cluster cluster() { + CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder() + .connectTimeout(60000) + .build(); + return CouchbaseCluster.create(env, "127.0.0.1"); + } + +} diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java similarity index 90% rename from couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java index 565aaed5da..267071ab35 100644 --- a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java +++ b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java @@ -1,27 +1,31 @@ package com.baeldung.couchbase.async.person; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.UUID; -import javax.annotation.PostConstruct; - import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baeldung.couchbase.async.AsyncIntegrationTest; -import com.baeldung.couchbase.async.person.Person; -import com.baeldung.couchbase.async.person.PersonCrudService; -import com.baeldung.couchbase.async.person.PersonDocumentConverter; import com.baeldung.couchbase.async.service.BucketService; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.document.JsonDocument; -public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest { +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {PersonCrudServiceIntegrationTestConfig.class}) +public class PersonCrudServiceLiveTest extends AsyncIntegrationTest { @Autowired private PersonCrudService personService; @@ -35,8 +39,8 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest { private Bucket bucket; - @PostConstruct - private void init() { + @Before + public void init() { bucket = bucketService.getBucket(); } diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java similarity index 94% rename from couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java index d0db5d37a3..5f478ae788 100644 --- a/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java +++ b/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java @@ -18,7 +18,7 @@ import com.couchbase.client.java.Bucket; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { AsyncIntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public class ClusterServiceIntegrationTest extends AsyncIntegrationTest { +public class ClusterServiceLiveTest extends AsyncIntegrationTest { @Autowired private ClusterService couchbaseService; diff --git a/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java similarity index 98% rename from couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java index 00d462e32a..d260795ed3 100644 --- a/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java +++ b/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java @@ -14,8 +14,8 @@ import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.view.ViewResult; import com.couchbase.client.java.view.ViewRow; -public class StudentGradeServiceIntegrationTest { - private static final Logger logger = LoggerFactory.getLogger(StudentGradeServiceIntegrationTest.class); +public class StudentGradeServiceLiveTest { + private static final Logger logger = LoggerFactory.getLogger(StudentGradeServiceLiveTest.class); static StudentGradeService studentGradeService; static Set gradeIds = new HashSet<>(); diff --git a/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java similarity index 97% rename from couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java index 8112d7d222..602bb5b8a5 100644 --- a/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java +++ b/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java @@ -1,5 +1,23 @@ package com.baeldung.couchbase.n1ql; +import static com.baeldung.couchbase.n1ql.CodeSnippets.extractJsonResult; +import static com.couchbase.client.java.query.Select.select; +import static com.couchbase.client.java.query.dsl.Expression.i; +import static com.couchbase.client.java.query.dsl.Expression.s; +import static com.couchbase.client.java.query.dsl.Expression.x; +import static org.junit.Assert.assertNotNull; + +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Cluster; import com.couchbase.client.java.document.JsonDocument; @@ -10,28 +28,13 @@ import com.couchbase.client.java.query.N1qlQueryResult; import com.couchbase.client.java.query.N1qlQueryRow; import com.couchbase.client.java.query.Statement; import com.fasterxml.jackson.databind.JsonNode; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + import rx.Observable; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import java.util.stream.Stream; - -import static com.baeldung.couchbase.n1ql.CodeSnippets.extractJsonResult; -import static com.couchbase.client.java.query.Select.select; -import static com.couchbase.client.java.query.dsl.Expression.*; -import static org.junit.Assert.assertNotNull; - @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { IntegrationTestConfig.class }) -public class N1QLIntegrationTest { +public class N1QLLiveTest { @Autowired diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java similarity index 97% rename from couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java index ec15be1acc..493b326d49 100644 --- a/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java +++ b/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java @@ -10,7 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired; import com.baeldung.couchbase.spring.IntegrationTest; -public class PersonCrudServiceIntegrationTest extends IntegrationTest { +public class PersonCrudServiceLiveTest extends IntegrationTest { private static final String CLARK_KENT = "Clark Kent"; private static final String SMALLVILLE = "Smallville"; diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java similarity index 94% rename from couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java index ead247dfbc..7a89a208f7 100644 --- a/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java +++ b/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java @@ -17,7 +17,7 @@ import com.couchbase.client.java.Bucket; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { IntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public class ClusterServiceIntegrationTest extends IntegrationTest { +public class ClusterServiceLiveTest extends IntegrationTest { @Autowired private ClusterService couchbaseService; diff --git a/custom-pmd-0.0.1.jar b/custom-pmd-0.0.1.jar index 4ad6933865..5038a70475 100644 Binary files a/custom-pmd-0.0.1.jar and b/custom-pmd-0.0.1.jar differ diff --git a/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java b/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java index 4136165b6f..9a2795b581 100644 --- a/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java +++ b/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java @@ -14,17 +14,16 @@ public class UnitTestNamingConventionRule extends AbstractJavaRule { "ManualTest", "JdbcTest", "LiveTest", - "UnitTest"); + "UnitTest", + "jmhTest"); public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { String className = node.getImage(); Objects.requireNonNull(className); - if (className.endsWith("Test") || className.endsWith("Tests")) { - if (allowedEndings.stream() - .noneMatch(className::endsWith)) { - addViolation(data, node); - } + if (className.endsWith("Tests") + || (className.endsWith("Test") && allowedEndings.stream().noneMatch(className::endsWith))) { + addViolation(data, node); } return data; diff --git a/dagger/README.md b/dagger/README.md new file mode 100644 index 0000000000..72cba3d3f2 --- /dev/null +++ b/dagger/README.md @@ -0,0 +1,3 @@ +### Relevant articles: + +- [Introduction to Dagger 2](http://www.baeldung.com/dagger-2) diff --git a/dagger/pom.xml b/dagger/pom.xml new file mode 100644 index 0000000000..f927ce42c4 --- /dev/null +++ b/dagger/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + dagger + dagger + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + junit + junit + ${junit.version} + test + + + + + com.google.dagger + dagger + ${dagger.version} + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.1 + + + + com.google.dagger + dagger-compiler + 2.16 + + + + + + + + + 4.12 + 2.16 + + + \ No newline at end of file diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/Brand.java b/dagger/src/main/java/com/baeldung/dagger/intro/Brand.java new file mode 100644 index 0000000000..5ec6607d67 --- /dev/null +++ b/dagger/src/main/java/com/baeldung/dagger/intro/Brand.java @@ -0,0 +1,45 @@ +package com.baeldung.dagger.intro; + +/** + * Brand of a {@link Car}. + * + * @author Donato Rimenti + * + */ +public class Brand { + + /** + * The name of the brand. + */ + private String name; + + /** + * Instantiates a new Brand. + * + * @param name + * the {@link #name} + */ + public Brand(String name) { + this.name = name; + } + + /** + * Gets the {@link #name}. + * + * @return the {@link #name} + */ + public String getName() { + return name; + } + + /** + * Sets the {@link #name}. + * + * @param name + * the new {@link #name} + */ + public void setName(String name) { + this.name = name; + } + +} diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/Car.java b/dagger/src/main/java/com/baeldung/dagger/intro/Car.java new file mode 100644 index 0000000000..2ad81b8f6c --- /dev/null +++ b/dagger/src/main/java/com/baeldung/dagger/intro/Car.java @@ -0,0 +1,75 @@ +package com.baeldung.dagger.intro; + +import javax.inject.Inject; + +/** + * Represents a car. + * + * @author Donato Rimenti + * + */ +public class Car { + + /** + * The car's engine. + */ + private Engine engine; + + /** + * The car's brand. + */ + private Brand brand; + + /** + * Instantiates a new Car. + * + * @param engine + * the {@link #engine} + * @param brand + * the {@link #brand} + */ + @Inject + public Car(Engine engine, Brand brand) { + this.engine = engine; + this.brand = brand; + } + + /** + * Gets the {@link #engine}. + * + * @return the {@link #engine} + */ + public Engine getEngine() { + return engine; + } + + /** + * Sets the {@link #engine}. + * + * @param engine + * the new {@link #engine} + */ + public void setEngine(Engine engine) { + this.engine = engine; + } + + /** + * Gets the {@link #brand}. + * + * @return the {@link #brand} + */ + public Brand getBrand() { + return brand; + } + + /** + * Sets the {@link #brand}. + * + * @param brand + * the new {@link #brand} + */ + public void setBrand(Brand brand) { + this.brand = brand; + } + +} diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/Engine.java b/dagger/src/main/java/com/baeldung/dagger/intro/Engine.java new file mode 100644 index 0000000000..99e30625cd --- /dev/null +++ b/dagger/src/main/java/com/baeldung/dagger/intro/Engine.java @@ -0,0 +1,24 @@ +package com.baeldung.dagger.intro; + +/** + * Engine of a {@link Car}. + * + * @author Donato Rimenti + * + */ +public class Engine { + + /** + * Starts the engine. + */ + public void start() { + System.out.println("Engine started"); + } + + /** + * Stops the engine. + */ + public void stop() { + System.out.println("Engine stopped"); + } +} diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesComponent.java b/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesComponent.java new file mode 100644 index 0000000000..aeeaab636e --- /dev/null +++ b/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesComponent.java @@ -0,0 +1,24 @@ +package com.baeldung.dagger.intro; + +import javax.inject.Singleton; + +import dagger.Component; + +/** + * Dagger component for building vehicles. + * + * @author Donato Rimenti + * + */ +@Singleton +@Component(modules = VehiclesModule.class) +public interface VehiclesComponent { + + /** + * Builds a {@link Car}. + * + * @return a {@link Car} + */ + public Car buildCar(); + +} \ No newline at end of file diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesModule.java b/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesModule.java new file mode 100644 index 0000000000..f6c6e4a108 --- /dev/null +++ b/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesModule.java @@ -0,0 +1,37 @@ +package com.baeldung.dagger.intro; + +import javax.inject.Singleton; + +import dagger.Module; +import dagger.Provides; + +/** + * Dagger module for providing vehicles components. + * + * @author Donato Rimenti + * + */ +@Module +public class VehiclesModule { + + /** + * Creates an {@link Engine}. + * + * @return an {@link Engine} + */ + @Provides + public Engine provideEngine() { + return new Engine(); + } + + /** + * Creates a {@link Brand}. + * + * @return a {@link Brand} + */ + @Provides + @Singleton + public Brand provideBrand() { + return new Brand("Baeldung"); + } +} \ No newline at end of file diff --git a/dagger/src/test/java/com/baeldung/dagger/intro/DaggerUnitTest.java b/dagger/src/test/java/com/baeldung/dagger/intro/DaggerUnitTest.java new file mode 100644 index 0000000000..83e881ffe1 --- /dev/null +++ b/dagger/src/test/java/com/baeldung/dagger/intro/DaggerUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.dagger.intro; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Unit test for building a {@link Car} using Dagger. + * + * @author Donato Rimenti + * + */ +public class DaggerUnitTest { + + /** + * Builds two {@link Car} and checks that the fields are injected correctly. + */ + @Test + public void givenGeneratedComponent_whenBuildingCar_thenDependenciesInjected() { + VehiclesComponent component = DaggerVehiclesComponent.create(); + + Car carOne = component.buildCar(); + Car carTwo = component.buildCar(); + + Assert.assertNotNull(carOne); + Assert.assertNotNull(carTwo); + Assert.assertNotNull(carOne.getEngine()); + Assert.assertNotNull(carTwo.getEngine()); + Assert.assertNotNull(carOne.getBrand()); + Assert.assertNotNull(carTwo.getBrand()); + Assert.assertNotEquals(carOne.getEngine(), carTwo.getEngine()); + Assert.assertEquals(carOne.getBrand(), carTwo.getBrand()); + } + +} diff --git a/drools/pom.xml b/drools/pom.xml index 60df7157f2..a060563eeb 100644 --- a/drools/pom.xml +++ b/drools/pom.xml @@ -6,9 +6,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -54,7 +54,6 @@ 4.4.6 7.4.1.Final 3.13 - 4.3.6.RELEASE diff --git a/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingTest.java b/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingIntegrationTest.java similarity index 95% rename from drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingTest.java rename to drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingIntegrationTest.java index f49d0b82de..fd49f94479 100644 --- a/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingTest.java +++ b/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingIntegrationTest.java @@ -10,7 +10,7 @@ import com.baeldung.drools.model.Result; import static junit.framework.TestCase.assertEquals; -public class BackwardChainingTest { +public class BackwardChainingIntegrationTest { private Result result; private KieSession ksession; diff --git a/ejb/ejb-client/pom.xml b/ejb/ejb-client/pom.xml index 83dd0aef30..88116f8003 100755 --- a/ejb/ejb-client/pom.xml +++ b/ejb/ejb-client/pom.xml @@ -3,7 +3,6 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 ejb-client - EJB3 Client Maven EJB3 Client Maven diff --git a/ethereumj/README.md b/ethereumj/README.md index 5a0be0bd16..320ae8c9f8 100644 --- a/ethereumj/README.md +++ b/ethereumj/README.md @@ -3,3 +3,4 @@ ### Relevant Articles: - [Introduction to EthereumJ](http://www.baeldung.com/ethereumj) - [Creating and Deploying Smart Contracts with Solidity](http://www.baeldung.com/smart-contracts-ethereum-solidity) +- [Lightweight Ethereum Clients Using Web3j](http://www.baeldung.com/web3j) diff --git a/ethereumj/pom.xml b/ethereumj/pom.xml index 611b7b09eb..6917505f1b 100644 --- a/ethereumj/pom.xml +++ b/ethereumj/pom.xml @@ -10,10 +10,10 @@ ethereumj - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/flips/pom.xml b/flips/pom.xml index be9f584114..34cbab7035 100644 --- a/flips/pom.xml +++ b/flips/pom.xml @@ -8,10 +8,10 @@ flips - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/flips/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java b/flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java similarity index 98% rename from flips/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java rename to flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java index 8fd9c4e340..9dd4ef064a 100644 --- a/flips/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java +++ b/flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java @@ -23,7 +23,7 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; }, webEnvironment = SpringBootTest.WebEnvironment.MOCK) @AutoConfigureMockMvc @ActiveProfiles("dev") -public class FlipControllerTest { +public class FlipControllerIntegrationTest { @Autowired private MockMvc mvc; diff --git a/flyway/pom.xml b/flyway/pom.xml index 3637f1de28..018f9b7f86 100644 --- a/flyway/pom.xml +++ b/flyway/pom.xml @@ -8,10 +8,10 @@ Flyway Callbacks Demo - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/grpc/pom.xml b/grpc/pom.xml index ad563f16fd..fb8312e8df 100644 --- a/grpc/pom.xml +++ b/grpc/pom.xml @@ -5,8 +5,6 @@ grpc-demo 0.0.1-SNAPSHOT jar - grpc-demo - http://maven.apache.org com.baeldung diff --git a/gson/README.md b/gson/README.md index 60c80477b1..bedfbd206c 100644 --- a/gson/README.md +++ b/gson/README.md @@ -6,3 +6,4 @@ ### Relevant Articles: - [Gson Deserialization Cookbook](http://www.baeldung.com/gson-deserialization-guide) - [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson) +- [Exclude Fields from Serialization in Gson](http://www.baeldung.com/gson-exclude-fields-serialization) diff --git a/gson/pom.xml b/gson/pom.xml index 912111374d..9ef775122c 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -1,67 +1,74 @@ - - 4.0.0 - com.baeldung - gson - 0.1-SNAPSHOT - gson + + 4.0.0 + com.baeldung + gson + 0.1-SNAPSHOT + gson - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + - - - - joda-time - joda-time - ${joda-time.version} - - - commons-io - commons-io - ${commons-io.version} - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - com.google.code.gson - gson - ${gson.version} - - + + + + org.projectlombok + lombok + 1.16.10 + provided + + + joda-time + joda-time + ${joda-time.version} + + + commons-io + commons-io + ${commons-io.version} + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + com.google.code.gson + gson + ${gson.version} + + - - gson - - - src/main/resources - true - - - + + gson + + + src/main/resources + true + + + - - - 2.8.0 - - 19.0 - 3.5 - 4.1 - 2.5 - 2.9.6 - + + + 2.8.0 + + 19.0 + 3.5 + 4.1 + 2.5 + 2.9.6 + \ No newline at end of file diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/Exclude.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/Exclude.java new file mode 100644 index 0000000000..429cb9d1b5 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/Exclude.java @@ -0,0 +1,11 @@ +package org.baeldung.gson.serializationwithexclusions; + +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.FIELD) +public @interface Exclude { +} \ No newline at end of file diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClass.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClass.java new file mode 100644 index 0000000000..cc6c498458 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClass.java @@ -0,0 +1,13 @@ +package org.baeldung.gson.serializationwithexclusions; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MyClass { + private long id; + private String name; + private String other; + private MySubClass subclass; +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithAnnotatedFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithAnnotatedFields.java new file mode 100644 index 0000000000..5d41f8a224 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithAnnotatedFields.java @@ -0,0 +1,20 @@ +package org.baeldung.gson.serializationwithexclusions; + +import com.google.gson.annotations.Expose; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MyClassWithAnnotatedFields { + + @Expose + private long id; + @Expose + private String name; + private String other; + @Expose + private MySubClassWithAnnotatedFields subclass; + +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithCustomAnnotatedFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithCustomAnnotatedFields.java new file mode 100644 index 0000000000..ace3583013 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithCustomAnnotatedFields.java @@ -0,0 +1,16 @@ +package org.baeldung.gson.serializationwithexclusions; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MyClassWithCustomAnnotatedFields { + + private long id; + private String name; + @Exclude + private String other; + private MySubClassWithCustomAnnotatedFields subclass; + +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithTransientFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithTransientFields.java new file mode 100644 index 0000000000..5e781a6287 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithTransientFields.java @@ -0,0 +1,15 @@ +package org.baeldung.gson.serializationwithexclusions; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MyClassWithTransientFields { + + private long id; + private String name; + private transient String other; + private MySubClassWithTransientFields subclass; + +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClass.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClass.java new file mode 100644 index 0000000000..5adac0697e --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClass.java @@ -0,0 +1,12 @@ +package org.baeldung.gson.serializationwithexclusions; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MySubClass { + private long id; + private String description; + private String otherVerboseInfo; +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithAnnotatedFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithAnnotatedFields.java new file mode 100644 index 0000000000..a0f7b5d277 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithAnnotatedFields.java @@ -0,0 +1,15 @@ +package org.baeldung.gson.serializationwithexclusions; + +import com.google.gson.annotations.Expose; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MySubClassWithAnnotatedFields { + + @Expose private long id; + @Expose private String description; + private String otherVerboseInfo; +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithCustomAnnotatedFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithCustomAnnotatedFields.java new file mode 100644 index 0000000000..f6aa4651b3 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithCustomAnnotatedFields.java @@ -0,0 +1,14 @@ +package org.baeldung.gson.serializationwithexclusions; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MySubClassWithCustomAnnotatedFields { + + private long id; + private String description; + @Exclude + private String otherVerboseInfo; +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithTransientFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithTransientFields.java new file mode 100644 index 0000000000..d4e31b0bc8 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithTransientFields.java @@ -0,0 +1,13 @@ +package org.baeldung.gson.serializationwithexclusions; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MySubClassWithTransientFields { + + private long id; + private String description; + private transient String otherVerboseInfo; +} diff --git a/gson/src/test/java/org/baeldung/gson/serializationwithexclusions/SerializationWithExclusionsUnitTest.java b/gson/src/test/java/org/baeldung/gson/serializationwithexclusions/SerializationWithExclusionsUnitTest.java new file mode 100644 index 0000000000..632d06946b --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/serializationwithexclusions/SerializationWithExclusionsUnitTest.java @@ -0,0 +1,104 @@ +package org.baeldung.gson.serializationwithexclusions; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +import com.google.gson.ExclusionStrategy; +import com.google.gson.FieldAttributes; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +class SerializationWithExclusionsUnitTest { + + final String expectedResult = "{\"id\":1,\"name\":\"foo\",\"subclass\":{\"id\":42,\"description\":\"the answer\"}}"; + + @Test + public void givenClassWithTransientFields_whenSerializing_thenCorrectWithoutTransientFields() { + MyClassWithTransientFields source = new MyClassWithTransientFields(1L, "foo", "bar", new MySubClassWithTransientFields(42L, "the answer", "Verbose field which we don't want to be serialized")); + String jsonString = new Gson().toJson(source); + assertEquals(expectedResult, jsonString); + } + + @Test + public void givenClassAnnotated_whenSerializing_thenCorrectWithoutNotAnnotatedFields() { + MyClassWithAnnotatedFields source = new MyClassWithAnnotatedFields(1L, "foo", "bar", new MySubClassWithAnnotatedFields(42L, "the answer", "Verbose field which we don't want to be serialized")); + Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation() + .create(); + String jsonString = gson.toJson(source); + + assertEquals(expectedResult, jsonString); + } + + @Test + public void givenExclusionStrategyByClassesAndFields_whenSerializing_thenFollowStrategy() { + MyClass source = new MyClass(1L, "foo", "bar", new MySubClass(42L, "the answer", "Verbose field which we don't want to be serialized")); + ExclusionStrategy strategy = new ExclusionStrategy() { + @Override + public boolean shouldSkipField(FieldAttributes field) { + if (field.getDeclaringClass() == MyClass.class && field.getName() + .equals("other")) + return true; + if (field.getDeclaringClass() == MySubClass.class && field.getName() + .equals("otherVerboseInfo")) + return true; + return false; + } + + @Override + public boolean shouldSkipClass(Class clazz) { + return false; + } + }; + + Gson gson = new GsonBuilder().addSerializationExclusionStrategy(strategy) + .create(); + String jsonString = gson.toJson(source); + + assertEquals(expectedResult, jsonString); + } + + @Test + public void givenExclusionStrategyByStartsWith_whenSerializing_thenFollowStrategy() { + MyClass source = new MyClass(1L, "foo", "bar", new MySubClass(42L, "the answer", "Verbose field which we don't want to be serialized")); + ExclusionStrategy strategy = new ExclusionStrategy() { + @Override + public boolean shouldSkipClass(Class clazz) { + return false; + } + + @Override + public boolean shouldSkipField(FieldAttributes field) { + return field.getName().startsWith("other"); + } + }; + Gson gson = new GsonBuilder().setExclusionStrategies(strategy) + .create(); + String jsonString = gson.toJson(source); + + assertEquals(expectedResult, jsonString); + } + + @Test + public void givenExclusionStrategyByCustomAnnotation_whenSerializing_thenFollowStrategy() { + MyClassWithCustomAnnotatedFields source = new MyClassWithCustomAnnotatedFields(1L, "foo", "bar", new MySubClassWithCustomAnnotatedFields(42L, "the answer", "Verbose field which we don't want to be serialized")); + ExclusionStrategy strategy = new ExclusionStrategy() { + @Override + public boolean shouldSkipClass(Class clazz) { + return false; + } + + @Override + public boolean shouldSkipField(FieldAttributes field) { + return field.getAnnotation(Exclude.class) != null; + } + + }; + + Gson gson = new GsonBuilder().setExclusionStrategies(strategy) + .create(); + String jsonString = gson.toJson(source); + assertEquals(expectedResult, jsonString); + } + +} \ No newline at end of file diff --git a/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java b/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java similarity index 97% rename from guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java rename to guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java index db82ea6da8..bd3a73c60f 100644 --- a/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java +++ b/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java @@ -11,7 +11,7 @@ import java.util.concurrent.ConcurrentHashMap; import static org.hamcrest.CoreMatchers.equalTo; -public class GuavaMiscUtilsTest { +public class GuavaMiscUtilsUnitTest { @Test public void whenHashingData_shouldReturnCorrectHashCode() throws Exception { int receivedData = 123; diff --git a/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java b/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java similarity index 98% rename from guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java rename to guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java index c7b8441b78..6f2d85bb04 100644 --- a/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java +++ b/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java @@ -12,7 +12,7 @@ import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInA import static org.hamcrest.core.AnyOf.anyOf; import static org.junit.Assert.*; -public class GuavaMiscUtilsTest { +public class GuavaMiscUtilsUnitTest { @Test public void whenGettingLazyStackTrace_ListShouldBeReturned() throws Exception { diff --git a/guava-modules/guava-21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java b/guava-modules/guava-21/src/test/java/com/baeldung/guava/zip/ZipCollectionUnitTest.java similarity index 98% rename from guava-modules/guava-21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java rename to guava-modules/guava-21/src/test/java/com/baeldung/guava/zip/ZipCollectionUnitTest.java index 866e09c6a0..e3d31d9404 100644 --- a/guava-modules/guava-21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java +++ b/guava-modules/guava-21/src/test/java/com/baeldung/guava/zip/ZipCollectionUnitTest.java @@ -13,7 +13,7 @@ import java.util.stream.IntStream; import static org.junit.Assert.assertEquals; -public class ZipCollectionTest { +public class ZipCollectionUnitTest { private List names; private List ages; diff --git a/guava/src/test/java/org/baeldung/guava/BloomFilterTest.java b/guava/src/test/java/org/baeldung/guava/BloomFilterUnitTest.java similarity index 97% rename from guava/src/test/java/org/baeldung/guava/BloomFilterTest.java rename to guava/src/test/java/org/baeldung/guava/BloomFilterUnitTest.java index d7c25b7c8d..ff3031a0cb 100644 --- a/guava/src/test/java/org/baeldung/guava/BloomFilterTest.java +++ b/guava/src/test/java/org/baeldung/guava/BloomFilterUnitTest.java @@ -9,7 +9,7 @@ import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; -public class BloomFilterTest { +public class BloomFilterUnitTest { @Test public void givenBloomFilter_whenAddNStringsToIt_thenShouldNotReturnAnyFalsePositive() { diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamTest.java b/guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamUnitTest.java similarity index 94% rename from guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamTest.java rename to guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamUnitTest.java index 5e96f3597c..7293b1631e 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamUnitTest.java @@ -7,7 +7,7 @@ import org.junit.Test; import com.google.common.io.CountingOutputStream; -public class GuavaCountingOutputStreamTest { +public class GuavaCountingOutputStreamUnitTest { public static final int MAX = 5; @Test(expected = RuntimeException.class) diff --git a/guest/spring-mvc/pom.xml b/guest/spring-mvc/pom.xml index 169b216ff9..da4d27b14d 100644 --- a/guest/spring-mvc/pom.xml +++ b/guest/spring-mvc/pom.xml @@ -27,28 +27,6 @@ - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - UTF-8 UTF-8 diff --git a/guest/spring-security/pom.xml b/guest/spring-security/pom.xml index 16e946d108..793df750de 100644 --- a/guest/spring-security/pom.xml +++ b/guest/spring-security/pom.xml @@ -45,28 +45,6 @@ - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - UTF-8 UTF-8 diff --git a/handling-spring-static-resources/pom.xml b/handling-spring-static-resources/pom.xml index da8f88ee22..771b37fb52 100644 --- a/handling-spring-static-resources/pom.xml +++ b/handling-spring-static-resources/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -37,7 +37,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -48,43 +48,43 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} @@ -190,8 +190,7 @@ 1.8 - 4.3.4.RELEASE - 4.2.0.RELEASE + 4.2.6.RELEASE 1.8.9 2.3.2-b02 diff --git a/hibernate5/README.md b/hibernate5/README.md index fb1319ed57..598f2b4913 100644 --- a/hibernate5/README.md +++ b/hibernate5/README.md @@ -10,3 +10,5 @@ - [JPA Attribute Converters](http://www.baeldung.com/jpa-attribute-converters) - [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob) - [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable) +- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) + diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java new file mode 100644 index 0000000000..f7b8e6bf6d --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.jpabootstrap.application; + +import com.baeldung.hibernate.jpabootstrap.config.JpaEntityManagerFactory; +import com.baeldung.hibernate.jpabootstrap.entities.User; +import javax.persistence.EntityManager; + +public class Application { + + public static void main(String[] args) { + EntityManager entityManager = getJpaEntityManager(); + User user = entityManager.find(User.class, 1); + System.out.println(user); + entityManager.getTransaction().begin(); + user.setName("John"); + user.setEmail("john@domain.com"); + entityManager.merge(user); + entityManager.getTransaction().commit(); + entityManager.getTransaction().begin(); + entityManager.persist(new User("Monica", "monica@domain.com")); + entityManager.getTransaction().commit(); + + // additional CRUD operations + + } + + private static class EntityManagerHolder { + private static final EntityManager ENTITY_MANAGER = new JpaEntityManagerFactory( + new Class[]{User.class}).getEntityManager(); + } + + public static EntityManager getJpaEntityManager() { + return EntityManagerHolder.ENTITY_MANAGER; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java new file mode 100644 index 0000000000..3852b44b64 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java @@ -0,0 +1,131 @@ +package com.baeldung.hibernate.jpabootstrap.config; + +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import javax.sql.DataSource; +import javax.persistence.SharedCacheMode; +import javax.persistence.ValidationMode; +import javax.persistence.spi.ClassTransformer; +import javax.persistence.spi.PersistenceUnitInfo; +import javax.persistence.spi.PersistenceUnitTransactionType; +import org.hibernate.jpa.HibernatePersistenceProvider; + +public class HibernatePersistenceUnitInfo implements PersistenceUnitInfo { + + public static final String JPA_VERSION = "2.1"; + private final String persistenceUnitName; + private PersistenceUnitTransactionType transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; + private final List managedClassNames; + private final List mappingFileNames = new ArrayList<>(); + private final Properties properties; + private DataSource jtaDataSource; + private DataSource nonjtaDataSource; + private final List transformers = new ArrayList<>(); + + public HibernatePersistenceUnitInfo(String persistenceUnitName, List managedClassNames, Properties properties) { + this.persistenceUnitName = persistenceUnitName; + this.managedClassNames = managedClassNames; + this.properties = properties; + } + + @Override + public String getPersistenceUnitName() { + return persistenceUnitName; + } + + @Override + public String getPersistenceProviderClassName() { + return HibernatePersistenceProvider.class.getName(); + } + + @Override + public PersistenceUnitTransactionType getTransactionType() { + return transactionType; + } + + public HibernatePersistenceUnitInfo setJtaDataSource(DataSource jtaDataSource) { + this.jtaDataSource = jtaDataSource; + this.nonjtaDataSource = null; + transactionType = PersistenceUnitTransactionType.JTA; + return this; + } + + @Override + public DataSource getJtaDataSource() { + return jtaDataSource; + } + + public HibernatePersistenceUnitInfo setNonJtaDataSource(DataSource nonJtaDataSource) { + this.nonjtaDataSource = nonJtaDataSource; + this.jtaDataSource = null; + transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; + return this; + } + + @Override + public DataSource getNonJtaDataSource() { + return nonjtaDataSource; + } + + @Override + public List getMappingFileNames() { + return mappingFileNames; + } + + @Override + public List getJarFileUrls() { + return Collections.emptyList(); + } + + @Override + public URL getPersistenceUnitRootUrl() { + return null; + } + + @Override + public List getManagedClassNames() { + return managedClassNames; + } + + @Override + public boolean excludeUnlistedClasses() { + return false; + } + + @Override + public SharedCacheMode getSharedCacheMode() { + return SharedCacheMode.UNSPECIFIED; + } + + @Override + public ValidationMode getValidationMode() { + return ValidationMode.AUTO; + } + + public Properties getProperties() { + return properties; + } + + @Override + public String getPersistenceXMLSchemaVersion() { + return JPA_VERSION; + } + + @Override + public ClassLoader getClassLoader() { + return Thread.currentThread().getContextClassLoader(); + } + + @Override + public void addTransformer(ClassTransformer transformer) { + transformers.add(transformer); + } + + @Override + public ClassLoader getNewTempClassLoader() { + return null; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java new file mode 100644 index 0000000000..bc1932af6f --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java @@ -0,0 +1,69 @@ +package com.baeldung.hibernate.jpabootstrap.config; + +import com.mysql.cj.jdbc.MysqlDataSource; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; +import javax.persistence.EntityManager; +import javax.sql.DataSource; +import javax.persistence.EntityManagerFactory; +import javax.persistence.spi.PersistenceUnitInfo; +import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; +import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor; + +public class JpaEntityManagerFactory { + + private final String DB_URL = "jdbc:mysql://databaseurl"; + private final String DB_USER_NAME = "username"; + private final String DB_PASSWORD = "password"; + private final Class[] entityClasses; + + public JpaEntityManagerFactory(Class[] entityClasses) { + this.entityClasses = entityClasses; + } + + public EntityManager getEntityManager() { + return getEntityManagerFactory().createEntityManager(); + } + + protected EntityManagerFactory getEntityManagerFactory() { + PersistenceUnitInfo persistenceUnitInfo = getPersistenceUnitInfo(getClass().getSimpleName()); + Map configuration = new HashMap<>(); + return new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration) + .build(); + } + + protected HibernatePersistenceUnitInfo getPersistenceUnitInfo(String name) { + return new HibernatePersistenceUnitInfo(name, getEntityClassNames(), getProperties()); + } + + protected List getEntityClassNames() { + return Arrays.asList(getEntities()) + .stream() + .map(Class::getName) + .collect(Collectors.toList()); + } + + protected Properties getProperties() { + Properties properties = new Properties(); + properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); + properties.put("hibernate.id.new_generator_mappings", false); + properties.put("hibernate.connection.datasource", getMysqlDataSource()); + return properties; + } + + protected Class[] getEntities() { + return entityClasses; + } + + protected DataSource getMysqlDataSource() { + MysqlDataSource mysqlDataSource = new MysqlDataSource(); + mysqlDataSource.setURL(DB_URL); + mysqlDataSource.setUser(DB_USER_NAME); + mysqlDataSource.setPassword(DB_PASSWORD); + return mysqlDataSource; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java new file mode 100644 index 0000000000..86ca1dfa19 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.jpabootstrap.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + private String name; + private String email; + + public User(){} + + public User(String name, String email) { + this.name = name; + this.email = email; + } + + public void setName(String name) { + this.name = name; + } + + public void setEmail(String email) { + this.email = email; + } + + public long getId() { + return id; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } +} \ No newline at end of file diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 8e4a9b28b7..b17ca2bfd9 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -6,10 +6,10 @@ hystrix - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/java-ee-8-security-api/app-auth-basic-store-db/pom.xml b/java-ee-8-security-api/app-auth-basic-store-db/pom.xml new file mode 100644 index 0000000000..7782fd0479 --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + + app-auth-basic-store-db + war + + + com.baeldung + java-ee-8-security-api + 1.0-SNAPSHOT + + + + 1.4.197 + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy + package + + copy + + + + + + + com.h2database + h2 + ${h2-version} + jar + + ${project.build.directory}/liberty/wlp/usr/servers/defaultServer/lib/global + + + + + + + + diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AdminServlet.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AdminServlet.java new file mode 100644 index 0000000000..32adbf1abb --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AdminServlet.java @@ -0,0 +1,22 @@ +package com.baeldung.javaee.security; + +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +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("/admin") +@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"admin_role"})) +public class AdminServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n"); + response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n"); + response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role")); + } +} \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AppConfig.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AppConfig.java new file mode 100644 index 0000000000..a16d944f5a --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AppConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition; +import javax.security.enterprise.authentication.mechanism.http.CustomFormAuthenticationMechanismDefinition; +import javax.security.enterprise.identitystore.DatabaseIdentityStoreDefinition; + +@BasicAuthenticationMechanismDefinition(realmName = "defaultRealm") +@DatabaseIdentityStoreDefinition( + dataSourceLookup = "java:comp/env/jdbc/securityDS", + callerQuery = "select password from users where username = ?", + groupsQuery = "select GROUPNAME from groups where username = ?" +) +@ApplicationScoped +public class AppConfig { +} diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/DatabaseSetupServlet.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/DatabaseSetupServlet.java new file mode 100644 index 0000000000..3658826e4d --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/DatabaseSetupServlet.java @@ -0,0 +1,59 @@ +package com.baeldung.javaee.security; + +import javax.annotation.Resource; +import javax.annotation.sql.DataSourceDefinition; +import javax.inject.Inject; +import javax.security.enterprise.identitystore.Pbkdf2PasswordHash; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +@DataSourceDefinition( + name = "java:comp/env/jdbc/securityDS", + className = "org.h2.jdbcx.JdbcDataSource", + url = "jdbc:h2:~/securityTest;MODE=Oracle" +) +@WebServlet(value = "/init", loadOnStartup = 0) +public class DatabaseSetupServlet extends HttpServlet { + + @Resource(lookup = "java:comp/env/jdbc/securityDS") + private DataSource dataSource; + + @Inject + private Pbkdf2PasswordHash passwordHash; + + @Override + public void init() throws ServletException { + super.init(); + initdb(); + } + + private void initdb() { + executeUpdate(dataSource, "DROP TABLE IF EXISTS USERS"); + executeUpdate(dataSource, "DROP TABLE IF EXISTS GROUPS"); + + executeUpdate(dataSource, "CREATE TABLE IF NOT EXISTS USERS(username VARCHAR(64) PRIMARY KEY, password VARCHAR(255))"); + executeUpdate(dataSource, "CREATE TABLE IF NOT EXISTS GROUPS(username VARCHAR(64), GROUPNAME VARCHAR(64))"); + + executeUpdate(dataSource, "INSERT INTO USERS VALUES('admin', '" + passwordHash.generate("passadmin".toCharArray()) + "')"); + executeUpdate(dataSource, "INSERT INTO USERS VALUES('user', '" + passwordHash.generate("passuser".toCharArray()) + "')"); + + executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('admin', 'admin_role')"); + executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('admin', 'user_role')"); + executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('user', 'user_role')"); + } + + private void executeUpdate(DataSource dataSource, String query) { + try (Connection connection = dataSource.getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(query)) { + statement.executeUpdate(); + } + } catch (SQLException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/UserServlet.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/UserServlet.java new file mode 100644 index 0000000000..548b5f6d85 --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/UserServlet.java @@ -0,0 +1,25 @@ +package com.baeldung.javaee.security; + +import javax.annotation.security.DeclareRoles; +import javax.inject.Inject; +import javax.security.enterprise.SecurityContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +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("/user") +@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"user_role"})) +public class UserServlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n"); + response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n"); + response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role")); + } +} diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/liberty/config/server.xml b/java-ee-8-security-api/app-auth-basic-store-db/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c49adff459 --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/liberty/config/server.xml @@ -0,0 +1,9 @@ + + + + webProfile-8.0 + + + + diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml new file mode 100644 index 0000000000..35a90621ae --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml @@ -0,0 +1,42 @@ + + + 4.0.0 + + app-auth-custom-form-store-custom + war + + + com.baeldung + java-ee-8-security-api + 1.0-SNAPSHOT + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + + diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/AppConfig.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/AppConfig.java new file mode 100644 index 0000000000..bba9fa36ce --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/AppConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.faces.annotation.FacesConfig; +import javax.security.enterprise.authentication.mechanism.http.CustomFormAuthenticationMechanismDefinition; +import javax.security.enterprise.authentication.mechanism.http.LoginToContinue; + + +@CustomFormAuthenticationMechanismDefinition( + loginToContinue = @LoginToContinue( + loginPage = "/login.xhtml", + errorPage = "/login-error.html" + ) +) +@ApplicationScoped +public class AppConfig { +} diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authentication.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authentication.java new file mode 100644 index 0000000000..54219f9750 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authentication.java @@ -0,0 +1,46 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.security.enterprise.credential.UsernamePasswordCredential; +import javax.security.enterprise.identitystore.CredentialValidationResult; +import javax.security.enterprise.identitystore.IdentityStore; +import java.util.*; + +import static javax.security.enterprise.identitystore.CredentialValidationResult.INVALID_RESULT; + +@ApplicationScoped +public class InMemoryIdentityStore4Authentication implements IdentityStore { + + private Map users = new HashMap<>(); + + public InMemoryIdentityStore4Authentication() { + //Init users + // from a file or hardcoded + init(); + } + + private void init() { + //user1 + users.put("user", "pass0"); + //user2 + users.put("admin", "pass1"); + } + + @Override + public int priority() { + return 70; + } + + @Override + public Set validationTypes() { + return EnumSet.of(ValidationType.VALIDATE); + } + + public CredentialValidationResult validate(UsernamePasswordCredential credential) { + String password = users.get(credential.getCaller()); + if (password != null && password.equals(credential.getPasswordAsString())) { + return new CredentialValidationResult(credential.getCaller()); + } + return INVALID_RESULT; + } +} diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authorization.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authorization.java new file mode 100644 index 0000000000..f088ab80b9 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authorization.java @@ -0,0 +1,46 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.security.enterprise.identitystore.CredentialValidationResult; +import javax.security.enterprise.identitystore.IdentityStore; +import java.util.*; + +@ApplicationScoped +class InMemoryIdentityStore4Authorization implements IdentityStore { + + private Map> userRoles = new HashMap<>(); + + public InMemoryIdentityStore4Authorization() { + //Init users + // from a file or hardcoded + init(); + } + + private void init() { + //user1 + List roles = new ArrayList<>(); + roles.add("USER_ROLE"); + userRoles.put("user", roles); + //user2 + roles = new ArrayList<>(); + roles.add("USER_ROLE"); + roles.add("ADMIN_ROLE"); + userRoles.put("admin", roles); + } + + @Override + public int priority() { + return 80; + } + + @Override + public Set validationTypes() { + return EnumSet.of(ValidationType.PROVIDE_GROUPS); + } + + @Override + public Set getCallerGroups(CredentialValidationResult validationResult) { + List roles = userRoles.get(validationResult.getCallerPrincipal().getName()); + return new HashSet<>(roles); + } +} diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/LoginBean.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/LoginBean.java new file mode 100644 index 0000000000..f8ee83432a --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/LoginBean.java @@ -0,0 +1,81 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.RequestScoped; +import javax.faces.annotation.FacesConfig; +import javax.faces.application.FacesMessage; +import javax.faces.context.FacesContext; +import javax.inject.Inject; +import javax.inject.Named; +import javax.security.enterprise.AuthenticationStatus; +import javax.security.enterprise.SecurityContext; +import javax.security.enterprise.credential.Credential; +import javax.security.enterprise.credential.Password; +import javax.security.enterprise.credential.UsernamePasswordCredential; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.validation.constraints.NotNull; + +import static javax.faces.application.FacesMessage.SEVERITY_ERROR; +import static javax.security.enterprise.AuthenticationStatus.SEND_CONTINUE; +import static javax.security.enterprise.AuthenticationStatus.SEND_FAILURE; +import static javax.security.enterprise.authentication.mechanism.http.AuthenticationParameters.withParams; + +@FacesConfig +@Named +@RequestScoped +public class LoginBean { + + @Inject + private SecurityContext securityContext; + + @Inject + private FacesContext facesContext; + + @NotNull + private String username; + + @NotNull + private String password; + + public void login() { + Credential credential = new UsernamePasswordCredential(username, new Password(password)); + AuthenticationStatus status = securityContext.authenticate( + getHttpRequestFromFacesContext(), + getHttpResponseFromFacesContext(), + withParams().credential(credential)); + if (status.equals(SEND_CONTINUE)) { + facesContext.responseComplete(); + } else if (status.equals(SEND_FAILURE)) { + facesContext.addMessage(null, + new FacesMessage(SEVERITY_ERROR, "Authentication failed", null)); + } + } + + private HttpServletRequest getHttpRequestFromFacesContext() { + return (HttpServletRequest) facesContext + .getExternalContext() + .getRequest(); + } + + private HttpServletResponse getHttpResponseFromFacesContext() { + return (HttpServletResponse) facesContext + .getExternalContext() + .getResponse(); + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/WelcomeServlet.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/WelcomeServlet.java new file mode 100644 index 0000000000..fb9c944140 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/WelcomeServlet.java @@ -0,0 +1,31 @@ +package com.baeldung.javaee.security; + +import javax.inject.Inject; +import javax.security.enterprise.SecurityContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +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("/welcome") +@ServletSecurity(@HttpConstraint(rolesAllowed = "USER_ROLE")) +public class WelcomeServlet extends HttpServlet { + + @Inject + private SecurityContext securityContext; + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + securityContext.hasAccessToWebResource("/protectedServlet", "GET"); + resp.getWriter().write("" + + "Authentication type :" + req.getAuthType() + "\n" + + "Caller Principal :" + securityContext.getCallerPrincipal() + "\n" + + "User in Role USER_ROLE :" + securityContext.isCallerInRole("USER_ROLE") + "\n" + + "User in Role ADMIN_ROLE :" + securityContext.isCallerInRole("ADMIN_ROLE") + "\n" + + ""); + } +} \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/liberty/config/server.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c49adff459 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/liberty/config/server.xml @@ -0,0 +1,9 @@ + + + + webProfile-8.0 + + + + diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/beans.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..2f4726a77e --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,7 @@ + + + diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/web.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..bd219bf983 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,27 @@ + + + + + javax.faces.validator.ENABLE_VALIDATE_WHOLE_BEAN + true + + + + javax.faces.ENABLE_CDI_RESOLVER_CHAIN + true + + + + Faces Servlet + javax.faces.webapp.FacesServlet + 1 + + + Faces Servlet + *.xhtml + + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login-error.html b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login-error.html new file mode 100644 index 0000000000..c540797b54 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login-error.html @@ -0,0 +1,10 @@ + + + + + Title + + +Custom Form Authentication Error + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login.xhtml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login.xhtml new file mode 100644 index 0000000000..48928b2513 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login.xhtml @@ -0,0 +1,32 @@ + + + + + + + +

+ Custom Form-based Authentication +

+ +
+

+ Username + +

+

+ Password + +

+

+ +

+
+ + + + diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/welcome.xhtml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/welcome.xhtml new file mode 100644 index 0000000000..d1a18db626 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/welcome.xhtml @@ -0,0 +1,19 @@ + + + + + + + +

+ Welcome !! +

+ + + + diff --git a/java-ee-8-security-api/app-auth-custom-no-store/pom.xml b/java-ee-8-security-api/app-auth-custom-no-store/pom.xml new file mode 100644 index 0000000000..32e20fb066 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + + app-auth-custom-no-store + war + + + com.baeldung + java-ee-8-security-api + 1.0-SNAPSHOT + + + + 1.4.197 + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy + package + + copy + + + + + + + com.h2database + h2 + ${h2-version} + jar + + ${project.build.directory}/liberty/wlp/usr/servers/defaultServer/lib/global + + + + + + + + diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AdminServlet.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AdminServlet.java new file mode 100644 index 0000000000..bef9e20038 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AdminServlet.java @@ -0,0 +1,28 @@ +package com.baeldung.javaee.security; + +import javax.inject.Inject; +import javax.security.enterprise.SecurityContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.security.Principal; + +@WebServlet("/admin") +@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"admin_role"})) +public class AdminServlet extends HttpServlet { + + @Inject + SecurityContext securityContext; + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.getWriter().append("getCallerPrincipal :" + securityContext.getCallerPrincipal() + "\n"); + response.getWriter().append("CustomPrincipal :" + securityContext.getPrincipalsByType(CustomPrincipal.class) + "\n"); + response.getWriter().append("Principal :" + securityContext.getPrincipalsByType(Principal.class) + "\n"); + } +} \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AppConfig.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AppConfig.java new file mode 100644 index 0000000000..e93360db4d --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/AppConfig.java @@ -0,0 +1,7 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; + +@ApplicationScoped +public class AppConfig { +} diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomAuthentication.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomAuthentication.java new file mode 100644 index 0000000000..9accf3c752 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomAuthentication.java @@ -0,0 +1,36 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.security.enterprise.AuthenticationException; +import javax.security.enterprise.AuthenticationStatus; +import javax.security.enterprise.authentication.mechanism.http.HttpAuthenticationMechanism; +import javax.security.enterprise.authentication.mechanism.http.HttpMessageContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.HashSet; + +@ApplicationScoped +public class CustomAuthentication implements HttpAuthenticationMechanism { + + @Override + public AuthenticationStatus validateRequest(HttpServletRequest httpServletRequest, + HttpServletResponse httpServletResponse, + HttpMessageContext httpMessageContext) throws AuthenticationException { + String username = httpServletRequest.getParameter("username"); + String password = httpServletRequest.getParameter("password"); + //Mocking UserDetail, but in real life, we can find it from a database. + UserDetail userDetail = findByUserNameAndPassword(username, password); + if (userDetail != null) { + return httpMessageContext.notifyContainerAboutLogin( + new CustomPrincipal(userDetail), + new HashSet<>(userDetail.getRoles())); + } + return httpMessageContext.responseUnauthorized(); + } + + private UserDetail findByUserNameAndPassword(String username, String password) { + UserDetail userDetail = new UserDetail("uid_10", username, password); + userDetail.addRole("admin_role"); + return userDetail; + } +} diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomPrincipal.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomPrincipal.java new file mode 100644 index 0000000000..5bd636ea62 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/CustomPrincipal.java @@ -0,0 +1,22 @@ +package com.baeldung.javaee.security; + +import java.security.Principal; + +public class CustomPrincipal implements Principal { + + private UserDetail userDetail; + + public CustomPrincipal(UserDetail userDetail) { + this.userDetail = userDetail; + } + + @Override + public String getName() { + return userDetail.getLogin(); + } + + @Override + public String toString() { + return this.getClass().getSimpleName() + ":" + getName(); + } +} diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/UserDetail.java b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/UserDetail.java new file mode 100644 index 0000000000..68e1df33c8 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/java/com/baeldung/javaee/security/UserDetail.java @@ -0,0 +1,38 @@ +package com.baeldung.javaee.security; + +import java.util.ArrayList; +import java.util.List; + +public class UserDetail { + private String uid; + private String login; + private String password; + private List roles = new ArrayList<>(); + //... + + UserDetail(String uid, String login, String password) { + this.uid = uid; + this.login = login; + this.password = password; + } + + public String getUid() { + return uid; + } + + public String getLogin() { + return login; + } + + public String getPassword() { + return password; + } + + public List getRoles() { + return roles; + } + + public void addRole(String role) { + roles.add(role); + } +} \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/liberty/config/server.xml b/java-ee-8-security-api/app-auth-custom-no-store/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c49adff459 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/liberty/config/server.xml @@ -0,0 +1,9 @@ + + + + webProfile-8.0 + + + + diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login-error.html b/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login-error.html new file mode 100644 index 0000000000..bd7263e0fb --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login-error.html @@ -0,0 +1,10 @@ + + + + + Title + + +Authentication Error + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login.html b/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login.html new file mode 100644 index 0000000000..3336eb5513 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-no-store/src/main/webapp/login.html @@ -0,0 +1,25 @@ + + + + + Title + + +

+ Form-based Authentication +

+
+

+ Username + +

+

+ Password + +

+

+ +

+
+ + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml b/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml new file mode 100644 index 0000000000..570b36add5 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + app-auth-form-store-ldap + war + + + com.baeldung + java-ee-8-security-api + 1.0-SNAPSHOT + + + + + com.unboundid + unboundid-ldapsdk + 4.0.4 + + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + + diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AdminServlet.java b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AdminServlet.java new file mode 100644 index 0000000000..32adbf1abb --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AdminServlet.java @@ -0,0 +1,22 @@ +package com.baeldung.javaee.security; + +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +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("/admin") +@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"admin_role"})) +public class AdminServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n"); + response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n"); + response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role")); + } +} \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AppConfig.java b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AppConfig.java new file mode 100644 index 0000000000..6fd9672e8a --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/AppConfig.java @@ -0,0 +1,22 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition; +import javax.security.enterprise.authentication.mechanism.http.LoginToContinue; +import javax.security.enterprise.identitystore.LdapIdentityStoreDefinition; + +@FormAuthenticationMechanismDefinition( + loginToContinue = @LoginToContinue( + loginPage = "/login.html", + errorPage = "/login-error.html" + ) +) +@LdapIdentityStoreDefinition( + url = "ldap://localhost:10389", + callerBaseDn = "ou=caller,dc=baeldung,dc=com", + groupSearchBase = "ou=group,dc=baeldung,dc=com", + groupSearchFilter = "(&(member=%s)(objectClass=groupOfNames))" +) +@ApplicationScoped +public class AppConfig { +} diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/LdapSetupServlet.java b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/LdapSetupServlet.java new file mode 100644 index 0000000000..e55fe0d2a7 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/LdapSetupServlet.java @@ -0,0 +1,45 @@ +package com.baeldung.javaee.security; + +import com.unboundid.ldap.listener.InMemoryDirectoryServer; +import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig; +import com.unboundid.ldap.listener.InMemoryListenerConfig; +import com.unboundid.ldap.sdk.LDAPException; +import com.unboundid.ldif.LDIFReader; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; + +@WebServlet(value = "/init-ldap", loadOnStartup = 1) +public class LdapSetupServlet extends HttpServlet { + + private InMemoryDirectoryServer inMemoryDirectoryServer; + + @Override + public void init() throws ServletException { + super.init(); + initLdap(); + System.out.println("@@@START_"); + } + + private void initLdap() { + try { + InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig("dc=baeldung,dc=com"); + config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("default", 10389)); + config.setSchema(null); + inMemoryDirectoryServer = new InMemoryDirectoryServer(config); + inMemoryDirectoryServer.importFromLDIF(true, + new LDIFReader(this.getClass().getResourceAsStream("/users.ldif"))); + inMemoryDirectoryServer.startListening(); + } catch (LDAPException e) { + e.printStackTrace(); + } + } + + @Override + public void destroy() { + super.destroy(); + inMemoryDirectoryServer.shutDown(true); + System.out.println("@@@END"); + } +} diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/UserServlet.java b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/UserServlet.java new file mode 100644 index 0000000000..9f14cd8817 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/java/com/baeldung/javaee/security/UserServlet.java @@ -0,0 +1,22 @@ +package com.baeldung.javaee.security; + +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +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("/user") +@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"user_role"})) +public class UserServlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n"); + response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n"); + response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role")); + } +} diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/liberty/config/server.xml b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c49adff459 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/liberty/config/server.xml @@ -0,0 +1,9 @@ + + + + webProfile-8.0 + + + + diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/resources/users.ldif b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/resources/users.ldif new file mode 100644 index 0000000000..538249aab7 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/resources/users.ldif @@ -0,0 +1,47 @@ +dn: dc=baeldung,dc=com +objectclass: top +objectclass: dcObject +objectclass: organization +dc: baeldung +o: baeldung + +dn: ou=caller,dc=baeldung,dc=com +objectclass: top +objectclass: organizationalUnit +ou: caller + +dn: ou=group,dc=baeldung,dc=com +objectclass: top +objectclass: organizationalUnit +ou: group + +dn: uid=admin,ou=caller,dc=baeldung,dc=com +objectclass: top +objectclass: uidObject +objectclass: person +uid: admin +cn: Administrator +sn: Admin +userPassword: passadmin + +dn: uid=user,ou=caller,dc=baeldung,dc=com +objectclass: top +objectclass: uidObject +objectclass: person +uid: user +cn: User +sn: User +userPassword: passuser + +dn: cn=admin_role,ou=group,dc=baeldung,dc=com +objectclass: top +objectclass: groupOfNames +cn: admin_role +member: uid=admin,ou=caller,dc=baeldung,dc=com + +dn: cn=user_role,ou=group,dc=baeldung,dc=com +objectclass: top +objectclass: groupOfNames +cn: user_role +member: uid=admin,ou=caller,dc=baeldung,dc=com +member: uid=user,ou=caller,dc=baeldung,dc=com diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login-error.html b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login-error.html new file mode 100644 index 0000000000..bd7263e0fb --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login-error.html @@ -0,0 +1,10 @@ + + + + + Title + + +Authentication Error + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login.html b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login.html new file mode 100644 index 0000000000..3336eb5513 --- /dev/null +++ b/java-ee-8-security-api/app-auth-form-store-ldap/src/main/webapp/login.html @@ -0,0 +1,25 @@ + + + + + Title + + +

+ Form-based Authentication +

+
+

+ Username + +

+

+ Password + +

+

+ +

+
+ + \ No newline at end of file diff --git a/java-ee-8-security-api/pom.xml b/java-ee-8-security-api/pom.xml new file mode 100644 index 0000000000..cdc288f469 --- /dev/null +++ b/java-ee-8-security-api/pom.xml @@ -0,0 +1,73 @@ + + + 4.0.0 + + com.baeldung + java-ee-8-security-api + 1.0-SNAPSHOT + pom + + + 1.8 + 1.8 + UTF-8 + + 9080 + 9443 + + 8.0 + 2.3 + 18.0.0.1 + 1.4.197 + + + + app-auth-basic-store-db + app-auth-form-store-ldap + app-auth-custom-form-store-custom + app-auth-custom-no-store + + + + + javax + javaee-web-api + ${javaee-version} + provided + + + + + + + maven-war-plugin + + false + pom.xml + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + ${liberty-maven-plugin.version} + + + + https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/nightly/2018-05-25_1422/openliberty-all-20180525-1300.zip + + + true + project + src/main/liberty/config/server.xml + true + + ${defaultHttpPort} + ${defaultHttpsPort} + + + + + + diff --git a/java-lite/src/test/java/app/models/ProductTest.java b/java-lite/src/test/java/app/models/ProductUnitTest.java similarity index 95% rename from java-lite/src/test/java/app/models/ProductTest.java rename to java-lite/src/test/java/app/models/ProductUnitTest.java index 5e5c6e8845..416df67d0e 100644 --- a/java-lite/src/test/java/app/models/ProductTest.java +++ b/java-lite/src/test/java/app/models/ProductUnitTest.java @@ -4,7 +4,7 @@ import org.javalite.activejdbc.Base; import org.junit.Assert; import org.junit.Test; -public class ProductTest { +public class ProductUnitTest { //@Test public void givenSavedProduct_WhenFindFirst_ThenSavedProductIsReturned() { diff --git a/java-spi/README.md b/java-spi/README.md new file mode 100644 index 0000000000..d2658c42fe --- /dev/null +++ b/java-spi/README.md @@ -0,0 +1,4 @@ + +### Relevant Articles: + +- [Java Service Provider Interface](http://www.baeldung.com/java-spi) diff --git a/java-vavr-stream/README.md b/java-vavr-stream/README.md new file mode 100644 index 0000000000..64299cde11 --- /dev/null +++ b/java-vavr-stream/README.md @@ -0,0 +1,5 @@ + +### Relevant Articles: + +- [Java Streams vs Vavr Streams](http://www.baeldung.com/vavr-java-streams) + diff --git a/java-websocket/pom.xml b/java-websocket/pom.xml index 461182e504..85078bd696 100644 --- a/java-websocket/pom.xml +++ b/java-websocket/pom.xml @@ -5,8 +5,6 @@ java-websocket war 0.0.1-SNAPSHOT - java-websocket Maven Webapp - http://maven.apache.org com.baeldung diff --git a/javax-servlets/README.md b/javax-servlets/README.md index 84330ac94c..de8a8e4498 100644 --- a/javax-servlets/README.md +++ b/javax-servlets/README.md @@ -2,3 +2,5 @@ - [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets) - [An MVC Example with Servlets and JSP](http://www.baeldung.com/mvc-servlet-jsp) - [Handling Cookies and a Session in a Java Servlet](http://www.baeldung.com/java-servlet-cookies-session) +- [Uploading Files with Servlets and JSP](http://www.baeldung.com/upload-file-servlet) +- [Example of Downloading File in a Servlet](http://www.baeldung.com/servlet-download-file) diff --git a/javax-servlets/pom.xml b/javax-servlets/pom.xml index 41a3bb69be..f64ce67a1f 100644 --- a/javax-servlets/pom.xml +++ b/javax-servlets/pom.xml @@ -1,75 +1,79 @@ - - 4.0.0 - javax-servlets - 1.0-SNAPSHOT + + 4.0.0 + javax-servlets + 1.0-SNAPSHOT - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - - - commons-fileupload - commons-fileupload - 1.3.3 - - - commons-io - commons-io - 2.6 - + + + + commons-fileupload + commons-fileupload + 1.3.3 + + + commons-io + commons-io + 2.6 + - - - javax.servlet - javax.servlet-api - 4.0.1 - - - javax.servlet.jsp.jstl - jstl-api - 1.2 - - - javax.servlet.jsp - javax.servlet.jsp-api - 2.3.1 - - - javax.servlet - jstl - 1.2 - + + + javax.servlet + javax.servlet-api + 4.0.1 + + + javax.servlet.jsp.jstl + jstl-api + 1.2 + + + javax.servlet.jsp + javax.servlet.jsp-api + 2.3.1 + + + javax.servlet + jstl + 1.2 + - - org.apache.httpcomponents - httpclient - ${org.apache.httpcomponents.version} - test - - - commons-logging - commons-logging - - - - - org.springframework - spring-test - ${spring-test.version} - test - - - - - 4.5.3 - 5.0.5.RELEASE - + + org.apache.httpcomponents + httpclient + ${org.apache.httpcomponents.version} + test + + + commons-logging + commons-logging + + + + + com.google.code.gson + gson + ${gson.version} + + + org.springframework + spring-test + ${spring-test.version} + test + + + + 4.5.3 + 5.0.5.RELEASE + 2.8.2 + \ No newline at end of file diff --git a/javax-servlets/src/main/java/com/baeldung/model/Employee.java b/javax-servlets/src/main/java/com/baeldung/model/Employee.java new file mode 100644 index 0000000000..698a598962 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/model/Employee.java @@ -0,0 +1,72 @@ +package com.baeldung.model; + +public class Employee { + + private int id; + private String name; + private String department; + private long salary; + + public Employee(int id, String name, String department, long salary) { + super(); + this.id = id; + this.name = name; + this.department = department; + this.salary = salary; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + id; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Employee other = (Employee) obj; + if (id != other.id) + return false; + return true; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDepartment() { + return department; + } + + public void setDepartment(String department) { + this.department = department; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + +} diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/DownloadServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/DownloadServlet.java new file mode 100644 index 0000000000..9bbf8f4095 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/DownloadServlet.java @@ -0,0 +1,35 @@ +package com.baeldung.servlets; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@WebServlet("/download") +public class DownloadServlet extends HttpServlet { + private final int ARBITARY_SIZE = 1048; + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + resp.setContentType("text/plain"); + resp.setHeader("Content-disposition", "attachment; filename=sample.txt"); + + OutputStream out = resp.getOutputStream(); + InputStream in = req.getServletContext().getResourceAsStream("/WEB-INF/sample.txt"); + + byte[] buffer = new byte[ARBITARY_SIZE]; + + int numBytesRead; + while ((numBytesRead = in.read(buffer)) > 0) { + out.write(buffer, 0, numBytesRead); + } + + in.close(); + out.flush(); + } +} diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/EmployeeServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/EmployeeServlet.java new file mode 100644 index 0000000000..dbc1a010f7 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/EmployeeServlet.java @@ -0,0 +1,34 @@ +package com.baeldung.servlets; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.baeldung.model.Employee; +import com.google.gson.Gson; + + +@WebServlet(name = "EmployeeServlet", urlPatterns = "/employeeServlet") +public class EmployeeServlet extends HttpServlet { + + private Gson gson = new Gson(); + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException { + + Employee employee = new Employee(1, "Karan", "IT", 5000); + String employeeJsonString = this.gson.toJson(employee); + + PrintWriter out = response.getWriter(); + response.setContentType("application/json"); + response.setCharacterEncoding("UTF-8"); + out.print(employeeJsonString); + out.flush(); + } + +} diff --git a/javax-servlets/src/main/webapp/sample.txt b/javax-servlets/src/main/webapp/sample.txt new file mode 100644 index 0000000000..bab4636a96 --- /dev/null +++ b/javax-servlets/src/main/webapp/sample.txt @@ -0,0 +1 @@ +nice simple text file \ No newline at end of file diff --git a/javax-servlets/src/test/java/com/baeldung/servlets/EmployeeServletIntegrationTest.java b/javax-servlets/src/test/java/com/baeldung/servlets/EmployeeServletIntegrationTest.java new file mode 100644 index 0000000000..4fe4908075 --- /dev/null +++ b/javax-servlets/src/test/java/com/baeldung/servlets/EmployeeServletIntegrationTest.java @@ -0,0 +1,54 @@ +package com.baeldung.servlets; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +import java.io.PrintWriter; +import java.io.StringWriter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import com.baeldung.model.Employee; +import com.google.gson.Gson; + + +@RunWith(MockitoJUnitRunner.class) +public class EmployeeServletIntegrationTest { + + @Mock + HttpServletRequest httpServletRequest; + + @Mock + HttpServletResponse httpServletResponse; + + Employee employee; + + @Test + public void whenPostRequestToEmployeeServlet_thenEmployeeReturnedAsJson() throws Exception { + + //Given + int id = 1; + String name = "Karan Khanna"; + String department = "IT"; + long salary = 5000; + employee = new Employee(id, name, department, salary); + + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + when(httpServletResponse.getWriter()).thenReturn(pw); + + EmployeeServlet employeeServlet = new EmployeeServlet(); + employeeServlet.doGet(httpServletRequest, httpServletResponse); + + String employeeJsonString = sw.getBuffer().toString().trim(); + Employee fetchedEmployee = new Gson().fromJson(employeeJsonString, Employee.class); + assertEquals(fetchedEmployee, employee); + } + +} diff --git a/jaxb/pom.xml b/jaxb/pom.xml index 26d7c8d362..f8e5ec0977 100644 --- a/jaxb/pom.xml +++ b/jaxb/pom.xml @@ -39,6 +39,11 @@ commons-lang3 ${commons-lang3.version}
+ + javax.activation + activation + 1.1 +
diff --git a/jaxb/src/main/resources/log4jstructuraldp.properties b/jaxb/src/main/resources/log4jstructuraldp.properties new file mode 100644 index 0000000000..5bc2bfe4b9 --- /dev/null +++ b/jaxb/src/main/resources/log4jstructuraldp.properties @@ -0,0 +1,9 @@ + +# Root logger +log4j.rootLogger=INFO, file, stdout + +# Write to console +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java b/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java index b2dde85c0f..77b7f1a0b3 100644 --- a/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java +++ b/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java @@ -44,7 +44,7 @@ public class JaxbIntegrationTest { File bookFile = new File(this.getClass().getResource("/book.xml").getFile()); String sampleBookXML = FileUtils.readFileToString(sampleBookFile, "UTF-8"); String marshallerBookXML = FileUtils.readFileToString(bookFile, "UTF-8"); - Assert.assertEquals(sampleBookXML, marshallerBookXML); + Assert.assertEquals(sampleBookXML.replace("\r", "").replace("\n", ""), marshallerBookXML.replace("\r", "").replace("\n", "")); } @Test diff --git a/jaxb/src/test/resources/book.xml b/jaxb/src/test/resources/book.xml new file mode 100644 index 0000000000..605d531b16 --- /dev/null +++ b/jaxb/src/test/resources/book.xml @@ -0,0 +1,5 @@ + + + Book1 + 2016-12-16T17:28:49.718Z + diff --git a/jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java b/jee-7/src/test/java/com/baeldung/convListVal/ConvListValLiveTest.java similarity index 98% rename from jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/convListVal/ConvListValLiveTest.java index caeba95e45..0d6fd295e6 100644 --- a/jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java +++ b/jee-7/src/test/java/com/baeldung/convListVal/ConvListValLiveTest.java @@ -22,7 +22,7 @@ import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; @RunWith(Arquillian.class) -public class ConvListValIntegrationTest { +public class ConvListValLiveTest { @ArquillianResource private URL deploymentUrl; diff --git a/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanLiveTest.java similarity index 98% rename from jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanLiveTest.java index 0e4c91ad67..41dde6549d 100644 --- a/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java +++ b/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanLiveTest.java @@ -21,7 +21,7 @@ import static org.hamcrest.Matchers.equalTo; @RunWith(Arquillian.class) -public class AutomaticTimerBeanIntegrationTest { +public class AutomaticTimerBeanLiveTest { //the @AutomaticTimerBean has a method called every 10 seconds //testing the difference ==> 100000 diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanLiveTest.java similarity index 96% rename from jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanLiveTest.java index 13cd1729db..350c094f38 100644 --- a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java +++ b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanLiveTest.java @@ -21,7 +21,7 @@ import static org.hamcrest.Matchers.is; @RunWith(Arquillian.class) -public class ProgrammaticAtFixedRateTimerBeanIntegrationTest { +public class ProgrammaticAtFixedRateTimerBeanLiveTest { final static long TIMEOUT = 1000; final static long TOLERANCE = 500l; diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java similarity index 97% rename from jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java index b90cb6d909..ad079c131b 100644 --- a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java +++ b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java @@ -19,7 +19,7 @@ import static org.hamcrest.Matchers.is; @RunWith(Arquillian.class) -public class ProgrammaticTimerBeanIntegrationTest { +public class ProgrammaticTimerBeanLiveTest { final static long TIMEOUT = 5000l; final static long TOLERANCE = 1000l; diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanLiveTest.java similarity index 96% rename from jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanLiveTest.java index e2e660f79b..974f0a285f 100644 --- a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java +++ b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanLiveTest.java @@ -21,7 +21,7 @@ import static org.hamcrest.Matchers.is; @RunWith(Arquillian.class) -public class ProgrammaticWithFixedDelayTimerBeanIntegrationTest { +public class ProgrammaticWithFixedDelayTimerBeanLiveTest { final static long TIMEOUT = 15000l; final static long TOLERANCE = 1000l; diff --git a/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanLiveTest.java similarity index 97% rename from jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanLiveTest.java index 580edade77..a4ed9ceb68 100644 --- a/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java +++ b/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanLiveTest.java @@ -20,7 +20,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @RunWith(Arquillian.class) -public class ScheduleTimerBeanIntegrationTest { +public class ScheduleTimerBeanLiveTest { private final static long TIMEOUT = 5000l; private final static long TOLERANCE = 1000l; diff --git a/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java similarity index 95% rename from jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java rename to jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java index 72ba4cc5b9..a6fd606e3f 100644 --- a/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java +++ b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java @@ -7,7 +7,7 @@ import org.junit.Ignore; import org.junit.Test; @Ignore -public class JerseyClientTest { +public class JerseyClientIntegrationTest { private static int HTTP_OK = 200; diff --git a/jhipster/jhipster-microservice/car-app/pom.xml b/jhipster/jhipster-microservice/car-app/pom.xml index 77e214234e..e5593bdbb9 100644 --- a/jhipster/jhipster-microservice/car-app/pom.xml +++ b/jhipster/jhipster-microservice/car-app/pom.xml @@ -3,10 +3,10 @@ 4.0.0 - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 com.car.app diff --git a/jhipster/jhipster-microservice/dealer-app/pom.xml b/jhipster/jhipster-microservice/dealer-app/pom.xml index beada8f064..3c21e0042f 100644 --- a/jhipster/jhipster-microservice/dealer-app/pom.xml +++ b/jhipster/jhipster-microservice/dealer-app/pom.xml @@ -3,10 +3,10 @@ 4.0.0 - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 com.dealer.app diff --git a/jhipster/jhipster-microservice/gateway-app/pom.xml b/jhipster/jhipster-microservice/gateway-app/pom.xml index d90addf51b..42808e26ce 100644 --- a/jhipster/jhipster-microservice/gateway-app/pom.xml +++ b/jhipster/jhipster-microservice/gateway-app/pom.xml @@ -3,10 +3,10 @@ 4.0.0 - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 com.gateway diff --git a/jhipster/jhipster-monolithic/pom.xml b/jhipster/jhipster-monolithic/pom.xml index fc8e8353b4..c8c9578fd6 100644 --- a/jhipster/jhipster-monolithic/pom.xml +++ b/jhipster/jhipster-monolithic/pom.xml @@ -3,10 +3,10 @@ 4.0.0 - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 com.baeldung diff --git a/jjwt/pom.xml b/jjwt/pom.xml index 51d4dcf1c0..2aa52b8818 100644 --- a/jjwt/pom.xml +++ b/jjwt/pom.xml @@ -10,10 +10,10 @@ Exercising the JJWT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/jmeter/pom.xml b/jmeter/pom.xml index bb5769ef57..5f9509f0be 100644 --- a/jmeter/pom.xml +++ b/jmeter/pom.xml @@ -9,10 +9,10 @@ Intro to Performance testing using JMeter - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/jni/README.md b/jni/README.md new file mode 100644 index 0000000000..663cafb0c0 --- /dev/null +++ b/jni/README.md @@ -0,0 +1,4 @@ + +### Relevant Articles: + +- [Guide to JNI (Java Native Interface)](http://www.baeldung.com/jni) diff --git a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java similarity index 98% rename from jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java rename to jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java index c0fb5485aa..8bc8c854da 100644 --- a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java +++ b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java @@ -15,7 +15,7 @@ import org.junit.Test; import com.baeldung.jpa.model.Car; -public class StoredProcedureIntegrationTest { +public class StoredProcedureLiveTest { private static EntityManagerFactory factory = null; private static EntityManager entityManager = null; diff --git a/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceTest.java b/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceIntegrationTest.java similarity index 98% rename from json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceTest.java rename to json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceIntegrationTest.java index 067e5cf8ce..85e5d3e826 100644 --- a/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceTest.java +++ b/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceIntegrationTest.java @@ -17,7 +17,7 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; -public class ServiceTest { +public class ServiceIntegrationTest { private InputStream jsonInputStream = this.getClass() .getClassLoader() .getResourceAsStream("intro_service.json"); diff --git a/kotlin-js/README.md b/kotlin-js/README.md new file mode 100644 index 0000000000..445ad6da9a --- /dev/null +++ b/kotlin-js/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Kotlin and Javascript](http://www.baeldung.com/kotlin-javascript) diff --git a/libraries-data/src/test/java/com/baeldung/jcache/CacheLoaderTest.java b/libraries-data/src/test/java/com/baeldung/jcache/CacheLoaderIntegrationTest.java similarity index 97% rename from libraries-data/src/test/java/com/baeldung/jcache/CacheLoaderTest.java rename to libraries-data/src/test/java/com/baeldung/jcache/CacheLoaderIntegrationTest.java index 93ff3f09a3..8017418eba 100644 --- a/libraries-data/src/test/java/com/baeldung/jcache/CacheLoaderTest.java +++ b/libraries-data/src/test/java/com/baeldung/jcache/CacheLoaderIntegrationTest.java @@ -13,7 +13,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -public class CacheLoaderTest { +public class CacheLoaderIntegrationTest { private static final String CACHE_NAME = "SimpleCache"; diff --git a/libraries-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java index 61c98d0126..fd1e9c29a9 100644 --- a/libraries-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java +++ b/libraries-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java @@ -15,12 +15,13 @@ import static org.junit.Assert.assertEquals; public class EntryProcessorIntegrationTest { private static final String CACHE_NAME = "MyCache"; + private static final String CACHE_PROVIDER_NAME = "com.hazelcast.cache.HazelcastCachingProvider"; private Cache cache; @Before public void instantiateCache() { - CachingProvider cachingProvider = Caching.getCachingProvider(); + CachingProvider cachingProvider = Caching.getCachingProvider(CACHE_PROVIDER_NAME); CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration config = new MutableConfiguration<>(); this.cache = cacheManager.createCache(CACHE_NAME, config); @@ -29,7 +30,7 @@ public class EntryProcessorIntegrationTest { @After public void tearDown() { - Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME); + Caching.getCachingProvider(CACHE_PROVIDER_NAME).getCacheManager().destroyCache(CACHE_NAME); } @Test diff --git a/libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java index fcbfbe6111..512a75ec61 100644 --- a/libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java +++ b/libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java @@ -17,6 +17,7 @@ import static org.junit.Assert.assertEquals; public class EventListenerIntegrationTest { private static final String CACHE_NAME = "MyCache"; + private static final String CACHE_PROVIDER_NAME = "com.hazelcast.cache.HazelcastCachingProvider"; private Cache cache; private SimpleCacheEntryListener listener; @@ -24,7 +25,7 @@ public class EventListenerIntegrationTest { @Before public void setup() { - CachingProvider cachingProvider = Caching.getCachingProvider(); + CachingProvider cachingProvider = Caching.getCachingProvider(CACHE_PROVIDER_NAME); CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration config = new MutableConfiguration(); this.cache = cacheManager.createCache("MyCache", config); @@ -33,7 +34,7 @@ public class EventListenerIntegrationTest { @After public void tearDown() { - Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME); + Caching.getCachingProvider(CACHE_PROVIDER_NAME).getCacheManager().destroyCache(CACHE_NAME); } @Test diff --git a/libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java index fac3d32bcb..33521469fa 100644 --- a/libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java +++ b/libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java @@ -14,7 +14,7 @@ public class JCacheIntegrationTest { @Test public void instantiateCache() { - CachingProvider cachingProvider = Caching.getCachingProvider(); + CachingProvider cachingProvider = Caching.getCachingProvider("com.hazelcast.cache.HazelcastCachingProvider"); CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration config = new MutableConfiguration<>(); Cache cache = cacheManager.createCache("simpleCache", config); diff --git a/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml b/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml index a1951f09b7..6e5d212fb8 100644 --- a/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml +++ b/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml @@ -2,6 +2,6 @@ - + \ No newline at end of file diff --git a/libraries/README.md b/libraries/README.md index bde13401e9..3ef6303c88 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -79,6 +79,8 @@ - [Java Concurrency Utility with JCTools](http://www.baeldung.com/java-concurrency-jc-tools) - [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils) - [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel) +- [Creating REST Microservices with Javalin](http://www.baeldung.com/javalin-rest-microservices) + The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/libraries/pom.xml b/libraries/pom.xml index 678ba3279c..4f90d63d93 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -698,6 +698,17 @@ jctools-core ${jctools.version} + + + org.apache.commons + commons-math3 + ${common-math3-version} + + + org.knowm.xchart + xchart + ${xchart-version} + @@ -910,6 +921,8 @@ 0.9.4.0006L 2.1.2 2.5.11 + 3.6.1 + 3.5.2
\ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/math3/Histogram.java b/libraries/src/main/java/com/baeldung/commons/math3/Histogram.java new file mode 100644 index 0000000000..a8c15887be --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/math3/Histogram.java @@ -0,0 +1,97 @@ +package com.baeldung.commons.math3; + +import org.apache.commons.math3.stat.Frequency; +import org.knowm.xchart.CategoryChart; +import org.knowm.xchart.CategoryChartBuilder; +import org.knowm.xchart.SwingWrapper; +import org.knowm.xchart.style.Styler; + +import java.util.*; + +public class Histogram { + + private Map distributionMap; + private int classWidth; + + public Histogram() { + + distributionMap = new TreeMap(); + classWidth = 10; + Map distributionMap = processRawData(); + List yData = new ArrayList(); + yData.addAll(distributionMap.values()); + List xData = Arrays.asList(distributionMap.keySet().toArray()); + + CategoryChart chart = buildChart(xData, yData); + new SwingWrapper<>(chart).displayChart(); + + } + + private CategoryChart buildChart(List xData, List yData) { + + // Create Chart + CategoryChart chart = new CategoryChartBuilder().width(800).height(600) + .title("Age Distribution") + .xAxisTitle("Age Group") + .yAxisTitle("Frequency") + .build(); + + chart.getStyler().setLegendPosition(Styler.LegendPosition.InsideNW); + chart.getStyler().setAvailableSpaceFill(0.99); + chart.getStyler().setOverlapped(true); + + chart.addSeries("age group", xData, yData); + + return chart; + } + + private Map processRawData() { + + List datasetList = Arrays.asList( + 36, 25, 38, 46, 55, 68, 72, + 55, 36, 38, 67, 45, 22, 48, + 91, 46, 52, 61, 58, 55); + Frequency frequency = new Frequency(); + datasetList.forEach(d -> frequency.addValue(Double.parseDouble(d.toString()))); + + datasetList.stream() + .map(d -> Double.parseDouble(d.toString())) + .distinct() + .forEach(observation -> { + long observationFrequency = frequency.getCount(observation); + int upperBoundary = (observation > classWidth) + ? Math.multiplyExact( (int) Math.ceil(observation / classWidth), classWidth) + : classWidth; + int lowerBoundary = (upperBoundary > classWidth) + ? Math.subtractExact(upperBoundary, classWidth) + : 0; + String bin = lowerBoundary + "-" + upperBoundary; + + updateDistributionMap(lowerBoundary, bin, observationFrequency); + + }); + + return distributionMap; + } + + private void updateDistributionMap(int lowerBoundary, String bin, long observationFrequency) { + + int prevLowerBoundary = (lowerBoundary > classWidth) ? lowerBoundary - classWidth : 0; + String prevBin = prevLowerBoundary + "-" + lowerBoundary; + if(!distributionMap.containsKey(prevBin)) + distributionMap.put(prevBin, 0); + + if(!distributionMap.containsKey(bin)) { + distributionMap.put(bin, observationFrequency); + } + else { + long oldFrequency = Long.parseLong(distributionMap.get(bin).toString()); + distributionMap.replace(bin, oldFrequency + observationFrequency); + } + } + + public static void main(String[] args) { + new Histogram(); + } + +} diff --git a/logging-modules/README.md b/logging-modules/README.md index a589b1245c..0f12d7eb22 100644 --- a/logging-modules/README.md +++ b/logging-modules/README.md @@ -5,4 +5,4 @@ - [Creating a Custom Logback Appender](http://www.baeldung.com/custom-logback-appender) - [Get Log Output in JSON Format](http://www.baeldung.com/java-log-json-output) -- [A Guide To Logback](http://www.baeldung.com/a-guide-to-logback) +- [A Guide To Logback](http://www.baeldung.com/logback) diff --git a/logging-modules/log-mdc/pom.xml b/logging-modules/log-mdc/pom.xml index 7628c708e9..6cfef12980 100644 --- a/logging-modules/log-mdc/pom.xml +++ b/logging-modules/log-mdc/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../../parent-spring + ../../parent-spring-4 @@ -80,7 +80,6 @@ - 4.3.4.RELEASE 1.2.17 2.7 3.3.6 diff --git a/logging-modules/log4j2/README.md b/logging-modules/log4j2/README.md index 57ca4df21b..e209c6f035 100644 --- a/logging-modules/log4j2/README.md +++ b/logging-modules/log4j2/README.md @@ -2,3 +2,4 @@ - [Intro to Log4j2 – Appenders, Layouts and Filters](http://www.baeldung.com/log4j2-appenders-layouts-filters) - [Log4j 2 and Lambda Expressions](http://www.baeldung.com/log4j-2-lazy-logging) +- [Programmatic Configuration with Log4j 2](http://www.baeldung.com/log4j2-programmatic-config) diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/Log4j2Test.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/Log4j2BaseIntegrationTest.java similarity index 92% rename from logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/Log4j2Test.java rename to logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/Log4j2BaseIntegrationTest.java index abd92a2202..6b68977fd6 100644 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/Log4j2Test.java +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/Log4j2BaseIntegrationTest.java @@ -6,7 +6,7 @@ import org.junit.AfterClass; import java.lang.reflect.Field; -public class Log4j2Test { +public class Log4j2BaseIntegrationTest { @AfterClass public static void tearDown() throws Exception { Field factories = ConfigurationFactory.class.getDeclaredField("factories"); diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/setconfigurationfactory/SetConfigurationFactoryTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/setconfigurationfactory/SetConfigurationFactoryIntegrationTest.java similarity index 89% rename from logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/setconfigurationfactory/SetConfigurationFactoryTest.java rename to logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/setconfigurationfactory/SetConfigurationFactoryIntegrationTest.java index 2f9a837424..db3b0780a2 100644 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/setconfigurationfactory/SetConfigurationFactoryTest.java +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/setconfigurationfactory/SetConfigurationFactoryIntegrationTest.java @@ -4,7 +4,7 @@ **/ package com.baeldung.logging.log4j2.setconfigurationfactory; -import com.baeldung.logging.log4j2.Log4j2Test; +import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest; import com.baeldung.logging.log4j2.simpleconfiguration.CustomConfigurationFactory; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -17,7 +17,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) -public class SetConfigurationFactoryTest extends Log4j2Test { +public class SetConfigurationFactoryIntegrationTest extends Log4j2BaseIntegrationTest { @BeforeClass public static void setUp() { CustomConfigurationFactory customConfigurationFactory = new CustomConfigurationFactory(); diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfiguration/SimpleConfigurationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfiguration/SimpleConfigurationIntegrationTest.java similarity index 88% rename from logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfiguration/SimpleConfigurationTest.java rename to logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfiguration/SimpleConfigurationIntegrationTest.java index 02330a808b..25f0736df5 100644 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfiguration/SimpleConfigurationTest.java +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfiguration/SimpleConfigurationIntegrationTest.java @@ -4,7 +4,7 @@ **/ package com.baeldung.logging.log4j2.simpleconfiguration; -import com.baeldung.logging.log4j2.Log4j2Test; +import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; @@ -13,7 +13,7 @@ import org.apache.logging.log4j.core.config.plugins.util.PluginManager; import org.junit.BeforeClass; import org.junit.Test; -public class SimpleConfigurationTest extends Log4j2Test { +public class SimpleConfigurationIntegrationTest extends Log4j2BaseIntegrationTest { @BeforeClass public static void setUp() { PluginManager.addPackage("com.baeldung.logging.log4j2.simpleconfiguration"); diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfigurator/SimpleConfiguratorTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfigurator/SimpleConfiguratorIntegrationTest.java similarity index 92% rename from logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfigurator/SimpleConfiguratorTest.java rename to logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfigurator/SimpleConfiguratorIntegrationTest.java index 03bf996120..49cde67303 100644 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfigurator/SimpleConfiguratorTest.java +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfigurator/SimpleConfiguratorIntegrationTest.java @@ -5,7 +5,7 @@ package com.baeldung.logging.log4j2.simpleconfigurator; -import com.baeldung.logging.log4j2.Log4j2Test; +import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.appender.ConsoleAppender; import org.apache.logging.log4j.core.config.Configurator; @@ -18,7 +18,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) -public class SimpleConfiguratorTest extends Log4j2Test { +public class SimpleConfiguratorIntegrationTest extends Log4j2BaseIntegrationTest { @Test public void givenDefaultLog4j2Environment_whenProgrammaticallyConfigured_thenLogsCorrectly() { diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java similarity index 90% rename from logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutTest.java rename to logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java index 7a6fbf999c..53634002a0 100644 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutTest.java +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java @@ -6,15 +6,16 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; -import com.baeldung.logging.log4j2.Log4j2Test; +import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Before; import org.junit.Test; + import com.fasterxml.jackson.databind.ObjectMapper; -public class JSONLayoutTest extends Log4j2Test { +public class JSONLayoutIntegrationTest extends Log4j2BaseIntegrationTest { private static Logger logger; private ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream(); diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/XMLConfigLogTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/XMLConfigLogIntegrationTest.java similarity index 91% rename from logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/XMLConfigLogTest.java rename to logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/XMLConfigLogIntegrationTest.java index 41f733804a..d705b50b1a 100644 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/XMLConfigLogTest.java +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/XMLConfigLogIntegrationTest.java @@ -7,7 +7,7 @@ package com.baeldung.logging.log4j2.xmlconfiguration; -import com.baeldung.logging.log4j2.Log4j2Test; +import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; @@ -17,7 +17,7 @@ import org.apache.logging.log4j.core.config.plugins.util.PluginManager; import org.junit.BeforeClass; import org.junit.Test; -public class XMLConfigLogTest extends Log4j2Test { +public class XMLConfigLogIntegrationTest extends Log4j2BaseIntegrationTest { @BeforeClass public static void setUp() { diff --git a/logging-modules/logback/src/test/java/com/baeldung/logback/JSONLayoutTest.java b/logging-modules/logback/src/test/java/com/baeldung/logback/JSONLayoutIntegrationTest.java similarity index 96% rename from logging-modules/logback/src/test/java/com/baeldung/logback/JSONLayoutTest.java rename to logging-modules/logback/src/test/java/com/baeldung/logback/JSONLayoutIntegrationTest.java index ca3c4b3457..06962c1ea1 100644 --- a/logging-modules/logback/src/test/java/com/baeldung/logback/JSONLayoutTest.java +++ b/logging-modules/logback/src/test/java/com/baeldung/logback/JSONLayoutIntegrationTest.java @@ -13,7 +13,7 @@ import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; -public class JSONLayoutTest { +public class JSONLayoutIntegrationTest { private static Logger logger; private ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream(); diff --git a/logging-modules/logback/src/test/java/com/baeldung/logback/LogbackTests.java b/logging-modules/logback/src/test/java/com/baeldung/logback/LogbackIntegrationTest.java similarity index 96% rename from logging-modules/logback/src/test/java/com/baeldung/logback/LogbackTests.java rename to logging-modules/logback/src/test/java/com/baeldung/logback/LogbackIntegrationTest.java index 85201965dc..2f4553df41 100644 --- a/logging-modules/logback/src/test/java/com/baeldung/logback/LogbackTests.java +++ b/logging-modules/logback/src/test/java/com/baeldung/logback/LogbackIntegrationTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import ch.qos.logback.classic.Logger; import org.slf4j.LoggerFactory; -public class LogbackTests { +public class LogbackIntegrationTest { @Test public void givenLogHierarchy_MessagesFiltered() { @@ -51,7 +51,7 @@ public class LogbackTests { @Test public void givenParameters_ValuesLogged() { - Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(LogbackTests.class); + Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(LogbackIntegrationTest.class); String message = "This is a String"; Integer zero = 0; diff --git a/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderTest.java b/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderUnitTest.java similarity index 98% rename from logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderTest.java rename to logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderUnitTest.java index a5a938a923..742b219a27 100644 --- a/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderTest.java +++ b/logging-modules/logback/src/test/java/com/baeldung/logback/MapAppenderUnitTest.java @@ -11,7 +11,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -public class MapAppenderTest { +public class MapAppenderUnitTest { private LoggerContext ctx; diff --git a/lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchTest.java b/lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchIntegrationTest.java similarity index 95% rename from lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchTest.java rename to lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchIntegrationTest.java index 4345057ff7..7d9bfb9cf5 100644 --- a/lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchTest.java +++ b/lucene/src/test/java/com/baeldung/lucene/LuceneFileSearchIntegrationTest.java @@ -12,7 +12,7 @@ import org.apache.lucene.store.FSDirectory; import org.junit.Assert; import org.junit.Test; -public class LuceneFileSearchTest { +public class LuceneFileSearchIntegrationTest { @Test public void givenSearchQueryWhenFetchedFileNamehenCorrect() throws IOException, URISyntaxException { diff --git a/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchTest.java b/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchIntegrationTest.java similarity index 99% rename from lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchTest.java rename to lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchIntegrationTest.java index acf688cb99..27893762fd 100644 --- a/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchTest.java +++ b/lucene/src/test/java/com/baeldung/lucene/LuceneInMemorySearchIntegrationTest.java @@ -20,7 +20,7 @@ import org.apache.lucene.util.BytesRef; import org.junit.Assert; import org.junit.Test; -public class LuceneInMemorySearchTest { +public class LuceneInMemorySearchIntegrationTest { @Test public void givenSearchQueryWhenFetchedDocumentThenCorrect() { diff --git a/maven/src/test/java/com/baeldung/maven/plugins/DataTest.java b/maven/src/test/java/com/baeldung/maven/plugins/DataUnitTest.java similarity index 90% rename from maven/src/test/java/com/baeldung/maven/plugins/DataTest.java rename to maven/src/test/java/com/baeldung/maven/plugins/DataUnitTest.java index 3f03b6f5d6..197f977fec 100644 --- a/maven/src/test/java/com/baeldung/maven/plugins/DataTest.java +++ b/maven/src/test/java/com/baeldung/maven/plugins/DataUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import com.baeldung.maven.plugins.Data; -public class DataTest { +public class DataUnitTest { @Test public void whenDataObjectIsNotCreated_thenItIsNull() { Data data = null; diff --git a/mesos-marathon/pom.xml b/mesos-marathon/pom.xml index 2b7a238ee8..77d13cd5c6 100644 --- a/mesos-marathon/pom.xml +++ b/mesos-marathon/pom.xml @@ -7,10 +7,10 @@ 0.0.1-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java b/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasIntegrationTest.java similarity index 99% rename from metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java rename to metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasIntegrationTest.java index b76dc40ba0..e7f3d7ec72 100644 --- a/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasIntegrationTest.java @@ -39,7 +39,7 @@ import com.netflix.spectator.atlas.AtlasConfig; /** * @author aiet */ -public class MicrometerAtlasTest { +public class MicrometerAtlasIntegrationTest { private AtlasConfig atlasConfig; diff --git a/msf4j/README.md b/msf4j/README.md new file mode 100644 index 0000000000..19e611832c --- /dev/null +++ b/msf4j/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to Java Microservices with MSF4J](http://www.baeldung.com/spring-boot-war-tomcat-deploy) diff --git a/msf4j/pom.xml b/msf4j/pom.xml new file mode 100644 index 0000000000..f691d746b7 --- /dev/null +++ b/msf4j/pom.xml @@ -0,0 +1,32 @@ + + + + org.wso2.msf4j + msf4j-service + 2.6.0 + + 4.0.0 + + com.baeldung.msf4j + msf4j + 0.0.1-SNAPSHOT + WSO2 MSF4J Microservice + + + com.baeldung.msf4j.msf4jintro.Application + + + + org.wso2.msf4j + msf4j-spring + 2.6.1 + + + org.wso2.msf4j + msf4j-mustache-template + 2.6.1 + + + + \ No newline at end of file diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Application.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Application.java new file mode 100644 index 0000000000..c4cf136536 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Application.java @@ -0,0 +1,11 @@ +package com.baeldung.msf4j.msf4japi; + +import org.wso2.msf4j.MicroservicesRunner; + +public class Application { + public static void main(String[] args) { + new MicroservicesRunner() + .deploy(new MenuService()) + .start(); + } +} \ No newline at end of file diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Meal.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Meal.java new file mode 100644 index 0000000000..d17a7a1034 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Meal.java @@ -0,0 +1,20 @@ +package com.baeldung.msf4j.msf4japi; + +public class Meal { + private String name; + private Float price; + + public Meal(String name, Float price) { + this.name = name; + this.price = price; + } + + public String getName() { + return name; + } + + public Float getPrice() { + return price; + } + +} diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/MenuService.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/MenuService.java new file mode 100644 index 0000000000..4f880a1393 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/MenuService.java @@ -0,0 +1,78 @@ +package com.baeldung.msf4j.msf4japi; + +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; + +import com.google.gson.Gson; + +@Path("/menu") +public class MenuService { + + private List meals = new ArrayList(); + + public MenuService() { + meals.add(new Meal("Java beans",42.0f)); + } + + @GET + @Path("/") + @Produces({ "application/json" }) + public Response index() { + return Response.ok() + .entity(meals) + .build(); + } + + @GET + @Path("/{id}") + @Produces({ "application/json" }) + public Response meal(@PathParam("id") int id) { + return Response.ok() + .entity(meals.get(id)) + .build(); + } + + + @POST + @Path("/") + @Consumes("application/json") + @Produces({ "application/json" }) + public Response create(Meal meal) { + meals.add(meal); + return Response.ok() + .entity(meal) + .build(); + } + + @PUT + @Path("/{id}") + @Consumes("application/json") + @Produces({ "application/json" }) + public Response update(@PathParam("id") int id, Meal meal) { + meals.set(id, meal); + return Response.ok() + .entity(meal) + .build(); + } + + @DELETE + @Path("/{id}") + @Produces({ "application/json" }) + public Response delete(@PathParam("id") int id) { + Meal meal = meals.get(id); + meals.remove(id); + return Response.ok() + .entity(meal) + .build(); + } +} diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/Application.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/Application.java new file mode 100644 index 0000000000..dc4a060056 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/Application.java @@ -0,0 +1,11 @@ +package com.baeldung.msf4j.msf4jintro; + +import org.wso2.msf4j.MicroservicesRunner; + +public class Application { + public static void main(String[] args) { + new MicroservicesRunner() + .deploy(new SimpleService()) + .start(); + } +} \ No newline at end of file diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/SimpleService.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/SimpleService.java new file mode 100644 index 0000000000..bcb52859b5 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/SimpleService.java @@ -0,0 +1,21 @@ +package com.baeldung.msf4j.msf4jintro; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; + +@Path("/") +public class SimpleService { + + @GET + public String index() { + return "Default content"; + } + + @GET + @Path("/say/{name}") + public String say(@PathParam("name") String name) { + return "Hello " + name; + } + +} diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/Application.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/Application.java new file mode 100644 index 0000000000..2a5232a7e6 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/Application.java @@ -0,0 +1,10 @@ +package com.baeldung.msf4j.msf4jspring; + +import org.wso2.msf4j.spring.MSF4JSpringApplication; + +public class Application { + + public static void main(String[] args) { + MSF4JSpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/configuration/PortConfiguration.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/configuration/PortConfiguration.java new file mode 100644 index 0000000000..c3313fc3b1 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/configuration/PortConfiguration.java @@ -0,0 +1,15 @@ +package com.baeldung.msf4j.msf4jspring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.wso2.msf4j.spring.transport.HTTPTransportConfig; + +@Configuration +public class PortConfiguration { + + @Bean + public HTTPTransportConfig http() { + return new HTTPTransportConfig(9090); + } + +} \ No newline at end of file diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/domain/Meal.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/domain/Meal.java new file mode 100644 index 0000000000..99de0abc4c --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/domain/Meal.java @@ -0,0 +1,20 @@ +package com.baeldung.msf4j.msf4jspring.domain; + +public class Meal { + private String name; + private Float price; + + public Meal(String name, Float price) { + this.name = name; + this.price = price; + } + + public String getName() { + return name; + } + + public Float getPrice() { + return price; + } + +} diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/repositories/MealRepository.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/repositories/MealRepository.java new file mode 100644 index 0000000000..4d9e54348e --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/repositories/MealRepository.java @@ -0,0 +1,37 @@ +package com.baeldung.msf4j.msf4jspring.repositories; + +import java.util.ArrayList; +import java.util.List; +import org.springframework.stereotype.Component; +import com.baeldung.msf4j.msf4jspring.domain.Meal; + +@Component +public class MealRepository { + + private List meals = new ArrayList(); + + public MealRepository() { + meals.add(new Meal("Salad", 4.2f)); + meals.add(new Meal("Litre of cola", 2.99f)); + } + + public void create(Meal meal) { + meals.add(meal); + } + + public void remove(Meal meal) { + meals.remove(meal); + } + + public Meal find(int id) { + return meals.get(id); + } + + public List findAll() { + return meals; + } + + public void update(int id, Meal meal) { + meals.set(id, meal); + } +} \ No newline at end of file diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/resources/MealResource.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/resources/MealResource.java new file mode 100644 index 0000000000..9c617257cb --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/resources/MealResource.java @@ -0,0 +1,47 @@ +package com.baeldung.msf4j.msf4jspring.resources; + +import java.util.Collections; +import java.util.Map; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.wso2.msf4j.template.MustacheTemplateEngine; + +import com.baeldung.msf4j.msf4jspring.services.MealService; + +@Component +@Path("/meal") +public class MealResource { + + @Autowired + private MealService mealService; + + @GET + @Path("/") + public Response all() { + Map map = Collections.singletonMap("meals", mealService.findAll()); + String html = MustacheTemplateEngine.instance() + .render("meals.mustache", map); + return Response.ok() + .type(MediaType.TEXT_HTML) + .entity(html) + .build(); + } + + @GET + @Path("/{id}") + @Produces({ "text/xml" }) + public Response meal(@PathParam("id") int id) { + return Response.ok() + .entity(mealService.find(id)) + .build(); + } + +} diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/services/MealService.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/services/MealService.java new file mode 100644 index 0000000000..fd6a519999 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/services/MealService.java @@ -0,0 +1,27 @@ +package com.baeldung.msf4j.msf4jspring.services; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.baeldung.msf4j.msf4jspring.domain.Meal; +import com.baeldung.msf4j.msf4jspring.repositories.MealRepository; + +@Service +public class MealService { + @Autowired + private MealRepository mealRepository; + + public Meal find(int id) { + return mealRepository.find(id); + } + + public List findAll() { + return mealRepository.findAll(); + } + + public void create(Meal meal) { + mealRepository.create(meal); + } +} diff --git a/spring-boot-ops/src/main/resources/application.properties b/msf4j/src/main/resources/application.properties similarity index 100% rename from spring-boot-ops/src/main/resources/application.properties rename to msf4j/src/main/resources/application.properties diff --git a/msf4j/src/main/resources/templates/meals.mustache b/msf4j/src/main/resources/templates/meals.mustache new file mode 100644 index 0000000000..f4bdfaccf9 --- /dev/null +++ b/msf4j/src/main/resources/templates/meals.mustache @@ -0,0 +1,13 @@ + + + Meals + + +
+

Today's Meals

+ {{#meals}} +
{{name}}: {{price}}$
+ {{/meals}} +
+ + \ No newline at end of file diff --git a/mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceTest.java b/mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceUnitTest.java similarity index 98% rename from mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceTest.java rename to mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceUnitTest.java index 0df2f7f8a4..0c192b30bc 100644 --- a/mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceTest.java +++ b/mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceUnitTest.java @@ -15,7 +15,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -public class TodoMustacheServiceTest { +public class TodoMustacheServiceUnitTest { private String executeTemplate(Mustache m, Map context) throws IOException { StringWriter writer = new StringWriter(); diff --git a/mvn-wrapper/pom.xml b/mvn-wrapper/pom.xml index 6fb9bfeffc..e26df81139 100644 --- a/mvn-wrapper/pom.xml +++ b/mvn-wrapper/pom.xml @@ -9,10 +9,10 @@ Setting up the Maven Wrapper - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBDocumentAPITest.java b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBDocumentAPILiveTest.java similarity index 97% rename from orientdb/src/test/java/com/baeldung/orientdb/OrientDBDocumentAPITest.java rename to orientdb/src/test/java/com/baeldung/orientdb/OrientDBDocumentAPILiveTest.java index c51ff6928f..be79394292 100644 --- a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBDocumentAPITest.java +++ b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBDocumentAPILiveTest.java @@ -11,7 +11,7 @@ import java.util.List; import static junit.framework.Assert.assertEquals; -public class OrientDBDocumentAPITest { +public class OrientDBDocumentAPILiveTest { private static ODatabaseDocumentTx db = null; // @BeforeClass diff --git a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBGraphAPITest.java b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBGraphAPILiveTest.java similarity index 98% rename from orientdb/src/test/java/com/baeldung/orientdb/OrientDBGraphAPITest.java rename to orientdb/src/test/java/com/baeldung/orientdb/OrientDBGraphAPILiveTest.java index fe16564755..69926e5ed6 100644 --- a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBGraphAPITest.java +++ b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBGraphAPILiveTest.java @@ -10,7 +10,7 @@ import org.junit.Test; import static junit.framework.Assert.assertEquals; -public class OrientDBGraphAPITest { +public class OrientDBGraphAPILiveTest { private static OrientGraphNoTx graph = null; // @BeforeClass diff --git a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBObjectAPITest.java b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBObjectAPILiveTest.java similarity index 97% rename from orientdb/src/test/java/com/baeldung/orientdb/OrientDBObjectAPITest.java rename to orientdb/src/test/java/com/baeldung/orientdb/OrientDBObjectAPILiveTest.java index 71be159107..61dad39050 100644 --- a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBObjectAPITest.java +++ b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBObjectAPILiveTest.java @@ -10,7 +10,7 @@ import java.util.List; import static junit.framework.Assert.assertEquals; -public class OrientDBObjectAPITest { +public class OrientDBObjectAPILiveTest { private static OObjectDatabaseTx db = null; // @BeforeClass diff --git a/parent-boot-5/README.md b/parent-boot-1/README.md similarity index 100% rename from parent-boot-5/README.md rename to parent-boot-1/README.md diff --git a/parent-boot-5/pom.xml b/parent-boot-1/pom.xml similarity index 96% rename from parent-boot-5/pom.xml rename to parent-boot-1/pom.xml index 32bb2eab04..af14d88aff 100644 --- a/parent-boot-5/pom.xml +++ b/parent-boot-1/pom.xml @@ -2,16 +2,15 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - parent-boot-5 + parent-boot-1 0.0.1-SNAPSHOT pom - Parent Boot 5 - Parent for all spring boot 1.5 modules + Parent for all Spring Boot 1.x modules org.springframework.boot spring-boot-starter-parent - 1.5.10.RELEASE + 1.5.13.RELEASE diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index a9c54dece9..625a96ff9d 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -105,6 +105,25 @@
+ + thin-jar + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.springframework.boot.experimental + spring-boot-thin-layout + ${thin.version} + + + + + + @@ -115,6 +134,7 @@ 1.8 1.8 + 1.0.11.RELEASE \ No newline at end of file diff --git a/parent-spring/README.md b/parent-spring-4/README.md similarity index 100% rename from parent-spring/README.md rename to parent-spring-4/README.md diff --git a/parent-spring-4/pom.xml b/parent-spring-4/pom.xml new file mode 100644 index 0000000000..b2b8295f01 --- /dev/null +++ b/parent-spring-4/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + com.baeldung + parent-spring-4 + 0.0.1-SNAPSHOT + pom + parent-spring-4 + Parent for all spring 4 core modules + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.springframework + spring-core + ${spring.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + + + 4.3.17.RELEASE + 5.0.2 + + + \ No newline at end of file diff --git a/parent-spring-5/README.md b/parent-spring-5/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/parent-spring-5/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/parent-spring/pom.xml b/parent-spring-5/pom.xml similarity index 83% rename from parent-spring/pom.xml rename to parent-spring-5/pom.xml index 547c43dc27..87479d5e2f 100644 --- a/parent-spring/pom.xml +++ b/parent-spring-5/pom.xml @@ -2,11 +2,11 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - parent-spring + parent-spring-5 0.0.1-SNAPSHOT pom - parent-spring - Parent for all spring core modules + parent-spring-5 + Parent for all spring 5 core modules com.baeldung @@ -29,7 +29,7 @@ - 4.3.6.RELEASE + 5.0.6.RELEASE 5.0.2 diff --git a/patterns/design-patterns/pom.xml b/patterns/design-patterns/pom.xml index abf449fc43..dd1c5abced 100644 --- a/patterns/design-patterns/pom.xml +++ b/patterns/design-patterns/pom.xml @@ -50,18 +50,18 @@ mysql mysql-connector-java - 8.0.11 - test - - + 6.0.6 + jar + + log4j log4j ${log4j.version} - - - com.googlecode.grep4j - grep4j - ${grep4j.version} + + + com.googlecode.grep4j + grep4j + ${grep4j.version} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/daopattern/application/UserApplication.java b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/application/UserApplication.java index 05155aafcd..3a5c049992 100644 --- a/patterns/design-patterns/src/main/java/com/baeldung/daopattern/application/UserApplication.java +++ b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/application/UserApplication.java @@ -1,5 +1,6 @@ package com.baeldung.daopattern.application; +import com.baeldung.daopattern.config.JpaEntityManagerFactory; import com.baeldung.daopattern.daos.Dao; import com.baeldung.daopattern.daos.JpaUserDao; import com.baeldung.daopattern.entities.User; @@ -21,17 +22,17 @@ public class UserApplication { getAllUsers().forEach(user -> System.out.println(user.getName())); } + private static class JpaUserDaoHolder { + private static final JpaUserDao jpaUserDao = new JpaUserDao(new JpaEntityManagerFactory().getEntityManager()); + } + public static Dao getJpaUserDao() { - if (jpaUserDao == null) { - EntityManager entityManager = Persistence.createEntityManagerFactory("user-unit").createEntityManager(); - jpaUserDao = new JpaUserDao(entityManager); - } - return jpaUserDao; + return JpaUserDaoHolder.jpaUserDao; } public static User getUser(long id) { Optional user = getJpaUserDao().get(id); - return user.orElse(new User("Non-existing user", "no-email")); + return user.orElseGet(()-> {return new User("non-existing user", "no-email");}); } public static List getAllUsers() { diff --git a/patterns/design-patterns/src/main/java/com/baeldung/daopattern/config/JpaEntityManagerFactory.java b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/config/JpaEntityManagerFactory.java new file mode 100644 index 0000000000..11718d5612 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/config/JpaEntityManagerFactory.java @@ -0,0 +1,65 @@ +package com.baeldung.daopattern.config; + +import com.baeldung.daopattern.entities.User; +import com.mysql.cj.jdbc.MysqlDataSource; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; +import javax.persistence.EntityManager; +import javax.sql.DataSource; +import javax.persistence.EntityManagerFactory; +import javax.persistence.spi.PersistenceUnitInfo; +import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; +import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor; + +public class JpaEntityManagerFactory { + + private final String DB_URL = "jdbc:mysql://databaseurl"; + private final String DB_USER_NAME = "username"; + private final String DB_PASSWORD = "password"; + + public EntityManager getEntityManager() { + return getEntityManagerFactory().createEntityManager(); + } + + protected EntityManagerFactory getEntityManagerFactory() { + PersistenceUnitInfo persistenceUnitInfo = getPersistenceUnitInfo(getClass().getSimpleName()); + Map configuration = new HashMap<>(); + return new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration) + .build(); + } + + protected PersistenceUnitInfoImpl getPersistenceUnitInfo(String name) { + return new PersistenceUnitInfoImpl(name, getEntityClassNames(), getProperties()); + } + + protected List getEntityClassNames() { + return Arrays.asList(getEntities()) + .stream() + .map(Class::getName) + .collect(Collectors.toList()); + } + + protected Properties getProperties() { + Properties properties = new Properties(); + properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); + properties.put("hibernate.id.new_generator_mappings", false); + properties.put("hibernate.connection.datasource", getMysqlDataSource()); + return properties; + } + + protected Class[] getEntities() { + return new Class[]{User.class}; + } + + protected DataSource getMysqlDataSource() { + MysqlDataSource mysqlDataSource = new MysqlDataSource(); + mysqlDataSource.setURL(DB_URL); + mysqlDataSource.setUser(DB_USER_NAME); + mysqlDataSource.setPassword(DB_PASSWORD); + return mysqlDataSource; + } +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/daopattern/config/PersistenceUnitInfoImpl.java b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/config/PersistenceUnitInfoImpl.java new file mode 100644 index 0000000000..f3277da0cf --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/config/PersistenceUnitInfoImpl.java @@ -0,0 +1,130 @@ +package com.baeldung.daopattern.config; + +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import javax.sql.DataSource; +import javax.persistence.SharedCacheMode; +import javax.persistence.ValidationMode; +import javax.persistence.spi.ClassTransformer; +import javax.persistence.spi.PersistenceUnitInfo; +import javax.persistence.spi.PersistenceUnitTransactionType; +import org.hibernate.jpa.HibernatePersistenceProvider; + +public class PersistenceUnitInfoImpl implements PersistenceUnitInfo { + + public static final String JPA_VERSION = "2.1"; + private final String persistenceUnitName; + private PersistenceUnitTransactionType transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; + private final List managedClassNames; + private final List mappingFileNames = new ArrayList<>(); + private final Properties properties; + private DataSource jtaDataSource; + private DataSource nonJtaDataSource; + + public PersistenceUnitInfoImpl(String persistenceUnitName, List managedClassNames, Properties properties) { + this.persistenceUnitName = persistenceUnitName; + this.managedClassNames = managedClassNames; + this.properties = properties; + } + + @Override + public String getPersistenceUnitName() { + return persistenceUnitName; + } + + @Override + public String getPersistenceProviderClassName() { + return HibernatePersistenceProvider.class.getName(); + } + + @Override + public PersistenceUnitTransactionType getTransactionType() { + return transactionType; + } + + @Override + public DataSource getJtaDataSource() { + return jtaDataSource; + } + + public PersistenceUnitInfoImpl setJtaDataSource(DataSource jtaDataSource) { + this.jtaDataSource = jtaDataSource; + this.nonJtaDataSource = null; + transactionType = PersistenceUnitTransactionType.JTA; + return this; + } + + @Override + public DataSource getNonJtaDataSource() { + return nonJtaDataSource; + } + + public PersistenceUnitInfoImpl setNonJtaDataSource(DataSource nonJtaDataSource) { + this.nonJtaDataSource = nonJtaDataSource; + this.jtaDataSource = null; + transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; + return this; + } + + @Override + public List getMappingFileNames() { + return mappingFileNames; + } + + @Override + public List getJarFileUrls() { + return Collections.emptyList(); + } + + @Override + public URL getPersistenceUnitRootUrl() { + return null; + } + + @Override + public List getManagedClassNames() { + return managedClassNames; + } + + @Override + public boolean excludeUnlistedClasses() { + return false; + } + + @Override + public SharedCacheMode getSharedCacheMode() { + return SharedCacheMode.UNSPECIFIED; + } + + @Override + public ValidationMode getValidationMode() { + return ValidationMode.AUTO; + } + + public Properties getProperties() { + return properties; + } + + @Override + public String getPersistenceXMLSchemaVersion() { + return JPA_VERSION; + } + + @Override + public ClassLoader getClassLoader() { + return Thread.currentThread().getContextClassLoader(); + } + + @Override + public void addTransformer(ClassTransformer transformer) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public ClassLoader getNewTempClassLoader() { + return null; + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/visitor/Document.java b/patterns/design-patterns/src/main/java/com/baeldung/visitor/Document.java new file mode 100644 index 0000000000..575146a8e0 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/visitor/Document.java @@ -0,0 +1,20 @@ +package com.baeldung.visitor; + +import java.util.ArrayList; +import java.util.List; + +public class Document extends Element { + + List elements = new ArrayList<>(); + + public Document(String uuid) { + super(uuid); + } + + @Override + public void accept(Visitor v) { + for (Element e : this.elements) { + e.accept(v); + } + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/visitor/Element.java b/patterns/design-patterns/src/main/java/com/baeldung/visitor/Element.java new file mode 100644 index 0000000000..70c96c99e1 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/visitor/Element.java @@ -0,0 +1,12 @@ +package com.baeldung.visitor; + +public abstract class Element { + + public String uuid; + + public Element(String uuid) { + this.uuid = uuid; + } + + public abstract void accept(Visitor v); +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/visitor/ElementVisitor.java b/patterns/design-patterns/src/main/java/com/baeldung/visitor/ElementVisitor.java new file mode 100644 index 0000000000..f8af42d554 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/visitor/ElementVisitor.java @@ -0,0 +1,14 @@ +package com.baeldung.visitor; + +public class ElementVisitor implements Visitor { + + @Override + public void visit(XmlElement xe) { + System.out.println("processing xml element with uuid: " + xe.uuid); + } + + @Override + public void visit(JsonElement je) { + System.out.println("processing json element with uuid: " + je.uuid); + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/visitor/JsonElement.java b/patterns/design-patterns/src/main/java/com/baeldung/visitor/JsonElement.java new file mode 100644 index 0000000000..a65fe277f1 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/visitor/JsonElement.java @@ -0,0 +1,12 @@ +package com.baeldung.visitor; + +public class JsonElement extends Element { + + public JsonElement(String uuid) { + super(uuid); + } + + public void accept(Visitor v) { + v.visit(this); + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/visitor/Visitor.java b/patterns/design-patterns/src/main/java/com/baeldung/visitor/Visitor.java new file mode 100644 index 0000000000..1cd94911a3 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/visitor/Visitor.java @@ -0,0 +1,8 @@ +package com.baeldung.visitor; + +public interface Visitor { + + void visit(XmlElement xe); + + void visit(JsonElement je); +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/visitor/VisitorDemo.java b/patterns/design-patterns/src/main/java/com/baeldung/visitor/VisitorDemo.java new file mode 100644 index 0000000000..ee3436616a --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/visitor/VisitorDemo.java @@ -0,0 +1,23 @@ +package com.baeldung.visitor; + +import java.util.UUID; + +public class VisitorDemo { + + public static void main(String[] args) { + + Visitor v = new ElementVisitor(); + + Document d = new Document(generateUuid()); + d.elements.add(new JsonElement(generateUuid())); + d.elements.add(new JsonElement(generateUuid())); + d.elements.add(new XmlElement(generateUuid())); + + d.accept(v); + } + + private static String generateUuid() { + return UUID.randomUUID() + .toString(); + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/java/com/baeldung/visitor/XmlElement.java b/patterns/design-patterns/src/main/java/com/baeldung/visitor/XmlElement.java new file mode 100644 index 0000000000..41998de428 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/visitor/XmlElement.java @@ -0,0 +1,12 @@ +package com.baeldung.visitor; + +public class XmlElement extends Element { + + public XmlElement(String uuid) { + super(uuid); + } + + public void accept(Visitor v) { + v.visit(this); + } +} \ No newline at end of file diff --git a/patterns/design-patterns/src/main/resources/META-INF/persistence.xml b/patterns/design-patterns/src/main/resources/META-INF/persistence.xml index 61a5c9effc..e67a25e467 100644 --- a/patterns/design-patterns/src/main/resources/META-INF/persistence.xml +++ b/patterns/design-patterns/src/main/resources/META-INF/persistence.xml @@ -2,12 +2,12 @@ org.hibernate.jpa.HibernatePersistenceProvider - com.baeldung.daopattern.entities.User + com.baeldung.pattern.daopattern.entities.User - + - + diff --git a/patterns/design-patterns/src/main/resources/log4jstructuraldp.properties b/patterns/design-patterns/src/main/resources/log4jstructuraldp.properties new file mode 100644 index 0000000000..5bc2bfe4b9 --- /dev/null +++ b/patterns/design-patterns/src/main/resources/log4jstructuraldp.properties @@ -0,0 +1,9 @@ + +# Root logger +log4j.rootLogger=INFO, file, stdout + +# Write to console +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityTest.java b/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java similarity index 69% rename from patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityTest.java rename to patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java index a84f9dd8e5..824b104f81 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java @@ -1,10 +1,15 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; import org.junit.Test; - +import com.baeldung.pattern.chainofresponsibility.AuthenticationProcessor; +import com.baeldung.pattern.chainofresponsibility.OAuthAuthenticationProcessor; +import com.baeldung.pattern.chainofresponsibility.OAuthTokenProvider; +import com.baeldung.pattern.chainofresponsibility.UsernamePasswordProvider; +import com.baeldung.pattern.chainofresponsibility.SamlAuthenticationProvider; +import com.baeldung.pattern.chainofresponsibility.UsernamePasswordAuthenticationProcessor; import static org.junit.Assert.assertTrue; -public class ChainOfResponsibilityTest { +public class ChainOfResponsibilityIntegrationTest { private static AuthenticationProcessor getChainOfAuthProcessor() { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/facade/CarEngineFacadeTest.java b/patterns/design-patterns/src/test/java/com/baeldung/facade/CarEngineFacadeIntegrationTest.java similarity index 98% rename from patterns/design-patterns/src/test/java/com/baeldung/facade/CarEngineFacadeTest.java rename to patterns/design-patterns/src/test/java/com/baeldung/facade/CarEngineFacadeIntegrationTest.java index 88c5d3c9bc..ab4c0717d9 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/facade/CarEngineFacadeTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/facade/CarEngineFacadeIntegrationTest.java @@ -13,7 +13,7 @@ import java.util.List; import static org.junit.Assert.*; -public class CarEngineFacadeTest { +public class CarEngineFacadeIntegrationTest { private InMemoryCustomTestAppender appender; diff --git a/patterns/design-patterns/src/test/java/com/baeldung/singleton/synchronization/SingletonSynchronizationUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/singleton/synchronization/SingletonSynchronizationIntegrationTest.java similarity index 94% rename from patterns/design-patterns/src/test/java/com/baeldung/singleton/synchronization/SingletonSynchronizationUnitTest.java rename to patterns/design-patterns/src/test/java/com/baeldung/singleton/synchronization/SingletonSynchronizationIntegrationTest.java index 08a70f6056..de3d31ed9f 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/singleton/synchronization/SingletonSynchronizationUnitTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/singleton/synchronization/SingletonSynchronizationIntegrationTest.java @@ -15,7 +15,7 @@ import org.junit.Test; * @author Donato Rimenti * */ -public class SingletonSynchronizationUnitTest { +public class SingletonSynchronizationIntegrationTest { /** * Size of the thread pools used. @@ -33,7 +33,7 @@ public class SingletonSynchronizationUnitTest { @Test public void givenDraconianSingleton_whenMultithreadInstancesEquals_thenTrue() { ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); - Set resultSet = Collections.synchronizedSet(new HashSet()); + Set resultSet = Collections.synchronizedSet(new HashSet<>()); // Submits the instantiation tasks. for (int i = 0; i < TASKS_TO_SUBMIT; i++) { @@ -51,7 +51,7 @@ public class SingletonSynchronizationUnitTest { @Test public void givenDclSingleton_whenMultithreadInstancesEquals_thenTrue() { ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); - Set resultSet = Collections.synchronizedSet(new HashSet()); + Set resultSet = Collections.synchronizedSet(new HashSet<>()); // Submits the instantiation tasks. for (int i = 0; i < TASKS_TO_SUBMIT; i++) { @@ -69,7 +69,7 @@ public class SingletonSynchronizationUnitTest { @Test public void givenEarlyInitSingleton_whenMultithreadInstancesEquals_thenTrue() { ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); - Set resultSet = Collections.synchronizedSet(new HashSet()); + Set resultSet = Collections.synchronizedSet(new HashSet<>()); // Submits the instantiation tasks. for (int i = 0; i < TASKS_TO_SUBMIT; i++) { @@ -87,7 +87,7 @@ public class SingletonSynchronizationUnitTest { @Test public void givenInitOnDemandSingleton_whenMultithreadInstancesEquals_thenTrue() { ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); - Set resultSet = Collections.synchronizedSet(new HashSet()); + Set resultSet = Collections.synchronizedSet(new HashSet<>()); // Submits the instantiation tasks. for (int i = 0; i < TASKS_TO_SUBMIT; i++) { @@ -105,7 +105,7 @@ public class SingletonSynchronizationUnitTest { @Test public void givenEnumSingleton_whenMultithreadInstancesEquals_thenTrue() { ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); - Set resultSet = Collections.synchronizedSet(new HashSet()); + Set resultSet = Collections.synchronizedSet(new HashSet<>()); // Submits the instantiation tasks. for (int i = 0; i < TASKS_TO_SUBMIT; i++) { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternTest.java b/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java similarity index 97% rename from patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternTest.java rename to patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java index 679559af9f..4ad4debb27 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.templatemethod.test; +package com.baeldung.templatemethod.test; import com.baeldung.pattern.templatemethod.model.Computer; import com.baeldung.pattern.templatemethod.model.HighEndComputerBuilder; @@ -10,7 +10,7 @@ import org.junit.Test; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; -public class TemplateMethodPatternTest { +public class TemplateMethodPatternIntegrationTest { private static StandardComputerBuilder standardComputerBuilder; private static HighEndComputerBuilder highEndComputerBuilder; diff --git a/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java b/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java index 9a45f032a6..fe770aef24 100644 --- a/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java +++ b/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java @@ -4,13 +4,32 @@ import com.baeldung.performancetests.dozer.DozerConverter; import com.baeldung.performancetests.jmapper.JMapperConverter; import com.baeldung.performancetests.mapstruct.MapStructConverter; import com.baeldung.performancetests.model.destination.DestinationCode; -import com.baeldung.performancetests.model.source.*; import com.baeldung.performancetests.model.destination.Order; +import com.baeldung.performancetests.model.source.AccountStatus; +import com.baeldung.performancetests.model.source.Address; +import com.baeldung.performancetests.model.source.DeliveryData; +import com.baeldung.performancetests.model.source.Discount; +import com.baeldung.performancetests.model.source.OrderStatus; +import com.baeldung.performancetests.model.source.PaymentType; +import com.baeldung.performancetests.model.source.Product; +import com.baeldung.performancetests.model.source.RefundPolicy; +import com.baeldung.performancetests.model.source.Review; +import com.baeldung.performancetests.model.source.Shop; +import com.baeldung.performancetests.model.source.SourceCode; +import com.baeldung.performancetests.model.source.SourceOrder; +import com.baeldung.performancetests.model.source.User; import com.baeldung.performancetests.modelmapper.ModelMapperConverter; import com.baeldung.performancetests.orika.OrikaConverter; -import org.junit.Assert; -import org.junit.Test; -import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Group; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.runner.RunnerException; import java.io.IOException; @@ -21,14 +40,24 @@ import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; +@Fork(value = 1, warmups = 5) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@BenchmarkMode(Mode.All) +@Measurement(iterations = 5) @State(Scope.Group) public class MappingFrameworksPerformance { - SourceOrder sourceOrder = null; - SourceCode sourceCode = null; + private SourceOrder sourceOrder = null; + private SourceCode sourceCode = null; + private static final OrikaConverter ORIKA_CONVERTER = new OrikaConverter(); + private static final JMapperConverter JMAPPER_CONVERTER = new JMapperConverter(); + private static final ModelMapperConverter MODEL_MAPPER_CONVERTER = new ModelMapperConverter(); + private static final DozerConverter DOZER_CONVERTER = new DozerConverter(); + @Setup public void setUp() { User user = new User("John", "John@doe.com", AccountStatus.ACTIVE); - RefundPolicy refundPolicy = new RefundPolicy(true, 30, Collections.singletonList("Refundable only if not used!")); + RefundPolicy refundPolicy = new RefundPolicy(true, 30, Collections + .singletonList("Refundable only if not used!")); Product product = new Product(BigDecimal.valueOf(10.99), 100, @@ -51,7 +80,7 @@ public class MappingFrameworksPerformance { List reviewList = new ArrayList<>(); reviewList.add(review); reviewList.add(negativeReview); - Shop shop = new Shop("Super Shop", shopAddress,"www.super-shop.com",reviewList); + Shop shop = new Shop("Super Shop", shopAddress, "www.super-shop.com", reviewList); sourceOrder = new SourceOrder(OrderStatus.CONFIRMED, Instant.now().toString(), @@ -68,126 +97,67 @@ public class MappingFrameworksPerformance { sourceCode = new SourceCode("This is source code!"); } - public void main(String[] args) throws IOException, RunnerException { org.openjdk.jmh.Main.main(args); } - @Benchmark @Group("realLifeTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void orikaMapperRealLifeBenchmark() { - OrikaConverter orikaConverter = new OrikaConverter(); - Order mappedOrder = orikaConverter.convert(sourceOrder); - Assert.assertEquals(mappedOrder, sourceOrder); - + public Order orikaMapperRealLifeBenchmark() { + return ORIKA_CONVERTER.convert(sourceOrder); } @Benchmark @Group("realLifeTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void jmapperRealLifeBenchmark() { - JMapperConverter jmapperConverter = new JMapperConverter(); - Order mappedOrder = jmapperConverter.convert(sourceOrder); - Assert.assertEquals(mappedOrder, sourceOrder); + public Order jmapperRealLifeBenchmark() { + return JMAPPER_CONVERTER.convert(sourceOrder); } @Benchmark @Group("realLifeTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void modelMapperRealLifeBenchmark() { - ModelMapperConverter modelMapperConverter = new ModelMapperConverter(); - Order mappedOrder = modelMapperConverter.convert(sourceOrder); - Assert.assertEquals(mappedOrder, sourceOrder); - } - - - @Benchmark - @Group("realLifeTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void dozerMapperRealLifeBenchmark() { - DozerConverter dozerConverter = new DozerConverter(); - Order mappedOrder = dozerConverter.convert(sourceOrder); - Assert.assertEquals(mappedOrder, sourceOrder); - + public Order modelMapperRealLifeBenchmark() { + return MODEL_MAPPER_CONVERTER.convert(sourceOrder); } @Benchmark @Group("realLifeTest") - @Fork(value = 1, warmups = 1) - @BenchmarkMode(Mode.All) - public void mapStructRealLifeMapperBenchmark() { - MapStructConverter converter = MapStructConverter.MAPPER; - Order mappedOrder = converter.convert(sourceOrder); - Assert.assertEquals(mappedOrder, sourceOrder); + public Order dozerMapperRealLifeBenchmark() { + return DOZER_CONVERTER.convert(sourceOrder); + } + + @Benchmark + @Group("realLifeTest") + public Order mapStructRealLifeMapperBenchmark() { + return MapStructConverter.MAPPER.convert(sourceOrder); } @Benchmark @Group("simpleTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void orikaMapperSimpleBenchmark() { - OrikaConverter orikaConverter = new OrikaConverter(); - DestinationCode mappedCode = orikaConverter.convert(sourceCode); - Assert.assertEquals(mappedCode.getCode(), sourceCode.getCode()); - + public DestinationCode orikaMapperSimpleBenchmark() { + return ORIKA_CONVERTER.convert(sourceCode); } @Benchmark @Group("simpleTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void jmapperSimpleBenchmark() { - JMapperConverter jmapperConverter = new JMapperConverter(); - DestinationCode mappedCode = jmapperConverter.convert(sourceCode); - Assert.assertEquals(mappedCode.getCode(), sourceCode.getCode()); + public DestinationCode jmapperSimpleBenchmark() { + return JMAPPER_CONVERTER.convert(sourceCode); } @Benchmark @Group("simpleTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void modelMapperBenchmark() { - ModelMapperConverter modelMapperConverter = new ModelMapperConverter(); - DestinationCode mappedCode = modelMapperConverter.convert(sourceCode); - Assert.assertEquals(mappedCode.getCode(), sourceCode.getCode()); - } - - - @Benchmark - @Group("simpleTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void dozerMapperSimpleBenchmark() { - DozerConverter dozerConverter = new DozerConverter(); - Order mappedOrder = dozerConverter.convert(sourceOrder); - Assert.assertEquals(mappedOrder, sourceOrder); - + public DestinationCode modelMapperBenchmark() { + return MODEL_MAPPER_CONVERTER.convert(sourceCode); } @Benchmark @Group("simpleTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void mapStructMapperSimpleBenchmark() { - MapStructConverter converter = MapStructConverter.MAPPER; - DestinationCode mappedCode = converter.convert(sourceCode); - Assert.assertEquals(mappedCode.getCode(), sourceCode.getCode()); + public Order dozerMapperSimpleBenchmark() { + return DOZER_CONVERTER.convert(sourceOrder); } - + @Benchmark + @Group("simpleTest") + public DestinationCode mapStructMapperSimpleBenchmark() { + return MapStructConverter.MAPPER.convert(sourceCode); + } } diff --git a/persistence-modules/README.md b/persistence-modules/README.md index dde4558387..8f8c3eb13d 100644 --- a/persistence-modules/README.md +++ b/persistence-modules/README.md @@ -9,3 +9,4 @@ - [Introduction to Lettuce – the Java Redis Client](http://www.baeldung.com/java-redis-lettuce) - [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging) - [A Guide to Jdbi](http://www.baeldung.com/jdbi) +- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) diff --git a/persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiTest.java b/persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiIntegrationTest.java similarity index 99% rename from persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiTest.java rename to persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiIntegrationTest.java index 503bf90fdb..dbc8a396ce 100644 --- a/persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiTest.java +++ b/persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiIntegrationTest.java @@ -17,7 +17,7 @@ import java.util.stream.Stream; import static org.junit.Assert.*; -public class JdbiTest { +public class JdbiIntegrationTest { @Test public void whenJdbiCreated_thenSuccess() { diff --git a/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java index 1862d6b035..860ca0927a 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java @@ -27,7 +27,9 @@ public class RedissonConfigurationIntegrationTest { @AfterClass public static void destroy() { redisServer.stop(); - client.shutdown(); + if (client != null) { + client.shutdown(); + } } @Test diff --git a/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java index 766963e5cf..53d77c2699 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java @@ -37,7 +37,9 @@ public class RedissonIntegrationTest { @AfterClass public static void destroy() { redisServer.stop(); - client.shutdown(); + if (client != null) { + client.shutdown(); + } } @Test diff --git a/persistence-modules/spring-data-cassandra/pom.xml b/persistence-modules/spring-data-cassandra/pom.xml index 84165564ba..b11a1fd07b 100644 --- a/persistence-modules/spring-data-cassandra/pom.xml +++ b/persistence-modules/spring-data-cassandra/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../../parent-spring + ../../parent-spring-4 @@ -23,7 +23,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -34,7 +34,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -76,7 +76,6 @@ UTF-8 - 4.3.4.RELEASE 1.3.2.RELEASE 2.1.5 2.1.9.2 diff --git a/persistence-modules/spring-data-dynamodb/pom.xml b/persistence-modules/spring-data-dynamodb/pom.xml index b115c0e087..b1b7c8237b 100644 --- a/persistence-modules/spring-data-dynamodb/pom.xml +++ b/persistence-modules/spring-data-dynamodb/pom.xml @@ -9,10 +9,10 @@ This is simple boot application for Spring boot actuator test - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index 26d5c6bddf..c5e0049e83 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-spring + parent-spring-5 0.0.1-SNAPSHOT - ../../parent-spring + ../../parent-spring-5 @@ -74,7 +74,6 @@ UTF-8 - 5.0.3.RELEASE 2.0.3.RELEASE 3.2.4 2.9.0 diff --git a/persistence-modules/spring-data-solr/pom.xml b/persistence-modules/spring-data-solr/pom.xml index f1c20344c1..036b40a7ed 100644 --- a/persistence-modules/spring-data-solr/pom.xml +++ b/persistence-modules/spring-data-solr/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../../parent-spring + ../../parent-spring-4 @@ -47,7 +47,6 @@ UTF-8 - 4.3.4.RELEASE 2.0.5.RELEASE diff --git a/persistence-modules/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md index cb71d386e2..02d4306ecb 100644 --- a/persistence-modules/spring-jpa/README.md +++ b/persistence-modules/spring-jpa/README.md @@ -22,6 +22,7 @@ - [Obtaining Auto-generated Keys in Spring JDBC](http://www.baeldung.com/spring-jdbc-autogenerated-keys) - [Transactions with Spring 4 and JPA](http://www.baeldung.com/transaction-configuration-with-jpa-and-spring) - [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) +- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/persistence-modules/spring-jpa/pom.xml b/persistence-modules/spring-jpa/pom.xml index 065b29b26b..c6762df54b 100644 --- a/persistence-modules/spring-jpa/pom.xml +++ b/persistence-modules/spring-jpa/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung spring-jpa 0.1-SNAPSHOT war diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/MyUtilityRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/MyUtilityRepository.java new file mode 100644 index 0000000000..5fe54b80d9 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/MyUtilityRepository.java @@ -0,0 +1,14 @@ +package org.baeldung.annotations; + +import java.io.Serializable; +import java.util.Optional; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.NoRepositoryBean; + +@NoRepositoryBean +public interface MyUtilityRepository extends CrudRepository { + + Optional findById(ID id); + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/Person.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/Person.java new file mode 100644 index 0000000000..309a4f43e1 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/Person.java @@ -0,0 +1,54 @@ +package org.baeldung.annotations; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.NamedStoredProcedureQueries; +import javax.persistence.NamedStoredProcedureQuery; +import javax.persistence.ParameterMode; +import javax.persistence.StoredProcedureParameter; + +import org.baeldung.persistence.multiple.model.user.User; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.Transient; + +@Entity +@NamedStoredProcedureQueries({ + @NamedStoredProcedureQuery( + name = "count_by_name", + procedureName = "person.count_by_name", + parameters = { + @StoredProcedureParameter( + mode = ParameterMode.IN, + name = "name", + type = String.class), + @StoredProcedureParameter( + mode = ParameterMode.OUT, + name = "count", + type = Long.class) + }) +}) +public class Person { + + @Id + private Long id; + + @Transient + private int age; + + @CreatedBy + private User creator; + + @LastModifiedBy + private User modifier; + + @CreatedDate + private Date createdAt; + + @LastModifiedBy + private Date modifiedAt; + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/PersonRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/PersonRepository.java new file mode 100644 index 0000000000..1c9a89bec5 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/PersonRepository.java @@ -0,0 +1,32 @@ +package org.baeldung.annotations; + +import javax.persistence.LockModeType; + +import org.springframework.data.jpa.repository.Lock; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.jpa.repository.query.Procedure; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +@Repository +public interface PersonRepository extends MyUtilityRepository { + + @Lock(LockModeType.NONE) + @Query("SELECT COUNT(*) FROM Person p") + long getPersonCount(); + + @Query("FROM Person p WHERE p.name = :name") + Person findByName(@Param("name") String name); + + @Query(value = "SELECT AVG(p.age) FROM person p", nativeQuery = true) + Person getAverageAge(); + + @Procedure(name = "count_by_name") + long getCountByName(@Param("name") String name); + + @Modifying + @Query("UPDATE Person p SET p.name = :name WHERE p.id = :id") + void changeName(@Param("id") long id, @Param("name") String name); + +} diff --git a/pom.xml b/pom.xml index 71f2a846fb..d42c3ac617 100644 --- a/pom.xml +++ b/pom.xml @@ -9,9 +9,10 @@ pom - parent-boot-5 + parent-boot-1 parent-boot-2 - parent-spring + parent-spring-4 + parent-spring-5 parent-java asm atomix @@ -101,6 +102,7 @@ metrics maven mesos-marathon + msf4j testing-modules/mockito testing-modules/mockito-2 testing-modules/mocks @@ -260,6 +262,7 @@ java-spi performance-tests twilio + java-ee-8-security-api @@ -371,9 +374,9 @@ - 5 - true - false + 5 + false + true true true true @@ -531,5 +534,4 @@ 1.3 5.0.2 - diff --git a/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersTest.java b/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersIntegrationTest.java similarity index 98% rename from reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersTest.java rename to reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersIntegrationTest.java index 5a0dcef5ba..e6108759e1 100644 --- a/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersTest.java +++ b/reactor-core/src/test/java/com/baeldung/reactor/core/CombiningPublishersIntegrationTest.java @@ -7,7 +7,7 @@ import org.junit.Test; import reactor.core.publisher.Flux; import reactor.test.StepVerifier; -public class CombiningPublishersTest { +public class CombiningPublishersIntegrationTest { private static Integer min = 1; private static Integer max = 5; diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableTest.java b/rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableIntegrationTest.java similarity index 93% rename from rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableIntegrationTest.java index 031ff0c5bb..5c28c53d11 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableIntegrationTest.java @@ -10,7 +10,7 @@ import static com.jayway.awaitility.Awaitility.await; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; -public class ConnectableObservableTest { +public class ConnectableObservableIntegrationTest { @Test public void givenConnectableObservable_whenConnect_thenGetMessage() throws InterruptedException { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/FlowableTest.java b/rxjava/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java similarity index 99% rename from rxjava/src/test/java/com/baeldung/rxjava/FlowableTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java index b9d1d64c24..9fee2bc005 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/FlowableTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java @@ -18,7 +18,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -public class FlowableTest { +public class FlowableIntegrationTest { @Test public void whenFlowableIsCreated_thenItIsProperlyInitialized() { Flowable integerFlowable = Flowable.just(1, 2, 3, 4); diff --git a/rxjava/src/test/java/com/baeldung/rxjava/MaybeTest.java b/rxjava/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java similarity index 97% rename from rxjava/src/test/java/com/baeldung/rxjava/MaybeTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java index 501ee1f196..d02fe990c0 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/MaybeTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import io.reactivex.Flowable; import io.reactivex.Maybe; -public class MaybeTest { +public class MaybeUnitTest { @Test public void whenEmitsSingleValue_thenItIsObserved() { Maybe maybe = Flowable.just(1, 2, 3, 4, 5) diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ObservableTest.java b/rxjava/src/test/java/com/baeldung/rxjava/ObservableUnitTest.java similarity index 99% rename from rxjava/src/test/java/com/baeldung/rxjava/ObservableTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/ObservableUnitTest.java index beb2cbeed3..22e52f73c4 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/ObservableTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/ObservableUnitTest.java @@ -6,7 +6,7 @@ import rx.Observable; import static com.baeldung.rxjava.ObservableImpl.getTitle; import static junit.framework.Assert.assertTrue; -public class ObservableTest { +public class ObservableUnitTest { private String result = ""; diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementTest.java b/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementUnitTest.java similarity index 94% rename from rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementUnitTest.java index 81be84fd0d..145194d374 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementUnitTest.java @@ -5,7 +5,7 @@ import rx.Observable; import static junit.framework.Assert.assertTrue; -public class ResourceManagementTest { +public class ResourceManagementUnitTest { @Test public void givenResource_whenUsingOberservable_thenCreatePrintDisposeResource() throws InterruptedException { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxRelayTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java similarity index 99% rename from rxjava/src/test/java/com/baeldung/rxjava/RxRelayTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java index 091e4df138..9fc5827d86 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/RxRelayTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java @@ -9,7 +9,7 @@ import org.junit.Test; import java.util.concurrent.TimeUnit; -public class RxRelayTest { +public class RxRelayIntegrationTest { @Test public void whenObserverSubscribedToPublishRelay_thenItReceivesEmittedEvents () { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SingleTest.java b/rxjava/src/test/java/com/baeldung/rxjava/SingleUnitTest.java similarity index 95% rename from rxjava/src/test/java/com/baeldung/rxjava/SingleTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/SingleUnitTest.java index 1352841ed9..8c39034cb9 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/SingleTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/SingleUnitTest.java @@ -6,7 +6,7 @@ import rx.Single; import static junit.framework.Assert.assertTrue; -public class SingleTest { +public class SingleUnitTest { @Test public void givenSingleObservable_whenSuccess_thenGetMessage() throws InterruptedException { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SubjectTest.java b/rxjava/src/test/java/com/baeldung/rxjava/SubjectUnitTest.java similarity index 95% rename from rxjava/src/test/java/com/baeldung/rxjava/SubjectTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/SubjectUnitTest.java index 628b1e5476..a678d83667 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/SubjectTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/SubjectUnitTest.java @@ -5,7 +5,7 @@ import rx.subjects.PublishSubject; import static junit.framework.Assert.assertTrue; -public class SubjectTest { +public class SubjectUnitTest { @Test public void givenSubjectAndTwoSubscribers_whenSubscribeOnSubject_thenSubscriberBeginsToAdd() { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsIntegrationTest.java similarity index 99% rename from rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsIntegrationTest.java index 0b38f0387b..a11d0ff8c3 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsIntegrationTest.java @@ -14,7 +14,7 @@ import java.util.concurrent.TimeUnit; import static com.jayway.awaitility.Awaitility.await; import static org.junit.Assert.assertTrue; -public class UtilityOperatorsTest { +public class UtilityOperatorsIntegrationTest { private int emittedTotal = 0; private int receivedTotal = 0; diff --git a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsIntegrationTest.java similarity index 99% rename from rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsIntegrationTest.java index be0f390b67..67f4c51cbe 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsIntegrationTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import rx.Observable; import rx.observers.TestSubscriber; -public class RxJavaFilterOperatorsTest { +public class RxJavaFilterOperatorsIntegrationTest { @Test public void givenRangeObservable_whenFilteringItems_thenOddItemsAreFiltered() { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsIntegrationTest.java similarity index 98% rename from rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsIntegrationTest.java index eca39b17bf..eca65e728e 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsIntegrationTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import rx.Observable; import rx.observers.TestSubscriber; -public class RxJavaSkipOperatorsTest { +public class RxJavaSkipOperatorsIntegrationTest { @Test public void givenRangeObservable_whenSkipping_thenFirstFourItemsAreSkipped() { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsIntegrationTest.java similarity index 99% rename from rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsIntegrationTest.java index 63076cbc4a..d9ec6c3798 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsIntegrationTest.java @@ -9,7 +9,7 @@ import rx.Observable; import rx.observers.TestSubscriber; import rx.schedulers.TestScheduler; -public class RxJavaTimeFilteringOperatorsTest { +public class RxJavaTimeFilteringOperatorsIntegrationTest { @Test public void givenTimedObservable_whenSampling_thenOnlySampleItemsAreEmitted() { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java index 477a2a1cb8..ec766ac7ac 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java @@ -18,26 +18,27 @@ public class AutomapInterfaceIntegrationTest { private ConnectionProvider connectionProvider = Connector.connectionProvider; private Database db = Database.from(connectionProvider); - private Observable create = null; + private Observable truncate = null; private Observable insert1, insert2 = null; @Before public void setup() { - create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))") + Observable create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))") .count(); + truncate = db.update("TRUNCATE TABLE EMPLOYEE") + .dependsOn(create) + .count(); insert1 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'Alan')") - .dependsOn(create) + .dependsOn(truncate) .count(); insert2 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(2, 'Sarah')") - .dependsOn(create) + .dependsOn(insert1) .count(); } @Test public void whenSelectFromTableAndAutomap_thenCorrect() { List employees = db.select("select id, name from EMPLOYEE") - .dependsOn(create) - .dependsOn(insert1) .dependsOn(insert2) .autoMap(Employee.class) .toList() @@ -57,7 +58,7 @@ public class AutomapInterfaceIntegrationTest { @After public void close() { db.update("DROP TABLE EMPLOYEE") - .dependsOn(create); + .dependsOn(truncate); connectionProvider.close(); } } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java index 5f445234d7..2fb3b3abd7 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java @@ -22,24 +22,24 @@ public class BasicQueryTypesIntegrationTest { @Test public void whenCreateTableAndInsertRecords_thenCorrect() { - create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))") + create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE_TABLE(id int primary key, name varchar(255))") .count(); - Observable insert1 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'John')") + Observable insert1 = db.update("INSERT INTO EMPLOYEE_TABLE(id, name) VALUES(1, 'John')") .dependsOn(create) .count(); - Observable update = db.update("UPDATE EMPLOYEE SET name = 'Alan' WHERE id = 1") + Observable update = db.update("UPDATE EMPLOYEE_TABLE SET name = 'Alan' WHERE id = 1") .dependsOn(create) .count(); - Observable insert2 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(2, 'Sarah')") + Observable insert2 = db.update("INSERT INTO EMPLOYEE_TABLE(id, name) VALUES(2, 'Sarah')") .dependsOn(create) .count(); - Observable insert3 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(3, 'Mike')") + Observable insert3 = db.update("INSERT INTO EMPLOYEE_TABLE(id, name) VALUES(3, 'Mike')") .dependsOn(create) .count(); - Observable delete = db.update("DELETE FROM EMPLOYEE WHERE id = 2") + Observable delete = db.update("DELETE FROM EMPLOYEE_TABLE WHERE id = 2") .dependsOn(create) .count(); - List names = db.select("select name from EMPLOYEE where id < ?") + List names = db.select("select name from EMPLOYEE_TABLE where id < ?") .parameter(3) .dependsOn(create) .dependsOn(insert1) @@ -57,7 +57,7 @@ public class BasicQueryTypesIntegrationTest { @After public void close() { - db.update("DROP TABLE EMPLOYEE") + db.update("DROP TABLE EMPLOYEE_TABLE") .dependsOn(create); connectionProvider.close(); } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java index 189bca4adb..284ecc4078 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java @@ -27,7 +27,7 @@ public class InsertClobIntegrationTest { @Before public void setup() throws IOException { - create = db.update("CREATE TABLE IF NOT EXISTS SERVERLOG (id int primary key, document CLOB)") + create = db.update("CREATE TABLE IF NOT EXISTS SERVERLOG_TABLE (id int primary key, document CLOB)") .count(); InputStream actualInputStream = new FileInputStream("src/test/resources/actual_clob"); @@ -35,7 +35,7 @@ public class InsertClobIntegrationTest { InputStream expectedInputStream = new FileInputStream("src/test/resources/expected_clob"); this.expectedDocument = Utils.getStringFromInputStream(expectedInputStream); - this.insert = db.update("insert into SERVERLOG(id,document) values(?,?)") + this.insert = db.update("insert into SERVERLOG_TABLE(id,document) values(?,?)") .parameter(1) .parameter(Database.toSentinelIfNull(actualDocument)) .dependsOn(create) @@ -44,7 +44,7 @@ public class InsertClobIntegrationTest { @Test public void whenSelectCLOB_thenCorrect() throws IOException { - db.select("select document from SERVERLOG where id = 1") + db.select("select document from SERVERLOG_TABLE where id = 1") .dependsOn(create) .dependsOn(insert) .getAs(String.class) @@ -56,7 +56,7 @@ public class InsertClobIntegrationTest { @After public void close() { - db.update("DROP TABLE SERVERLOG") + db.update("DROP TABLE SERVERLOG_TABLE") .dependsOn(create); connectionProvider.close(); } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java index 2018a9427c..c9e06a347f 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java @@ -22,14 +22,14 @@ public class ReturnKeysIntegrationTest { @Before public void setup() { begin = db.beginTransaction(); - createStatement = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int auto_increment primary key, name varchar(255))") + createStatement = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE_SAMPLE(id int auto_increment primary key, name varchar(255))") .dependsOn(begin) .count(); } @Test public void whenInsertAndReturnGeneratedKey_thenCorrect() { - Integer key = db.update("INSERT INTO EMPLOYEE(name) VALUES('John')") + Integer key = db.update("INSERT INTO EMPLOYEE_SAMPLE(name) VALUES('John')") .dependsOn(createStatement) .returnGeneratedKeys() .getAs(Integer.class) @@ -41,7 +41,7 @@ public class ReturnKeysIntegrationTest { @After public void close() { - db.update("DROP TABLE EMPLOYEE") + db.update("DROP TABLE EMPLOYEE_SAMPLE") .dependsOn(createStatement); connectionProvider.close(); } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java index 4e24d7f10e..d5f09be23c 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java @@ -24,8 +24,11 @@ public class TransactionIntegrationTest { .update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))") .dependsOn(begin) .count(); + Observable truncateStatement = db.update("TRUNCATE TABLE EMPLOYEE") + .dependsOn(createStatement) + .count(); Observable insertStatement = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'John')") - .dependsOn(createStatement) + .dependsOn(truncateStatement) .count(); Observable updateStatement = db.update("UPDATE EMPLOYEE SET name = 'Tom' WHERE id = 1") .dependsOn(insertStatement) diff --git a/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingTest.java b/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java similarity index 98% rename from rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java index b1d711ab39..304dc98274 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java @@ -9,7 +9,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.assertTrue; -public class ExceptionHandlingTest { +public class ExceptionHandlingIntegrationTest { private Error UNKNOWN_ERROR = new Error("unknown error"); private Exception UNKNOWN_EXCEPTION = new Exception("unknown exception"); diff --git a/rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryTest.java b/rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java similarity index 99% rename from rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java index 3cc72056ba..746e3cfbf6 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java @@ -9,7 +9,7 @@ import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertTrue; -public class OnErrorRetryTest { +public class OnErrorRetryIntegrationTest { private Error UNKNOWN_ERROR = new Error("unknown error"); diff --git a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsUnitTest.java similarity index 99% rename from rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsUnitTest.java index 6733aa08c5..f0d7a9a4e4 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsUnitTest.java @@ -11,7 +11,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; -public class RxAggregateOperatorsTest { +public class RxAggregateOperatorsUnitTest { @Test public void givenTwoObservable_whenConcatenatingThem_thenSuccessfull() { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsUnitTest.java similarity index 98% rename from rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsUnitTest.java index cd212a2e18..9390792737 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsUnitTest.java @@ -9,7 +9,7 @@ import java.util.Arrays; import java.util.Comparator; import java.util.List; -public class RxMathematicalOperatorsTest { +public class RxMathematicalOperatorsUnitTest { @Test public void givenRangeNumericObservable_whenCalculatingAverage_ThenSuccessfull() { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsUnitTest.java similarity index 99% rename from rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsUnitTest.java index 5e58b32d8b..1ffc9b3ca2 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsUnitTest.java @@ -12,7 +12,7 @@ import rx.observables.StringObservable; import rx.observers.TestSubscriber; -public class RxStringOperatorsTest +public class RxStringOperatorsUnitTest { @Test diff --git a/spring-4/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java b/spring-4/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java similarity index 98% rename from spring-4/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java rename to spring-4/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java index 8fd9c4e340..9dd4ef064a 100644 --- a/spring-4/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java +++ b/spring-4/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java @@ -23,7 +23,7 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; }, webEnvironment = SpringBootTest.WebEnvironment.MOCK) @AutoConfigureMockMvc @ActiveProfiles("dev") -public class FlipControllerTest { +public class FlipControllerIntegrationTest { @Autowired private MockMvc mvc; diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 06ddfb82d9..711463c430 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -10,10 +10,10 @@ spring 5 MVC sample project about new features - org.springframework.boot - spring-boot-starter-parent - 2.0.0.M7 - + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 @@ -90,7 +90,7 @@ com.jayway.restassured rest-assured - ${rest-assured.version} + ${jayway-rest-assured.version} test @@ -174,7 +174,7 @@ - 2.9.0 + 2.9.0 UTF-8 UTF-8 1.8 diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index fa86e9ca8a..8b40ccee00 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -11,10 +11,10 @@ spring 5 sample project about new features - org.springframework.boot - spring-boot-starter-parent - 2.0.0.RELEASE - + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 @@ -141,6 +141,12 @@ rxjava ${rxjava-version} + + io.projectreactor + reactor-test + ${project-reactor-test} + test + @@ -185,6 +191,7 @@ 1.0 1.0 4.1 + 3.1.6.RELEASE diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java index 86f995ed79..f425826dce 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java @@ -10,6 +10,7 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -25,26 +26,44 @@ public class AccountCrudRepositoryIntegrationTest { public void givenValue_whenFindAllByValue_thenFindAccount() { repository.save(new Account(null, "Bill", 12.3)).block(); Flux accountFlux = repository.findAllByValue(12.3); - Account account = accountFlux.next().block(); - assertEquals("Bill", account.getOwner()); - assertEquals(Double.valueOf(12.3) , account.getValue()); - assertNotNull(account.getId()); + + StepVerifier.create(accountFlux) + .assertNext(account -> { + assertEquals("Bill", account.getOwner()); + assertEquals(Double.valueOf(12.3) , account.getValue()); + assertNotNull(account.getId()); + }) + .expectComplete() + .verify(); } @Test public void givenOwner_whenFindFirstByOwner_thenFindAccount() { repository.save(new Account(null, "Bill", 12.3)).block(); Mono accountMono = repository.findFirstByOwner(Mono.just("Bill")); - Account account = accountMono.block(); - assertEquals("Bill", account.getOwner()); - assertEquals(Double.valueOf(12.3) , account.getValue()); - assertNotNull(account.getId()); + + StepVerifier.create(accountMono) + .assertNext(account -> { + assertEquals("Bill", account.getOwner()); + assertEquals(Double.valueOf(12.3) , account.getValue()); + assertNotNull(account.getId()); + }) + .expectComplete() + .verify(); + + + } @Test public void givenAccount_whenSave_thenSaveAccount() { Mono accountMono = repository.save(new Account(null, "Bill", 12.3)); - assertNotNull(accountMono.block().getId()); + + StepVerifier + .create(accountMono) + .assertNext(account -> assertNotNull(account.getId())) + .expectComplete() + .verify(); } diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java index f95c443b7f..bfa6a789b2 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java @@ -2,8 +2,6 @@ package com.baeldung.reactive.repository; import com.baeldung.reactive.Spring5ReactiveApplication; import com.baeldung.reactive.model.Account; -import org.junit.After; -import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -13,10 +11,10 @@ import org.springframework.data.domain.ExampleMatcher; import org.springframework.test.context.junit4.SpringRunner; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; -import java.util.List; - -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.startsWith; @RunWith(SpringRunner.class) @@ -32,23 +30,38 @@ public class AccountMongoRepositoryIntegrationTest { ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("owner", startsWith()); Example example = Example.of(new Account(null, "jo", null), matcher); Flux accountFlux = repository.findAll(example); - List accounts = accountFlux.collectList().block(); - assertTrue(accounts.stream().anyMatch(x -> x.getOwner().equals("john"))); + StepVerifier + .create(accountFlux) + .assertNext(account -> assertEquals("john", account.getOwner())) + .expectComplete() + .verify(); } @Test public void givenAccount_whenSave_thenSave() { Mono accountMono = repository.save(new Account(null, "john", 12.3)); - assertNotNull(accountMono.block().getId()); + + StepVerifier + .create(accountMono) + .assertNext(account -> assertNotNull(account.getId())) + .expectComplete() + .verify(); } @Test public void givenId_whenFindById_thenFindAccount() { Account inserted = repository.save(new Account(null, "john", 12.3)).block(); Mono accountMono = repository.findById(inserted.getId()); - assertEquals("john", accountMono.block().getOwner()); - assertEquals(Double.valueOf(12.3), accountMono.block().getValue()); - assertNotNull(accountMono.block().getId()); + + StepVerifier + .create(accountMono) + .assertNext(account -> { + assertEquals("john", account.getOwner()); + assertEquals(Double.valueOf(12.3), account.getValue()); + assertNotNull(account.getId()); + }) + .expectComplete() + .verify(); } } \ No newline at end of file diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java index 6199b460d0..e9b3eb1c40 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java @@ -21,23 +21,38 @@ public class AccountRxJavaRepositoryIntegrationTest { AccountRxJavaRepository repository; @Test - public void givenValue_whenFindAllByValue_thenFindAccounts() { + public void givenValue_whenFindAllByValue_thenFindAccounts() throws InterruptedException { repository.save(new Account(null, "bruno", 12.3)).blockingGet(); Observable accountObservable = repository.findAllByValue(12.3); - Account account = accountObservable.filter(x -> x.getOwner().equals("bruno")).blockingFirst(); - assertEquals("bruno", account.getOwner()); - assertEquals(Double.valueOf(12.3), account.getValue()); - assertNotNull(account.getId()); + + accountObservable + .test() + .await() + .assertComplete() + .assertValueAt(0, account -> { + assertEquals("bruno", account.getOwner()); + assertEquals(Double.valueOf(12.3), account.getValue()); + return true; + }); + } @Test - public void givenOwner_whenFindFirstByOwner_thenFindAccount() { + public void givenOwner_whenFindFirstByOwner_thenFindAccount() throws InterruptedException { repository.save(new Account(null, "bruno", 12.3)).blockingGet(); Single accountSingle = repository.findFirstByOwner(Single.just("bruno")); - Account account = accountSingle.blockingGet(); - assertEquals("bruno", account.getOwner()); - assertEquals(Double.valueOf(12.3), account.getValue()); - assertNotNull(account.getId()); + + accountSingle + .test() + .await() + .assertComplete() + .assertValueAt(0, account -> { + assertEquals("bruno", account.getOwner()); + assertEquals(Double.valueOf(12.3), account.getValue()); + assertNotNull(account.getId()); + return true; + }); + } } \ No newline at end of file diff --git a/spring-5-security/pom.xml b/spring-5-security/pom.xml index c9b16f8b88..96cbff8938 100644 --- a/spring-5-security/pom.xml +++ b/spring-5-security/pom.xml @@ -9,10 +9,10 @@ spring 5 security sample project - org.springframework.boot - spring-boot-starter-parent - 2.0.0.RELEASE - + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 diff --git a/spring-5-security/src/test/java/com/baeldung/loginextrafields/AbstractExtraLoginFieldsTest.java b/spring-5-security/src/test/java/com/baeldung/loginextrafields/AbstractExtraLoginFieldsIntegrationTest.java similarity index 93% rename from spring-5-security/src/test/java/com/baeldung/loginextrafields/AbstractExtraLoginFieldsTest.java rename to spring-5-security/src/test/java/com/baeldung/loginextrafields/AbstractExtraLoginFieldsIntegrationTest.java index 30b869714f..c46cbd8113 100644 --- a/spring-5-security/src/test/java/com/baeldung/loginextrafields/AbstractExtraLoginFieldsTest.java +++ b/spring-5-security/src/test/java/com/baeldung/loginextrafields/AbstractExtraLoginFieldsIntegrationTest.java @@ -13,7 +13,7 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -public abstract class AbstractExtraLoginFieldsTest { +public abstract class AbstractExtraLoginFieldsIntegrationTest { @Autowired private FilterChainProxy springSecurityFilterChain; diff --git a/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsFullTest.java b/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsFullIntegrationTest.java similarity index 95% rename from spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsFullTest.java rename to spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsFullIntegrationTest.java index 38c219cb5e..20826eb9d7 100644 --- a/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsFullTest.java +++ b/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsFullIntegrationTest.java @@ -29,7 +29,7 @@ import com.baeldung.loginextrafieldscustom.User; @RunWith(SpringRunner.class) @SpringJUnitWebConfig @SpringBootTest(classes = ExtraLoginFieldsApplication.class) -public class LoginFieldsFullTest extends AbstractExtraLoginFieldsTest { +public class LoginFieldsFullIntegrationTest extends AbstractExtraLoginFieldsIntegrationTest { @Test public void givenAccessSecuredResource_whenAuthenticated_thenAuthHasExtraFields() throws Exception { diff --git a/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsSimpleTest.java b/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsSimpleIntegrationTest.java similarity index 95% rename from spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsSimpleTest.java rename to spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsSimpleIntegrationTest.java index 5c0d462772..3d0e2a8d09 100644 --- a/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsSimpleTest.java +++ b/spring-5-security/src/test/java/com/baeldung/loginextrafields/LoginFieldsSimpleIntegrationTest.java @@ -29,7 +29,7 @@ import com.baeldung.loginextrafieldssimple.User; @RunWith(SpringRunner.class) @SpringJUnitWebConfig @SpringBootTest(classes = ExtraLoginFieldsApplication.class) -public class LoginFieldsSimpleTest extends AbstractExtraLoginFieldsTest { +public class LoginFieldsSimpleIntegrationTest extends AbstractExtraLoginFieldsIntegrationTest { @Test public void givenAccessSecuredResource_whenAuthenticated_thenAuthHasExtraFields() throws Exception { diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 67a6930569..bbd5272ae1 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -11,10 +11,10 @@ spring 5 sample project about new features - org.springframework.boot - spring-boot-starter-parent - 2.0.0.RELEASE - + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 diff --git a/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java b/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java index 3e91a0354b..551ea6c84b 100644 --- a/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java +++ b/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java @@ -16,8 +16,6 @@ class IndexRewriteFilter implements WebFilter { .equals("/")) { return webFilterChain.filter(serverWebExchange.mutate() .request(builder -> builder.method(request.getMethod()) - .contextPath(request.getPath() - .toString()) .path("/test")) .build()); } diff --git a/spring-5/src/main/java/com/baeldung/persistence/FooRepository.java b/spring-5/src/main/java/com/baeldung/persistence/FooRepository.java index 1f1e071158..9270d58d35 100644 --- a/spring-5/src/main/java/com/baeldung/persistence/FooRepository.java +++ b/spring-5/src/main/java/com/baeldung/persistence/FooRepository.java @@ -1,10 +1,9 @@ package com.baeldung.persistence; +import com.baeldung.web.Foo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -import com.baeldung.web.Foo; - public interface FooRepository extends JpaRepository, JpaSpecificationExecutor { } diff --git a/spring-5/src/main/java/com/baeldung/web/FooController.java b/spring-5/src/main/java/com/baeldung/web/FooController.java index 925f2b49f4..a09e628421 100644 --- a/spring-5/src/main/java/com/baeldung/web/FooController.java +++ b/spring-5/src/main/java/com/baeldung/web/FooController.java @@ -7,6 +7,7 @@ import org.springframework.http.HttpStatus; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import javax.annotation.PostConstruct; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import java.util.List; @@ -14,6 +15,11 @@ import java.util.List; @RestController("/foos") public class FooController { + @PostConstruct + public void init(){ + System.out.println("test"); + } + @Autowired private FooRepository repo; diff --git a/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java b/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java index 8b9e66213f..ecc677465e 100644 --- a/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java @@ -3,10 +3,12 @@ package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest +@EnableJpaRepositories("com.baeldung.persistence") public class Example1IntegrationTest { @Test diff --git a/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java b/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java index 6ed53ca4e9..e1d56c2fc3 100644 --- a/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java @@ -3,10 +3,12 @@ package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest +@EnableJpaRepositories("com.baeldung.persistence") public class Example2IntegrationTest { @Test diff --git a/spring-5/src/test/java/com/baeldung/Spring5ApplicationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/Spring5ApplicationIntegrationTest.java index af288c3c2d..1bbf0e3775 100644 --- a/spring-5/src/test/java/com/baeldung/Spring5ApplicationIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/Spring5ApplicationIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; @@ -7,6 +8,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest +@Ignore public class Spring5ApplicationIntegrationTest { @Test diff --git a/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java index 5392a59343..fba01726f4 100644 --- a/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java @@ -6,6 +6,7 @@ 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.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.context.support.GenericWebApplicationContext; @@ -13,6 +14,7 @@ import com.baeldung.Spring5Application; @RunWith(SpringRunner.class) @SpringBootTest(classes = Spring5Application.class) +@EnableJpaRepositories("com.baeldung.persistence") public class BeanRegistrationIntegrationTest { @Autowired diff --git a/spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java b/spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java index c52e18ef7f..45012a95aa 100644 --- a/spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java +++ b/spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java @@ -2,6 +2,7 @@ package com.baeldung.jdbc.autogenkey; import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -15,6 +16,7 @@ import com.baeldung.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate; import com.baeldung.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert; @RunWith(SpringRunner.class) +@Ignore public class GetAutoGenKeyByJDBC { @Configuration diff --git a/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java index 756b303f3b..f4749c0d33 100644 --- a/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java @@ -5,6 +5,7 @@ import static org.junit.Assert.assertTrue; import java.math.BigDecimal; import java.time.LocalDate; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -16,18 +17,15 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = Spring5Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@Ignore public class JsonbIntegrationTest { - @Value("${security.user.name}") - private String username; - @Value("${security.user.password}") - private String password; @Autowired private TestRestTemplate template; @Test public void givenId_whenUriIsPerson_thenGetPerson() { - ResponseEntity response = template.withBasicAuth(username, password) + ResponseEntity response = template .getForEntity("/person/1", Person.class); Person person = response.getBody(); assertTrue(person.equals(new Person(2, "Jhon", "jhon1@test.com", 0, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500.0)))); @@ -35,8 +33,8 @@ public class JsonbIntegrationTest { @Test public void whenSendPostAPerson_thenGetOkStatus() { - ResponseEntity response = template.withBasicAuth(username, password) - .postForEntity("/person", "{\"birthDate\":\"07-09-2017\",\"email\":\"jhon1@test.com\",\"person-name\":\"Jhon\",\"id\":10}", Boolean.class); + ResponseEntity response = template.withBasicAuth("user","password"). + postForEntity("/person", "{\"birthDate\":\"07-09-2017\",\"email\":\"jhon1@test.com\",\"person-name\":\"Jhon\",\"id\":10}", Boolean.class); assertTrue(response.getBody()); } diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationIntegrationTest.java similarity index 91% rename from spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationTest.java rename to spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationIntegrationTest.java index ae058bc8ba..35363e0ea3 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationIntegrationTest.java @@ -9,9 +9,9 @@ import org.springframework.test.context.junit.jupiter.DisabledIf; import org.springframework.test.context.junit.jupiter.EnabledIf; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@SpringJUnitConfig(Spring5EnabledAnnotationTest.Config.class) +@SpringJUnitConfig(Spring5EnabledAnnotationIntegrationTest.Config.class) @TestPropertySource(properties = { "tests.enabled=true" }) -public class Spring5EnabledAnnotationTest { +public class Spring5EnabledAnnotationIntegrationTest { @Configuration static class Config { diff --git a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigTest.java b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigIntegrationTest.java similarity index 87% rename from spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigTest.java rename to spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigIntegrationTest.java index 6b0a6f9808..5f81c94aa0 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigIntegrationTest.java @@ -15,8 +15,8 @@ import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; * @ContextConfiguration(classes = SpringJUnitConfigTest.Config.class ) * */ -@SpringJUnitConfig(SpringJUnitConfigTest.Config.class) -public class SpringJUnitConfigTest { +@SpringJUnitConfig(SpringJUnitConfigIntegrationTest.Config.class) +public class SpringJUnitConfigIntegrationTest { @Configuration static class Config { diff --git a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigTest.java b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigIntegrationTest.java similarity index 87% rename from spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigTest.java rename to spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigIntegrationTest.java index c679dce77f..4c3ffda203 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigIntegrationTest.java @@ -16,8 +16,8 @@ import org.springframework.web.context.WebApplicationContext; * @ContextConfiguration(classes = SpringJUnitWebConfigTest.Config.class ) * */ -@SpringJUnitWebConfig(SpringJUnitWebConfigTest.Config.class) -public class SpringJUnitWebConfigTest { +@SpringJUnitWebConfig(SpringJUnitWebConfigIntegrationTest.Config.class) +public class SpringJUnitWebConfigIntegrationTest { @Configuration static class Config { diff --git a/spring-5/src/test/java/com/baeldung/security/SecurityIntegrationTest.java b/spring-5/src/test/java/com/baeldung/security/SecurityIntegrationTest.java index 5680625496..1f8bb549c7 100644 --- a/spring-5/src/test/java/com/baeldung/security/SecurityIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/security/SecurityIntegrationTest.java @@ -2,6 +2,7 @@ package com.baeldung.security; import com.baeldung.SpringSecurity5Application; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -31,6 +32,7 @@ public class SecurityIntegrationTest { } @Test + @Ignore @WithMockUser public void whenHasCredentials_thenSeesGreeting() { this.rest.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("Hello, user"); diff --git a/spring-5/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java b/spring-5/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java index 9a6e997ca1..f9472452ba 100644 --- a/spring-5/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java @@ -5,6 +5,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.server.RequestPredicates; @@ -16,6 +17,7 @@ import reactor.core.publisher.Mono; @RunWith(SpringRunner.class) @SpringBootTest(classes = Spring5Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@EnableJpaRepositories("com.baeldung.persistence") public class WebTestClientIntegrationTest { @LocalServerPort diff --git a/spring-all/pom.xml b/spring-all/pom.xml index f9ced963e7..c509622fca 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -8,10 +8,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-all/src/test/java/org/baeldung/controller/PassParametersControllerTest.java b/spring-all/src/test/java/org/baeldung/controller/PassParametersControllerIntegrationTest.java similarity index 97% rename from spring-all/src/test/java/org/baeldung/controller/PassParametersControllerTest.java rename to spring-all/src/test/java/org/baeldung/controller/PassParametersControllerIntegrationTest.java index 76ac14f292..21084f44ce 100644 --- a/spring-all/src/test/java/org/baeldung/controller/PassParametersControllerTest.java +++ b/spring-all/src/test/java/org/baeldung/controller/PassParametersControllerIntegrationTest.java @@ -23,7 +23,7 @@ import org.springframework.web.servlet.ModelAndView; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration({"classpath:test-mvc.xml"}) -public class PassParametersControllerTest { +public class PassParametersControllerIntegrationTest { private MockMvc mockMvc; @Autowired diff --git a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalTest.java b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalUnitTest.java similarity index 80% rename from spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalTest.java rename to spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalUnitTest.java index c7b95bced4..3c180e91c8 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalUnitTest.java @@ -5,9 +5,9 @@ import org.slf4j.LoggerFactory; import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; -public interface ITransactionalTest { +public interface ITransactionalUnitTest { - Logger log = LoggerFactory.getLogger(ITransactionalTest.class); + Logger log = LoggerFactory.getLogger(ITransactionalUnitTest.class); @BeforeTransaction default void beforeTransaction() { diff --git a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java index b4ac7e8ccf..dde153487d 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java @@ -5,7 +5,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; @ContextConfiguration(classes = TransactionalTestConfiguration.class) -public class TransactionalIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests implements ITransactionalTest { +public class TransactionalIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests implements ITransactionalUnitTest { @Test public void whenDefaultMethodAnnotatedWithBeforeTransaction_thenDefaultMethodIsExecuted() { diff --git a/spring-amqp-simple/pom.xml b/spring-amqp-simple/pom.xml index f3dfbccaec..eb0f25d1a7 100644 --- a/spring-amqp-simple/pom.xml +++ b/spring-amqp-simple/pom.xml @@ -8,10 +8,10 @@ Spring AMQP Simple App - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-aop/pom.xml b/spring-aop/pom.xml index 7cdf9bd7cc..0f4e08baa3 100644 --- a/spring-aop/pom.xml +++ b/spring-aop/pom.xml @@ -8,10 +8,10 @@ spring-aop - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodTest.java b/spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodUnitTest.java similarity index 86% rename from spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodTest.java rename to spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodUnitTest.java index 7ecb2a3ee3..cbdb2db057 100644 --- a/spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodTest.java +++ b/spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodUnitTest.java @@ -2,7 +2,7 @@ package org.baeldung.aspectj; import org.junit.Test; -public class SecuredMethodTest { +public class SecuredMethodUnitTest { @Test public void testMethod() throws Exception { SecuredMethod service = new SecuredMethod(); diff --git a/spring-aop/src/test/java/org/baeldung/logger/CalculatorTest.java b/spring-aop/src/test/java/org/baeldung/logger/CalculatorIntegrationTest.java similarity index 92% rename from spring-aop/src/test/java/org/baeldung/logger/CalculatorTest.java rename to spring-aop/src/test/java/org/baeldung/logger/CalculatorIntegrationTest.java index b1c88c67df..8c31b7f892 100644 --- a/spring-aop/src/test/java/org/baeldung/logger/CalculatorTest.java +++ b/spring-aop/src/test/java/org/baeldung/logger/CalculatorIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(value = {"classpath:springAop-applicationContext.xml"}) -public class CalculatorTest { +public class CalculatorIntegrationTest { @Autowired private SampleAdder sampleAdder; diff --git a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksTest.java b/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java similarity index 96% rename from spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksTest.java rename to spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java index 2a71970637..eaf73e4a4a 100644 --- a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksTest.java +++ b/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = ChunksConfig.class) -public class ChunksTest { +public class ChunksIntegrationTest { @Autowired private JobLauncherTestUtils jobLauncherTestUtils; diff --git a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsTest.java b/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java similarity index 96% rename from spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsTest.java rename to spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java index 20379b58fe..322b17bd55 100644 --- a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsTest.java +++ b/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = TaskletsConfig.class) -public class TaskletsTest { +public class TaskletsIntegrationTest { @Autowired private JobLauncherTestUtils jobLauncherTestUtils; diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index 03ce9b6906..ff5bca615b 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -15,25 +15,6 @@ ../parent-boot-2 - - org.springframework.boot @@ -107,6 +88,28 @@
+ + thin-jar + + + + org.springframework.boot.experimental + spring-boot-thin-maven-plugin + ${thin.version} + + + + resolve + + resolve + + false + + + + + + diff --git a/spring-boot-ctx-fluent/README.md b/spring-boot-ctx-fluent/README.md new file mode 100644 index 0000000000..0b4b9c1271 --- /dev/null +++ b/spring-boot-ctx-fluent/README.md @@ -0,0 +1,4 @@ + +### Relevant Articles: + +- [Context Hierarchy with the Spring Boot Fluent Builder API](http://www.baeldung.com/spring-boot-context-hierarchy) diff --git a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml index 6ae6572ca9..96647ea0f1 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml +++ b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml @@ -6,10 +6,10 @@ greeter-spring-boot-autoconfigure 0.0.1-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 UTF-8 diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml index 9db76759ec..a2c96a8555 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml +++ b/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml @@ -7,10 +7,10 @@ 0.0.1-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml index e771cbaa8d..7bf13eebc8 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml +++ b/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml @@ -6,10 +6,10 @@ greeter-spring-boot-starter 0.0.1-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 UTF-8 diff --git a/spring-boot-custom-starter/greeter/pom.xml b/spring-boot-custom-starter/greeter/pom.xml index 6143992088..aa45b8e6a4 100644 --- a/spring-boot-custom-starter/greeter/pom.xml +++ b/spring-boot-custom-starter/greeter/pom.xml @@ -6,9 +6,9 @@ greeter 0.0.1-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 \ No newline at end of file diff --git a/spring-boot-gradle/.gitignore b/spring-boot-gradle/.gitignore new file mode 100644 index 0000000000..192221b47d --- /dev/null +++ b/spring-boot-gradle/.gitignore @@ -0,0 +1,2 @@ +.gradle/ +build/ \ No newline at end of file diff --git a/spring-boot-gradle/build.gradle b/spring-boot-gradle/build.gradle index e602c485a9..96055536c3 100644 --- a/spring-boot-gradle/build.gradle +++ b/spring-boot-gradle/build.gradle @@ -1,12 +1,16 @@ buildscript { ext { - springBootVersion = '2.0.0.RELEASE' + springBootPlugin = 'org.springframework.boot:spring-boot-gradle-plugin' + springBootVersion = '2.0.2.RELEASE' + thinPlugin = 'org.springframework.boot.experimental:spring-boot-thin-gradle-plugin' + thinVersion = '1.0.11.RELEASE' } repositories { mavenCentral() } dependencies { - classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") + classpath("${springBootPlugin}:${springBootVersion}") + classpath("${thinPlugin}:${thinVersion}") } } @@ -14,6 +18,8 @@ apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' +//add tasks thinJar and thinResolve for thin JAR deployments +apply plugin: 'org.springframework.boot.experimental.thin-launcher' group = 'org.baeldung' version = '0.0.1-SNAPSHOT' @@ -23,7 +29,6 @@ repositories { mavenCentral() } - dependencies { compile('org.springframework.boot:spring-boot-starter') testCompile('org.springframework.boot:spring-boot-starter-test') @@ -42,3 +47,21 @@ bootJar { // attributes 'Start-Class': 'org.baeldung.DemoApplication' // } } + +//Enable this to generate and use a pom.xml file +apply plugin: 'maven' + +//If you want to customize the generated pom.xml you can edit this task and add it as a dependency to the bootJar task +task createPom { + def basePath = 'build/resources/main/META-INF/maven' + doLast { + pom { + withXml(dependencyManagement.pomConfigurer) + }.writeTo("${basePath}/${project.group}/${project.name}/pom.xml") + } +} +//Uncomment the following to use your custom generated pom.xml +bootJar.dependsOn = [createPom] + +//Enable this to generate and use a thin.properties file +//bootJar.dependsOn = [thinProperties] \ No newline at end of file diff --git a/spring-boot-gradle/gradle/wrapper/gradle-wrapper.properties b/spring-boot-gradle/gradle/wrapper/gradle-wrapper.properties index 44d9d03d80..a8868a918a 100644 --- a/spring-boot-gradle/gradle/wrapper/gradle-wrapper.properties +++ b/spring-boot-gradle/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Tue Feb 06 12:27:20 CET 2018 +#Fri Jun 01 20:39:48 CEST 2018 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.5.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-4.5.1-all.zip diff --git a/spring-boot-jasypt/README.md b/spring-boot-jasypt/README.md new file mode 100644 index 0000000000..5df2a4a6e5 --- /dev/null +++ b/spring-boot-jasypt/README.md @@ -0,0 +1,4 @@ + +### Relevant Articles: + +- [Spring Boot Configuration with Jasypt](http://www.baeldung.com/spring-boot-jasypt) diff --git a/spring-boot-keycloak/pom.xml b/spring-boot-keycloak/pom.xml index d2df261b2f..b7b15935ec 100644 --- a/spring-boot-keycloak/pom.xml +++ b/spring-boot-keycloak/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-5 + parent-boot-1 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-boot-ops/README.md b/spring-boot-ops/README.md new file mode 100644 index 0000000000..02c4c100aa --- /dev/null +++ b/spring-boot-ops/README.md @@ -0,0 +1,3 @@ +### Relevant articles + +- [Deploy a Spring Boot WAR into a Tomcat Server](http://www.baeldung.com/spring-boot-war-tomcat-deploy) diff --git a/spring-boot-ops/docker/Dockerfile b/spring-boot-ops/docker/Dockerfile new file mode 100644 index 0000000000..85db5c7bed --- /dev/null +++ b/spring-boot-ops/docker/Dockerfile @@ -0,0 +1,16 @@ +# Alpine Linux with OpenJDK JRE +FROM openjdk:8-jre-alpine +RUN apk add --no-cache bash + +# copy fat WAR +COPY spring-boot-ops.war /app.war + +# copy fat WAR +COPY logback.xml /logback.xml + +COPY run.sh /run.sh + +# runs application +#CMD ["/usr/bin/java", "-jar", "-Dspring.profiles.active=default", "-Dlogging.config=/logback.xml", "/app.war"] + +ENTRYPOINT ["/run.sh"] diff --git a/spring-boot-ops/docker/logback.xml b/spring-boot-ops/docker/logback.xml new file mode 100644 index 0000000000..aad6d3fcb3 --- /dev/null +++ b/spring-boot-ops/docker/logback.xml @@ -0,0 +1,15 @@ + + + + + /var/log/WebjarsdemoApplication/application.log + true + + %-7d{yyyy-MM-dd HH:mm:ss:SSS} %m%n + + + + + + + diff --git a/spring-boot-ops/docker/run.sh b/spring-boot-ops/docker/run.sh new file mode 100755 index 0000000000..aeecc29371 --- /dev/null +++ b/spring-boot-ops/docker/run.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +java -Dspring.profiles.active=$1 -Dlogging.config=/logback.xml -jar /app.war + diff --git a/spring-boot-ops/pom.xml b/spring-boot-ops/pom.xml index 0d0ccc0ef2..b34fef8e6f 100644 --- a/spring-boot-ops/pom.xml +++ b/spring-boot-ops/pom.xml @@ -11,20 +11,44 @@ spring-boot-ops Demo project for Spring Boot - - org.springframework.boot - spring-boot-starter-parent - 2.0.1.RELEASE - - + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + org.baeldung.boot.Application UTF-8 UTF-8 1.8 + 3.1.1 + 3.3.7-1 + + + org.springframework.boot spring-boot-starter-web @@ -32,7 +56,7 @@ org.springframework.boot - spring-boot-starter-tomcat + spring-boot-starter-thymeleaf provided @@ -41,6 +65,59 @@ spring-boot-starter-test test + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-mail + + + + org.springframework.boot + spring-boot-starter-actuator + + + + com.h2database + h2 + runtime + + + + javax.persistence + javax.persistence-api + 2.2 + + + + com.google.guava + guava + 18.0 + + + + org.subethamail + subethasmtp + 3.1.7 + test + + + + org.webjars + bootstrap + ${bootstrap.version} + + + + org.webjars + jquery + ${jquery.version} + + @@ -50,8 +127,59 @@ org.springframework.boot spring-boot-maven-plugin + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + com.baeldung.webjar.WebjarsdemoApplication + ${project.basedir}/docker + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + + + **/AutoconfigurationTest.java + + + + + + + json + + + + + + + diff --git a/spring-boot/src/main/java/com/baeldung/shutdown/Application.java b/spring-boot-ops/src/main/java/com/baeldung/shutdown/Application.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/shutdown/Application.java rename to spring-boot-ops/src/main/java/com/baeldung/shutdown/Application.java diff --git a/spring-boot/src/main/java/com/baeldung/shutdown/ShutdownConfig.java b/spring-boot-ops/src/main/java/com/baeldung/shutdown/ShutdownConfig.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/shutdown/ShutdownConfig.java rename to spring-boot-ops/src/main/java/com/baeldung/shutdown/ShutdownConfig.java diff --git a/spring-boot/src/main/java/com/baeldung/shutdown/TerminateBean.java b/spring-boot-ops/src/main/java/com/baeldung/shutdown/TerminateBean.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/shutdown/TerminateBean.java rename to spring-boot-ops/src/main/java/com/baeldung/shutdown/TerminateBean.java diff --git a/spring-boot/src/main/java/com/baeldung/shutdown/shutdown/ShutdownController.java b/spring-boot-ops/src/main/java/com/baeldung/shutdown/shutdown/ShutdownController.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/shutdown/shutdown/ShutdownController.java rename to spring-boot-ops/src/main/java/com/baeldung/shutdown/shutdown/ShutdownController.java diff --git a/spring-boot/src/main/java/com/baeldung/webjar/TestController.java b/spring-boot-ops/src/main/java/com/baeldung/webjar/TestController.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/webjar/TestController.java rename to spring-boot-ops/src/main/java/com/baeldung/webjar/TestController.java diff --git a/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java b/spring-boot-ops/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java rename to spring-boot-ops/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/Application.java b/spring-boot-ops/src/main/java/org/baeldung/boot/Application.java new file mode 100644 index 0000000000..c1b6558b26 --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/Application.java @@ -0,0 +1,14 @@ +package org.baeldung.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; + +@SpringBootApplication +public class Application { + private static ApplicationContext applicationContext; + + public static void main(String[] args) { + applicationContext = SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java b/spring-boot-ops/src/main/java/org/baeldung/boot/config/WebConfig.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/config/WebConfig.java diff --git a/spring-boot/src/main/java/org/baeldung/boot/controller/GenericEntityController.java b/spring-boot-ops/src/main/java/org/baeldung/boot/controller/GenericEntityController.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/controller/GenericEntityController.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/controller/GenericEntityController.java diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java similarity index 89% rename from spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java index b07e11e01a..e00d0ad312 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java @@ -1,6 +1,6 @@ package org.baeldung.boot.converter; -import com.baeldung.toggle.Employee; +import org.baeldung.boot.domain.Employee; import org.springframework.core.convert.converter.Converter; public class StringToEmployeeConverter implements Converter { diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToLocalDateTimeConverter.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToLocalDateTimeConverter.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/converter/StringToLocalDateTimeConverter.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToLocalDateTimeConverter.java diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java similarity index 90% rename from spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java index a6e0400845..762d237156 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java @@ -1,6 +1,6 @@ package org.baeldung.boot.converter.controller; -import com.baeldung.toggle.Employee; +import org.baeldung.boot.domain.Employee; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Employee.java b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Employee.java new file mode 100644 index 0000000000..8242e53200 --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Employee.java @@ -0,0 +1,37 @@ +package org.baeldung.boot.domain; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + + @Id + private long id; + private double salary; + + public Employee() { + } + + public Employee(long id, double salary) { + this.id = id; + this.salary = salary; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + +} diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/domain/GenericEntity.java b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/GenericEntity.java new file mode 100644 index 0000000000..f1c936e432 --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/GenericEntity.java @@ -0,0 +1,42 @@ +package org.baeldung.boot.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-boot-ops/src/main/java/org/baeldung/boot/domain/Modes.java b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Modes.java new file mode 100644 index 0000000000..dcba064e8c --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Modes.java @@ -0,0 +1,6 @@ +package org.baeldung.boot.domain; + +public enum Modes { + + ALPHA, BETA; +} diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java b/spring-boot-ops/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java new file mode 100644 index 0000000000..d897e17afe --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java @@ -0,0 +1,7 @@ +package org.baeldung.boot.repository; + +import org.baeldung.boot.domain.GenericEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface GenericEntityRepository extends JpaRepository { +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java b/spring-boot-ops/src/main/java/org/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java diff --git a/spring-boot/src/main/java/org/baeldung/boot/web/resolver/Version.java b/spring-boot-ops/src/main/java/org/baeldung/boot/web/resolver/Version.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/web/resolver/Version.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/web/resolver/Version.java diff --git a/spring-boot/src/main/resources/templates/index.html b/spring-boot-ops/src/main/resources/templates/index.html similarity index 100% rename from spring-boot/src/main/resources/templates/index.html rename to spring-boot-ops/src/main/resources/templates/index.html diff --git a/spring-boot/src/test/java/com/baeldung/shutdown/ShutdownApplicationIntegrationTest.java b/spring-boot-ops/src/test/java/com/baeldung/shutdown/ShutdownApplicationIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/shutdown/ShutdownApplicationIntegrationTest.java rename to spring-boot-ops/src/test/java/com/baeldung/shutdown/ShutdownApplicationIntegrationTest.java diff --git a/spring-boot-ops/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationTests.java b/spring-boot-ops/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationIntegrationTest.java similarity index 84% rename from spring-boot-ops/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationTests.java rename to spring-boot-ops/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationIntegrationTest.java index 4c0d4d577a..a10ebbbd35 100644 --- a/spring-boot-ops/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationTests.java +++ b/spring-boot-ops/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class SpringBootTomcatApplicationTests { +public class SpringBootTomcatApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-boot/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java b/spring-boot-ops/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java rename to spring-boot-ops/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java b/spring-boot-ops/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java rename to spring-boot-ops/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java b/spring-boot-ops/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java rename to spring-boot-ops/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java b/spring-boot-ops/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java rename to spring-boot-ops/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java diff --git a/spring-boot-ops/src/test/resources/application-integrationtest.properties b/spring-boot-ops/src/test/resources/application-integrationtest.properties new file mode 100644 index 0000000000..bcd03226d3 --- /dev/null +++ b/spring-boot-ops/src/test/resources/application-integrationtest.properties @@ -0,0 +1,4 @@ +spring.datasource.url=jdbc:mysql://localhost:3306/employee_int_test +spring.datasource.username=root +spring.datasource.password=root + diff --git a/spring-boot-ops/src/test/resources/application.properties b/spring-boot-ops/src/test/resources/application.properties new file mode 100644 index 0000000000..2095a82a14 --- /dev/null +++ b/spring-boot-ops/src/test/resources/application.properties @@ -0,0 +1,7 @@ +spring.mail.host=localhost +spring.mail.port=8025 +spring.mail.properties.mail.smtp.auth=false + +management.endpoints.web.exposure.include=* +management.endpoint.shutdown.enabled=true +endpoints.shutdown.enabled=true \ No newline at end of file diff --git a/spring-boot-property-exp/property-exp-default-config/pom.xml b/spring-boot-property-exp/property-exp-default-config/pom.xml index e4cbaebf56..0ac4a31c7c 100644 --- a/spring-boot-property-exp/property-exp-default-config/pom.xml +++ b/spring-boot-property-exp/property-exp-default-config/pom.xml @@ -8,10 +8,10 @@ jar - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 094a70654a..595e13cd9f 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -4,12 +4,8 @@ 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) - [Guide to Spring WebUtils and ServletRequestUtils](http://www.baeldung.com/spring-webutils-servletrequestutils) @@ -29,11 +25,11 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Guide to Spring Type Conversions](http://www.baeldung.com/spring-type-conversions) - [Quick Guide on data.sql and schema.sql Files in Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql) - [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8) -- [A Quick Guide to Maven Wrapper](http://www.baeldung.com/maven-wrapper) - [An Introduction to Kong](http://www.baeldung.com/kong) - [Spring Boot Customize Whitelabel Error Page](http://www.baeldung.com/spring-boot-custom-error-page) - [Spring Boot: Configuring a Main Class](http://www.baeldung.com/spring-boot-main-class) -- [Shutdown a Spring Boot Application](http://www.baeldung.com/spring-boot-shutdown) - [A Quick Intro to the SpringBootServletInitializer](http://www.baeldung.com/spring-boot-servlet-initializer) - [How to Define a Spring Boot Filter?](http://www.baeldung.com/spring-boot-add-filter) - [How to Change the Default Port in Spring Boot](http://www.baeldung.com/spring-boot-change-port) +- [Spring Boot Exit Codes](http://www.baeldung.com/spring-boot-exit-codes) +- [Guide to the Favicon in Spring Boot](http://www.baeldung.com/spring-boot-favicon) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index afc80eb68b..c1b21b9b5e 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -38,11 +38,6 @@ graphql-spring-boot-starter 3.6.0 - - com.graphql-java - graphiql-spring-boot-starter - 3.6.0 - com.graphql-java graphql-java-tools @@ -84,27 +79,6 @@ 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 @@ -218,9 +192,6 @@ org.baeldung.demo.DemoApplication - 3.1.1 - 3.3.7-1 - 3.1.7 8.5.11 2.4.1.Final 1.9.0 diff --git a/spring-boot/src/main/resources/templates/customer.html b/spring-boot/src/main/resources/templates/customer.html deleted file mode 100644 index c8f5a25d5e..0000000000 --- a/spring-boot/src/main/resources/templates/customer.html +++ /dev/null @@ -1,16 +0,0 @@ - - - -Customer Page - - - -
-
-Contact Info:
- -
-

-
- - \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/customers.html b/spring-boot/src/main/resources/templates/customers.html deleted file mode 100644 index 5a060d31da..0000000000 --- a/spring-boot/src/main/resources/templates/customers.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - -
-

- Hello, --name--. -

- - - - - - - - - - - - - - - - - -
IDNameAddressService Rendered
Text ...Text ...Text ...Text...
- -
- - - diff --git a/spring-boot/src/main/resources/templates/displayallbeans.html b/spring-boot/src/main/resources/templates/displayallbeans.html deleted file mode 100644 index 5fc78a7fca..0000000000 --- a/spring-boot/src/main/resources/templates/displayallbeans.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - Baeldung - - -

-

- - diff --git a/spring-boot/src/main/resources/templates/error-404.html b/spring-boot/src/main/resources/templates/error-404.html deleted file mode 100644 index cf68032596..0000000000 --- a/spring-boot/src/main/resources/templates/error-404.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - -
-
-

Sorry, we couldn't find the page you were looking for.

-

Go Home

-
- - \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/error-500.html b/spring-boot/src/main/resources/templates/error-500.html deleted file mode 100644 index 5ddf458229..0000000000 --- a/spring-boot/src/main/resources/templates/error-500.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - -
-
-

Sorry, something went wrong!

- -

We're fixing it.

-

Go Home

-
- - \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/error.html b/spring-boot/src/main/resources/templates/error.html deleted file mode 100644 index bc517913b2..0000000000 --- a/spring-boot/src/main/resources/templates/error.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - -
-
-

Something went wrong!

- -

Our Engineers are on it.

-

Go Home

-
- - diff --git a/spring-boot/src/main/resources/templates/error/404.html b/spring-boot/src/main/resources/templates/error/404.html deleted file mode 100644 index df83ce219b..0000000000 --- a/spring-boot/src/main/resources/templates/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-boot/src/main/resources/templates/external.html b/spring-boot/src/main/resources/templates/external.html deleted file mode 100644 index 2f9cc76961..0000000000 --- a/spring-boot/src/main/resources/templates/external.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - -
-
-

Customer Portal

-
-
-

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam - erat lectus, vehicula feugiat ultricies at, tempus sed ante. Cras - arcu erat, lobortis vitae quam et, mollis pharetra odio. Nullam sit - amet congue ipsum. Nunc dapibus odio ut ligula venenatis porta non - id dui. Duis nec tempor tellus. Suspendisse id blandit ligula, sit - amet varius mauris. Nulla eu eros pharetra, tristique dui quis, - vehicula libero. Aenean a neque sit amet tellus porttitor rutrum nec - at leo.

- -

Existing Customers

-
- Enter the intranet: customers -
-
- -
- - - - diff --git a/spring-boot/src/main/resources/templates/international.html b/spring-boot/src/main/resources/templates/international.html deleted file mode 100644 index e0cfb5143b..0000000000 --- a/spring-boot/src/main/resources/templates/international.html +++ /dev/null @@ -1,20 +0,0 @@ - - - - -Home - - - - -

- -

-: - - - \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/layout.html b/spring-boot/src/main/resources/templates/layout.html deleted file mode 100644 index bab0c2982b..0000000000 --- a/spring-boot/src/main/resources/templates/layout.html +++ /dev/null @@ -1,18 +0,0 @@ - - - -Customer Portal - - - - - \ No newline at end of file diff --git a/spring-boot/src/main/resources/templates/other.html b/spring-boot/src/main/resources/templates/other.html deleted file mode 100644 index d13373f9fe..0000000000 --- a/spring-boot/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-boot/src/main/resources/templates/utils.html b/spring-boot/src/main/resources/templates/utils.html deleted file mode 100644 index 93030f424f..0000000000 --- a/spring-boot/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-cloud-data-flow/batch-job/pom.xml b/spring-cloud-data-flow/batch-job/pom.xml index 123c4aeda6..08439065a4 100644 --- a/spring-cloud-data-flow/batch-job/pom.xml +++ b/spring-cloud-data-flow/batch-job/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-cloud-data-flow/data-flow-server/pom.xml b/spring-cloud-data-flow/data-flow-server/pom.xml index f0d513ce4d..1b81e1ba2d 100644 --- a/spring-cloud-data-flow/data-flow-server/pom.xml +++ b/spring-cloud-data-flow/data-flow-server/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-cloud-data-flow/data-flow-shell/pom.xml b/spring-cloud-data-flow/data-flow-shell/pom.xml index debbe44a4a..0166aa79c2 100644 --- a/spring-cloud-data-flow/data-flow-shell/pom.xml +++ b/spring-cloud-data-flow/data-flow-shell/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-cloud-data-flow/log-sink/pom.xml b/spring-cloud-data-flow/log-sink/pom.xml index 6e541ae3fa..ab367fadd7 100644 --- a/spring-cloud-data-flow/log-sink/pom.xml +++ b/spring-cloud-data-flow/log-sink/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-cloud-data-flow/time-processor/pom.xml b/spring-cloud-data-flow/time-processor/pom.xml index 42d0fa434f..79bae89857 100644 --- a/spring-cloud-data-flow/time-processor/pom.xml +++ b/spring-cloud-data-flow/time-processor/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-cloud-data-flow/time-source/pom.xml b/spring-cloud-data-flow/time-source/pom.xml index 2a50c9b0d0..17d2f5c693 100644 --- a/spring-cloud-data-flow/time-source/pom.xml +++ b/spring-cloud-data-flow/time-source/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/config/pom.xml b/spring-cloud/spring-cloud-bootstrap/config/pom.xml index ace46395c0..14a926fc2c 100644 --- a/spring-cloud/spring-cloud-bootstrap/config/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/config/pom.xml @@ -6,10 +6,10 @@ 1.0.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml b/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml index 7a3ffd81cd..f94d8829f6 100644 --- a/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml @@ -7,10 +7,10 @@ 1.0.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml index 5001b35fb5..fc69c16738 100644 --- a/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml @@ -6,10 +6,10 @@ 1.0.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml b/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml index 2552752e29..c0d920d373 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml @@ -8,10 +8,10 @@ 1.0.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml b/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml index 857ee486c0..3aa2db8f65 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml @@ -8,10 +8,10 @@ 1.0.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml b/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml index 743281d346..8735e24d48 100644 --- a/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml @@ -6,10 +6,10 @@ 1.0.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-config/pom.xml b/spring-cloud/spring-cloud-config/pom.xml index 100b421a55..0a8f4f9dc3 100644 --- a/spring-cloud/spring-cloud-config/pom.xml +++ b/spring-cloud/spring-cloud-config/pom.xml @@ -9,10 +9,10 @@ pom - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-gateway/pom.xml b/spring-cloud/spring-cloud-gateway/pom.xml index 4cc45cc6b3..aa523ec604 100644 --- a/spring-cloud/spring-cloud-gateway/pom.xml +++ b/spring-cloud/spring-cloud-gateway/pom.xml @@ -14,21 +14,30 @@ ..
+ + + + org.springframework.cloud + spring-cloud-gateway + ${cloud.version} + pom + import + + + + + + org.springframework.cloud + spring-cloud-starter-gateway + org.springframework.boot - spring-boot-actuator - ${version} + spring-boot-starter-actuator org.springframework.boot spring-boot-starter-webflux - ${version} - - - org.springframework.cloud - spring-cloud-gateway-core - ${version} @@ -39,12 +48,10 @@ javax.validation validation-api - 2.0.0.Final io.projectreactor.ipc reactor-netty - 0.7.0.M1 @@ -70,8 +77,9 @@ UTF-8 3.7.0 - 1.4.2.RELEASE - 2.0.0.M6 + 2.0.0.RELEASE + 2.0.0.RELEASE + 2.0.0.RC2 diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/spring/cloud/GatewayApplication.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/spring/cloud/GatewayApplication.java index 4d5f61315f..ba384749df 100644 --- a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/spring/cloud/GatewayApplication.java +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/spring/cloud/GatewayApplication.java @@ -9,4 +9,5 @@ public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } + } \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/src/main/resources/application.yml b/spring-cloud/spring-cloud-gateway/src/main/resources/application.yml index 8b981f8071..2450638e46 100644 --- a/spring-cloud/spring-cloud-gateway/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-gateway/src/main/resources/application.yml @@ -8,6 +8,9 @@ spring: uri: http://www.baeldung.com predicates: - Path=/baeldung + management: - security: - enabled: false \ No newline at end of file + endpoints: + web: + exposure: + include: "*" diff --git a/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationTests.java b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationIntegrationTest.java similarity index 84% rename from spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationTests.java rename to spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationIntegrationTest.java index 5ccc49eaa7..2440b97aaf 100644 --- a/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationTests.java +++ b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class KubernetesBackendApplicationTests { +public class KubernetesBackendApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationTests.java b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationIntegrationTest.java similarity index 84% rename from spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationTests.java rename to spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationIntegrationTest.java index 0e34eb45f8..19ad9676cb 100644 --- a/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationTests.java +++ b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class KubernetesFrontendApplicationTests { +public class KubernetesFrontendApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud/spring-cloud-kubernetes/pom.xml b/spring-cloud/spring-cloud-kubernetes/pom.xml index 96388c3672..61fd84ca27 100644 --- a/spring-cloud/spring-cloud-kubernetes/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/pom.xml @@ -14,10 +14,10 @@ - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 4.0.0 diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml index 8da8ef6141..664ab96576 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml @@ -10,10 +10,10 @@ Simple books API - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml index e083986890..814f5edfcb 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml @@ -12,10 +12,10 @@ Spring Cloud REST configuration server - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml index c7d647a154..f3ce213540 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml @@ -10,10 +10,10 @@ Spring Cloud REST server - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml index d97ab43bfe..27e327110a 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml @@ -10,10 +10,10 @@ Simple reviews API - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-ribbon-client/pom.xml b/spring-cloud/spring-cloud-ribbon-client/pom.xml index cada10ec35..64682c6173 100644 --- a/spring-cloud/spring-cloud-ribbon-client/pom.xml +++ b/spring-cloud/spring-cloud-ribbon-client/pom.xml @@ -9,10 +9,10 @@ Introduction to Spring Cloud Rest Client with Netflix Ribbon - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-core/pom.xml b/spring-core/pom.xml index 93ff73bb37..032f2214d2 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -86,7 +86,6 @@ 1.10.19 1.4.4.RELEASE - 4.3.4.RELEASE 1 20.0 2.6 diff --git a/spring-core/src/main/java/com/baeldung/collection/BaeldungBean.java b/spring-core/src/main/java/com/baeldung/collection/BaeldungBean.java new file mode 100644 index 0000000000..6d7351df02 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/collection/BaeldungBean.java @@ -0,0 +1,18 @@ +package com.baeldung.collection; + +/** + * Created by Gebruiker on 5/22/2018. + */ +public class BaeldungBean { + + private String name; + + public BaeldungBean(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } +} diff --git a/spring-core/src/main/java/com/baeldung/collection/CollectionConfig.java b/spring-core/src/main/java/com/baeldung/collection/CollectionConfig.java new file mode 100644 index 0000000000..fbae2963e5 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/collection/CollectionConfig.java @@ -0,0 +1,50 @@ +package com.baeldung.collection; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; + +import java.util.*; + +@Configuration +public class CollectionConfig { + + @Bean + public CollectionsBean getCollectionsBean() { + return new CollectionsBean(new HashSet<>(Arrays.asList("John", "Adam", "Harry"))); + } + + @Bean + public List nameList(){ + return Arrays.asList("John", "Adam", "Harry", null); + } + + @Bean + public Map nameMap(){ + Map nameMap = new HashMap<>(); + nameMap.put(1, "John"); + nameMap.put(2, "Adam"); + nameMap.put(3, "Harry"); + return nameMap; + } + + @Bean + @Qualifier("CollectionsBean") + @Order(2) + public BaeldungBean getElement() { + return new BaeldungBean("John"); + } + + @Bean + @Order(3) + public BaeldungBean getAnotherElement() { + return new BaeldungBean("Adam"); + } + + @Bean + @Order(1) + public BaeldungBean getOneMoreElement() { + return new BaeldungBean("Harry"); + } +} diff --git a/spring-core/src/main/java/com/baeldung/collection/CollectionInjectionDemo.java b/spring-core/src/main/java/com/baeldung/collection/CollectionInjectionDemo.java new file mode 100644 index 0000000000..2e0d9eb8d8 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/collection/CollectionInjectionDemo.java @@ -0,0 +1,20 @@ +package com.baeldung.collection; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +/** + * Created by Gebruiker on 5/18/2018. + */ +public class CollectionInjectionDemo { + + public static void main(String[] args) { + + ApplicationContext context = new AnnotationConfigApplicationContext(CollectionConfig.class); + CollectionsBean collectionsBean = context.getBean(CollectionsBean.class); + collectionsBean.printNameList(); + collectionsBean.printNameSet(); + collectionsBean.printNameMap(); + collectionsBean.printBeanList(); + } +} diff --git a/spring-core/src/main/java/com/baeldung/collection/CollectionsBean.java b/spring-core/src/main/java/com/baeldung/collection/CollectionsBean.java new file mode 100644 index 0000000000..a0e985267f --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/collection/CollectionsBean.java @@ -0,0 +1,54 @@ +package com.baeldung.collection; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Created by Gebruiker on 5/18/2018. + */ +public class CollectionsBean { + + @Autowired + private List nameList; + + private Set nameSet; + + private Map nameMap; + + @Autowired(required = false) + @Qualifier("CollectionsBean") + private List beanList = new ArrayList<>(); + + public CollectionsBean() { + } + + public CollectionsBean(Set strings) { + this.nameSet = strings; + } + + @Autowired + public void setNameMap(Map nameMap) { + this.nameMap = nameMap; + } + + public void printNameList() { + System.out.println(nameList); + } + + public void printNameSet() { + System.out.println(nameSet); + } + + public void printNameMap() { + System.out.println(nameMap); + } + + public void printBeanList() { + System.out.println(beanList); + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependson/DriverApplication.java b/spring-core/src/main/java/com/baeldung/dependson/DriverApplication.java new file mode 100644 index 0000000000..166f388aa3 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependson/DriverApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.dependson; + +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import com.baeldung.dependson.config.Config; +import com.baeldung.dependson.file.processor.FileProcessor; + +public class DriverApplication { + public static void main(String[] args) { + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class); + ctx.getBean(FileProcessor.class); + ctx.close(); + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependson/config/Config.java b/spring-core/src/main/java/com/baeldung/dependson/config/Config.java new file mode 100644 index 0000000000..8d96707ba6 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependson/config/Config.java @@ -0,0 +1,38 @@ +package com.baeldung.dependson.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; +import org.springframework.context.annotation.Lazy; + +import com.baeldung.dependson.file.processor.FileProcessor; +import com.baeldung.dependson.file.reader.FileReader; +import com.baeldung.dependson.file.writer.FileWriter; +import com.baeldung.dependson.shared.File; + +@Configuration +@ComponentScan("com.baeldung.dependson") +public class Config { + + @Autowired + File file; + + @Bean("fileProcessor") + @DependsOn({"fileReader","fileWriter"}) + @Lazy + public FileProcessor fileProcessor(){ + return new FileProcessor(file); + } + + @Bean("fileReader") + public FileReader fileReader(){ + return new FileReader(file); + } + + @Bean("fileWriter") + public FileWriter fileWriter(){ + return new FileWriter(file); + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependson/file/processor/FileProcessor.java b/spring-core/src/main/java/com/baeldung/dependson/file/processor/FileProcessor.java new file mode 100644 index 0000000000..f5d55dc032 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependson/file/processor/FileProcessor.java @@ -0,0 +1,19 @@ +package com.baeldung.dependson.file.processor; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.baeldung.dependson.file.reader.FileReader; +import com.baeldung.dependson.file.writer.FileWriter; +import com.baeldung.dependson.shared.File; + +public class FileProcessor { + + File file; + + public FileProcessor(File file){ + this.file = file; + if(file.getText().contains("write") && file.getText().contains("read")){ + file.setText("processed"); + } + } +} \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/dependson/file/reader/FileReader.java b/spring-core/src/main/java/com/baeldung/dependson/file/reader/FileReader.java new file mode 100644 index 0000000000..b6ff446534 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependson/file/reader/FileReader.java @@ -0,0 +1,12 @@ +package com.baeldung.dependson.file.reader; + +import com.baeldung.dependson.shared.File; + +public class FileReader { + + public FileReader(File file) { + file.setText("read"); + } + + public void readFile() {} +} diff --git a/spring-core/src/main/java/com/baeldung/dependson/file/writer/FileWriter.java b/spring-core/src/main/java/com/baeldung/dependson/file/writer/FileWriter.java new file mode 100644 index 0000000000..f251166c80 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependson/file/writer/FileWriter.java @@ -0,0 +1,13 @@ +package com.baeldung.dependson.file.writer; + +import com.baeldung.dependson.shared.File; + + +public class FileWriter { + + public FileWriter(File file){ + file.setText("write"); + } + + public void writeFile(){} +} diff --git a/spring-core/src/main/java/com/baeldung/dependson/shared/File.java b/spring-core/src/main/java/com/baeldung/dependson/shared/File.java new file mode 100644 index 0000000000..c1b1badc43 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependson/shared/File.java @@ -0,0 +1,17 @@ +package com.baeldung.dependson.shared; + +import org.springframework.stereotype.Service; + +@Service +public class File { + + private String text = ""; + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = this.text+text; + } +} diff --git a/spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionTest.java b/spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionIntegrationTest.java similarity index 96% rename from spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionTest.java rename to spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionIntegrationTest.java index 57c1927e58..faaadfcbc3 100644 --- a/spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionTest.java +++ b/spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionIntegrationTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -public class DependencyInjectionTest { +public class DependencyInjectionIntegrationTest { @Test public void givenAutowiredAnnotation_WhenSetOnSetter_ThenDependencyValid() { diff --git a/spring-core/src/test/java/com/baeldung/dependson/config/TestConfig.java b/spring-core/src/test/java/com/baeldung/dependson/config/TestConfig.java new file mode 100644 index 0000000000..f4b2e39ebc --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/dependson/config/TestConfig.java @@ -0,0 +1,59 @@ +package com.baeldung.dependson.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; +import org.springframework.context.annotation.Lazy; + +import com.baeldung.dependson.file.processor.FileProcessor; +import com.baeldung.dependson.file.reader.FileReader; +import com.baeldung.dependson.file.writer.FileWriter; +import com.baeldung.dependson.shared.File; + +@Configuration +@ComponentScan("com.baeldung.dependson") +public class TestConfig { + + @Autowired + File file; + + @Bean("fileProcessor") + @DependsOn({"fileReader","fileWriter"}) + @Lazy + public FileProcessor fileProcessor(){ + return new FileProcessor(file); + } + + @Bean("fileReader") + public FileReader fileReader(){ + return new FileReader(file); + } + + @Bean("fileWriter") + public FileWriter fileWriter(){ + return new FileWriter(file); + } + + @Bean("dummyFileProcessor") + @DependsOn({"dummyfileWriter"}) + @Lazy + public FileProcessor dummyFileProcessor(){ + return new FileProcessor(file); + } + + @Bean("dummyFileProcessorCircular") + @DependsOn({"dummyFileReaderCircular"}) + @Lazy + public FileProcessor dummyFileProcessorCircular(){ + return new FileProcessor(file); + } + + @Bean("dummyFileReaderCircular") + @DependsOn({"dummyFileProcessorCircular"}) + @Lazy + public FileReader dummyFileReaderCircular(){ + return new FileReader(file); + } +} diff --git a/spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorTest.java b/spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorTest.java new file mode 100644 index 0000000000..b54ac16125 --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorTest.java @@ -0,0 +1,42 @@ +package com.baeldung.dependson.processor; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.dependson.config.TestConfig; +import com.baeldung.dependson.shared.File; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = TestConfig.class) +public class FileProcessorTest { + + @Autowired + ApplicationContext context; + + @Autowired + File file; + + @Test + public void whenAllBeansCreated_FileTextEndsWithProcessed() { + context.getBean("fileProcessor"); + assertTrue(file.getText().endsWith("processed")); + } + + @Test(expected=NoSuchBeanDefinitionException.class) + public void whenDependentBeanNotAvailable_ThrowsNoSuchBeanDefinitionException(){ + context.getBean("dummyFileProcessor"); + } + + @Test(expected=BeanCreationException.class) + public void whenCircularDependency_ThrowsBeanCreationException(){ + context.getBean("dummyFileReaderCircular"); + } +} diff --git a/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java b/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionIntegrationTest.java similarity index 92% rename from spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java rename to spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionIntegrationTest.java index 1660b99726..4bfb3c5de4 100644 --- a/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java +++ b/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionIntegrationTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -public class BeanInjectionTest { +public class BeanInjectionIntegrationTest { private ApplicationContext applicationContext; diff --git a/spring-core/src/test/java/com/baeldung/methodinjections/StudentTest.java b/spring-core/src/test/java/com/baeldung/methodinjections/StudentIntegrationTest.java similarity index 97% rename from spring-core/src/test/java/com/baeldung/methodinjections/StudentTest.java rename to spring-core/src/test/java/com/baeldung/methodinjections/StudentIntegrationTest.java index 8c04ef472e..5d326a99dd 100644 --- a/spring-core/src/test/java/com/baeldung/methodinjections/StudentTest.java +++ b/spring-core/src/test/java/com/baeldung/methodinjections/StudentIntegrationTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -public class StudentTest { +public class StudentIntegrationTest { @Test public void whenLookupMethodCalled_thenNewInstanceReturned() { diff --git a/spring-core/src/test/java/com/baeldung/scope/PrototypeBeanInjectionTest.java b/spring-core/src/test/java/com/baeldung/scope/PrototypeBeanInjectionIntegrationTest.java similarity index 98% rename from spring-core/src/test/java/com/baeldung/scope/PrototypeBeanInjectionTest.java rename to spring-core/src/test/java/com/baeldung/scope/PrototypeBeanInjectionIntegrationTest.java index 0c4c5d6069..1c05bb3e8e 100644 --- a/spring-core/src/test/java/com/baeldung/scope/PrototypeBeanInjectionTest.java +++ b/spring-core/src/test/java/com/baeldung/scope/PrototypeBeanInjectionIntegrationTest.java @@ -15,7 +15,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = AppConfig.class) -public class PrototypeBeanInjectionTest { +public class PrototypeBeanInjectionIntegrationTest { @Test public void givenPrototypeInjection_WhenObjectFactory_ThenNewInstanceReturn() { diff --git a/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamTest.java b/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamIntegrationTest.java similarity index 99% rename from spring-core/src/test/java/com/baeldung/streamutils/CopyStreamTest.java rename to spring-core/src/test/java/com/baeldung/streamutils/CopyStreamIntegrationTest.java index 9fe2f00a77..7f4a026229 100644 --- a/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamTest.java +++ b/spring-core/src/test/java/com/baeldung/streamutils/CopyStreamIntegrationTest.java @@ -16,7 +16,7 @@ import org.springframework.util.StreamUtils; import static com.baeldung.streamutils.CopyStream.getStringFromInputStream; -public class CopyStreamTest { +public class CopyStreamIntegrationTest { @Test public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException { diff --git a/spring-core/src/test/java/com/baeldung/value/ClassNotManagedBySpringTest.java b/spring-core/src/test/java/com/baeldung/value/ClassNotManagedBySpringIntegrationTest.java similarity index 95% rename from spring-core/src/test/java/com/baeldung/value/ClassNotManagedBySpringTest.java rename to spring-core/src/test/java/com/baeldung/value/ClassNotManagedBySpringIntegrationTest.java index d07d490642..689801bece 100644 --- a/spring-core/src/test/java/com/baeldung/value/ClassNotManagedBySpringTest.java +++ b/spring-core/src/test/java/com/baeldung/value/ClassNotManagedBySpringIntegrationTest.java @@ -10,7 +10,7 @@ import static junit.framework.TestCase.assertEquals; import static org.mockito.Mockito.when; @RunWith(SpringRunner.class) -public class ClassNotManagedBySpringTest { +public class ClassNotManagedBySpringIntegrationTest { @MockBean private InitializerBean initializerBean; diff --git a/spring-cucumber/pom.xml b/spring-cucumber/pom.xml index cabd1a9020..1da4c8a124 100644 --- a/spring-cucumber/pom.xml +++ b/spring-cucumber/pom.xml @@ -10,10 +10,10 @@ Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-custom-aop/pom.xml b/spring-custom-aop/pom.xml index 76d8e7c344..4e95d175e7 100644 --- a/spring-custom-aop/pom.xml +++ b/spring-custom-aop/pom.xml @@ -9,10 +9,10 @@ This is simple boot application for Spring boot actuator test - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegationTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTest.java similarity index 92% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegationTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTest.java index cb671dc469..05ba58d616 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegationTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTest.java @@ -9,6 +9,6 @@ import org.springframework.test.context.support.DependencyInjectionTestExecution @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { MultiBucketCouchbaseConfig.class, MultiBucketIntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public abstract class MultiBucketIntegationTest { +public abstract class MultiBucketIntegrationTest { } diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java index 71648cf59b..0996b252f1 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java @@ -10,7 +10,7 @@ import java.util.Set; import javax.annotation.PostConstruct; import org.baeldung.spring.data.couchbase.model.Campus; -import org.baeldung.spring.data.couchbase2b.MultiBucketIntegationTest; +import org.baeldung.spring.data.couchbase2b.MultiBucketIntegrationTest; import org.baeldung.spring.data.couchbase2b.repos.CampusRepository; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -18,7 +18,7 @@ import org.springframework.data.geo.Distance; import org.springframework.data.geo.Metrics; import org.springframework.data.geo.Point; -public class CampusServiceImplIntegrationTest extends MultiBucketIntegationTest { +public class CampusServiceImplIntegrationTest extends MultiBucketIntegrationTest { @Autowired private CampusServiceImpl campusService; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java index 819798d536..45475e50f6 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java @@ -9,7 +9,7 @@ import java.util.List; import org.baeldung.spring.data.couchbase.model.Person; import org.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig; -import org.baeldung.spring.data.couchbase2b.MultiBucketIntegationTest; +import org.baeldung.spring.data.couchbase2b.MultiBucketIntegrationTest; import org.joda.time.DateTime; import org.junit.BeforeClass; import org.junit.Test; @@ -21,7 +21,7 @@ import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; -public class PersonServiceImplIntegrationTest extends MultiBucketIntegationTest { +public class PersonServiceImplIntegrationTest extends MultiBucketIntegrationTest { static final String typeField = "_class"; static final String john = "John"; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java index f37f11744d..e7c1eab92a 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java @@ -11,7 +11,7 @@ import javax.validation.ConstraintViolationException; import org.baeldung.spring.data.couchbase.model.Student; import org.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig; -import org.baeldung.spring.data.couchbase2b.MultiBucketIntegationTest; +import org.baeldung.spring.data.couchbase2b.MultiBucketIntegrationTest; import org.joda.time.DateTime; import org.junit.BeforeClass; import org.junit.Test; @@ -23,7 +23,7 @@ import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; -public class StudentServiceImplIntegrationTest extends MultiBucketIntegationTest { +public class StudentServiceImplIntegrationTest extends MultiBucketIntegrationTest { static final String typeField = "_class"; static final String joe = "Joe"; diff --git a/spring-data-elasticsearch/pom.xml b/spring-data-elasticsearch/pom.xml index 804cf23a69..386bd54ee8 100644 --- a/spring-data-elasticsearch/pom.xml +++ b/spring-data-elasticsearch/pom.xml @@ -9,16 +9,16 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -53,7 +53,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -80,7 +80,6 @@ UTF-8 1.8 1.8 - 4.3.4.RELEASE 2.0.5.RELEASE 4.2.2 2.4.2 diff --git a/spring-data-keyvalue/README.md b/spring-data-keyvalue/README.md new file mode 100644 index 0000000000..f76cf4d5ac --- /dev/null +++ b/spring-data-keyvalue/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [A Guide to Spring Data Key Value](http://www.baeldung.com/spring-data-key-value) diff --git a/spring-data-mongodb/README.md b/spring-data-mongodb/README.md index c2a1f703b5..4e12a2218a 100644 --- a/spring-data-mongodb/README.md +++ b/spring-data-mongodb/README.md @@ -10,3 +10,4 @@ - [GridFS in Spring Data MongoDB](http://www.baeldung.com/spring-data-mongodb-gridfs) - [Introduction to Spring Data MongoDB](http://www.baeldung.com/spring-data-mongodb-tutorial) - [Spring Data MongoDB: Projections and Aggregations](http://www.baeldung.com/spring-data-mongodb-projections-aggregations) +- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations) diff --git a/spring-data-mongodb/pom.xml b/spring-data-mongodb/pom.xml index 24847aaec6..c3d1f74b4b 100644 --- a/spring-data-mongodb/pom.xml +++ b/spring-data-mongodb/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -22,7 +22,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -33,7 +33,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -71,7 +71,6 @@ UTF-8 - 4.3.4.RELEASE 1.10.4.RELEASE 2.9.0 4.1.4 diff --git a/spring-data-mongodb/src/main/java/org/baeldung/annotation/CascadeSave.java b/spring-data-mongodb/src/main/java/com/baeldung/annotation/CascadeSave.java similarity index 88% rename from spring-data-mongodb/src/main/java/org/baeldung/annotation/CascadeSave.java rename to spring-data-mongodb/src/main/java/com/baeldung/annotation/CascadeSave.java index aae0214d09..3e43221aff 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/annotation/CascadeSave.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/annotation/CascadeSave.java @@ -1,4 +1,4 @@ -package org.baeldung.annotation; +package com.baeldung.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/config/MongoConfig.java b/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java similarity index 84% rename from spring-data-mongodb/src/main/java/org/baeldung/config/MongoConfig.java rename to spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java index 80b177f4c9..551a9142a6 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/config/MongoConfig.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java @@ -1,10 +1,10 @@ -package org.baeldung.config; +package com.baeldung.config; import com.mongodb.Mongo; import com.mongodb.MongoClient; -import org.baeldung.converter.UserWriterConverter; -import org.baeldung.event.CascadeSaveMongoEventListener; -import org.baeldung.event.UserCascadeSaveMongoEventListener; +import com.baeldung.converter.UserWriterConverter; +import com.baeldung.event.CascadeSaveMongoEventListener; +import com.baeldung.event.UserCascadeSaveMongoEventListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.converter.Converter; @@ -17,7 +17,7 @@ import java.util.ArrayList; import java.util.List; @Configuration -@EnableMongoRepositories(basePackages = "org.baeldung.repository") +@EnableMongoRepositories(basePackages = "com.baeldung.repository") public class MongoConfig extends AbstractMongoConfiguration { private final List> converters = new ArrayList>(); @@ -34,7 +34,7 @@ public class MongoConfig extends AbstractMongoConfiguration { @Override public String getMappingBasePackage() { - return "org.baeldung"; + return "com.baeldung"; } @Bean diff --git a/spring-data-mongodb/src/main/java/org/baeldung/config/SimpleMongoConfig.java b/spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java similarity index 86% rename from spring-data-mongodb/src/main/java/org/baeldung/config/SimpleMongoConfig.java rename to spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java index 9653796d8d..95f192811f 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/config/SimpleMongoConfig.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import com.mongodb.Mongo; import com.mongodb.MongoClient; @@ -8,7 +8,7 @@ import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; @Configuration -@EnableMongoRepositories(basePackages = "org.baeldung.repository") +@EnableMongoRepositories(basePackages = "com.baeldung.repository") public class SimpleMongoConfig { @Bean diff --git a/spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java b/spring-data-mongodb/src/main/java/com/baeldung/converter/UserWriterConverter.java similarity index 92% rename from spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java rename to spring-data-mongodb/src/main/java/com/baeldung/converter/UserWriterConverter.java index 4a6970489e..542ebb2c85 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/converter/UserWriterConverter.java @@ -1,8 +1,8 @@ -package org.baeldung.converter; +package com.baeldung.converter; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; -import org.baeldung.model.User; +import com.baeldung.model.User; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java b/spring-data-mongodb/src/main/java/com/baeldung/event/CascadeCallback.java similarity index 95% rename from spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java rename to spring-data-mongodb/src/main/java/com/baeldung/event/CascadeCallback.java index 94cad4566a..6ce5747793 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/event/CascadeCallback.java @@ -1,8 +1,8 @@ -package org.baeldung.event; +package com.baeldung.event; import java.lang.reflect.Field; -import org.baeldung.annotation.CascadeSave; +import com.baeldung.annotation.CascadeSave; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.util.ReflectionUtils; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java b/spring-data-mongodb/src/main/java/com/baeldung/event/CascadeSaveMongoEventListener.java similarity index 96% rename from spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java rename to spring-data-mongodb/src/main/java/com/baeldung/event/CascadeSaveMongoEventListener.java index acc377011d..499e727a90 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/event/CascadeSaveMongoEventListener.java @@ -1,4 +1,4 @@ -package org.baeldung.event; +package com.baeldung.event; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/FieldCallback.java b/spring-data-mongodb/src/main/java/com/baeldung/event/FieldCallback.java similarity index 95% rename from spring-data-mongodb/src/main/java/org/baeldung/event/FieldCallback.java rename to spring-data-mongodb/src/main/java/com/baeldung/event/FieldCallback.java index c6bd90d4f3..5e478270c1 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/FieldCallback.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/event/FieldCallback.java @@ -1,4 +1,4 @@ -package org.baeldung.event; +package com.baeldung.event; import java.lang.reflect.Field; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java b/spring-data-mongodb/src/main/java/com/baeldung/event/UserCascadeSaveMongoEventListener.java similarity index 92% rename from spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java rename to spring-data-mongodb/src/main/java/com/baeldung/event/UserCascadeSaveMongoEventListener.java index ade20bcc1d..832e3563f9 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/event/UserCascadeSaveMongoEventListener.java @@ -1,6 +1,6 @@ -package org.baeldung.event; +package com.baeldung.event; -import org.baeldung.model.User; +import com.baeldung.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/model/EmailAddress.java b/spring-data-mongodb/src/main/java/com/baeldung/model/EmailAddress.java similarity index 94% rename from spring-data-mongodb/src/main/java/org/baeldung/model/EmailAddress.java rename to spring-data-mongodb/src/main/java/com/baeldung/model/EmailAddress.java index 6db7d160d7..13fe340f69 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/model/EmailAddress.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/model/EmailAddress.java @@ -1,4 +1,4 @@ -package org.baeldung.model; +package com.baeldung.model; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/model/User.java b/spring-data-mongodb/src/main/java/com/baeldung/model/User.java similarity index 96% rename from spring-data-mongodb/src/main/java/org/baeldung/model/User.java rename to spring-data-mongodb/src/main/java/com/baeldung/model/User.java index 9b8c47a58f..1bbe49ee1d 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/model/User.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/model/User.java @@ -1,6 +1,6 @@ -package org.baeldung.model; +package com.baeldung.model; -import org.baeldung.annotation.CascadeSave; +import com.baeldung.annotation.CascadeSave; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.PersistenceConstructor; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/repository/UserRepository.java b/spring-data-mongodb/src/main/java/com/baeldung/repository/UserRepository.java similarity index 94% rename from spring-data-mongodb/src/main/java/org/baeldung/repository/UserRepository.java rename to spring-data-mongodb/src/main/java/com/baeldung/repository/UserRepository.java index 8e442e8b7f..e9dc0f5c95 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/repository/UserRepository.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/repository/UserRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.repository; +package com.baeldung.repository; -import org.baeldung.model.User; +import com.baeldung.model.User; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import org.springframework.data.querydsl.QueryDslPredicateExecutor; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/aggregation/ZipsAggregationLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java similarity index 97% rename from spring-data-mongodb/src/test/java/org/baeldung/aggregation/ZipsAggregationLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java index 5686465c19..a4bea45fcf 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/aggregation/ZipsAggregationLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java @@ -1,12 +1,12 @@ -package org.baeldung.aggregation; +package com.baeldung.aggregation; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.util.JSON; -import org.baeldung.aggregation.model.StatePopulation; -import org.baeldung.config.MongoConfig; +import com.baeldung.aggregation.model.StatePopulation; +import com.baeldung.config.MongoConfig; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/aggregation/model/StatePopulation.java b/spring-data-mongodb/src/test/java/com/baeldung/aggregation/model/StatePopulation.java similarity index 95% rename from spring-data-mongodb/src/test/java/org/baeldung/aggregation/model/StatePopulation.java rename to spring-data-mongodb/src/test/java/com/baeldung/aggregation/model/StatePopulation.java index 6a3cd0d426..be77783439 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/aggregation/model/StatePopulation.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/aggregation/model/StatePopulation.java @@ -1,4 +1,4 @@ -package org.baeldung.aggregation.model; +package com.baeldung.aggregation.model; import org.springframework.data.annotation.Id; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java similarity index 99% rename from spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java index 88205ba7fd..02485e8517 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.gridfs; +package com.baeldung.gridfs; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java similarity index 97% rename from spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java index 729b0f6dfa..7a61f9f98a 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java @@ -1,8 +1,8 @@ -package org.baeldung.mongotemplate; +package com.baeldung.mongotemplate; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.EmailAddress; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.EmailAddress; +import com.baeldung.model.User; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java similarity index 94% rename from spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java index 2d2117afbb..309f14e995 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java @@ -1,7 +1,7 @@ -package org.baeldung.mongotemplate; +package com.baeldung.mongotemplate; -import org.baeldung.config.SimpleMongoConfig; -import org.baeldung.model.User; +import com.baeldung.config.SimpleMongoConfig; +import com.baeldung.model.User; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java similarity index 97% rename from spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java index b7ce0cafae..ee1d4f4760 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java @@ -1,8 +1,8 @@ -package org.baeldung.mongotemplate; +package com.baeldung.mongotemplate; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.EmailAddress; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.EmailAddress; +import com.baeldung.model.User; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/BaseQueryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/BaseQueryLiveTest.java similarity index 83% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/BaseQueryLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/repository/BaseQueryLiveTest.java index afd7259c6c..e4849181e5 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/BaseQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/BaseQueryLiveTest.java @@ -1,7 +1,7 @@ -package org.baeldung.repository; +package com.baeldung.repository; -import org.baeldung.model.User; -import org.baeldung.repository.UserRepository; +import com.baeldung.model.User; +import com.baeldung.repository.UserRepository; import org.junit.After; import org.junit.Before; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/DSLQueryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/DSLQueryLiveTest.java similarity index 95% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/DSLQueryLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/repository/DSLQueryLiveTest.java index 5924dea9fe..f87ca5cbb5 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/DSLQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/DSLQueryLiveTest.java @@ -1,13 +1,13 @@ -package org.baeldung.repository; +package com.baeldung.repository; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.List; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.QUser; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.QUser; +import com.baeldung.model.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/JSONQueryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/JSONQueryLiveTest.java similarity index 96% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/JSONQueryLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/repository/JSONQueryLiveTest.java index 9464a4eb52..4e99c0b140 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/JSONQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/JSONQueryLiveTest.java @@ -1,12 +1,12 @@ -package org.baeldung.repository; +package com.baeldung.repository; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.List; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/QueryMethodsLiveTest.java similarity index 96% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/repository/QueryMethodsLiveTest.java index 5705c119b8..47e67a6b4c 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/QueryMethodsLiveTest.java @@ -1,12 +1,12 @@ -package org.baeldung.repository; +package com.baeldung.repository; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.List; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java similarity index 97% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java index 1543b847ba..da4e91baec 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java @@ -1,12 +1,12 @@ -package org.baeldung.repository; +package com.baeldung.repository; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.List; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.User; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryProjectionLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryProjectionLiveTest.java similarity index 93% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryProjectionLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryProjectionLiveTest.java index 5436896f08..80f4275794 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryProjectionLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryProjectionLiveTest.java @@ -1,9 +1,9 @@ -package org.baeldung.repository; +package com.baeldung.repository; import static org.junit.Assert.*; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.User; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-data-rest-querydsl/pom.xml b/spring-data-rest-querydsl/pom.xml new file mode 100644 index 0000000000..e4832e1552 --- /dev/null +++ b/spring-data-rest-querydsl/pom.xml @@ -0,0 +1,101 @@ + + + 4.0.0 + + com.baeldung + spring-data-rest-querydsl + 1.0 + + spring-data-rest-querydsl + + + org.springframework.boot + spring-boot-starter-parent + 1.5.9.RELEASE + + + + + org.springframework.boot + spring-boot-starter-data-rest + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + + + com.querydsl + querydsl-apt + + + com.querydsl + querydsl-jpa + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.boot + spring-boot-maven-plugin + + ${start-class} + ZIP + + + + + repackage + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + -verbose + -parameters + + + + + com.mysema.maven + apt-maven-plugin + 1.1.3 + + + generate-sources + + process + + + ${project.build.directory}/generated-sources + com.querydsl.apt.jpa.JPAAnnotationProcessor + + + + + + +<<<<<<< HEAD + +======= + +>>>>>>> 19a1633c35d6d49f9c51b8ecc3dbe127c91d75c3 diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/Application.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..28d084a4dc --- /dev/null +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/Application.java @@ -0,0 +1,44 @@ +package com.baeldung; + +import com.baeldung.controller.repository.AddressRepository; +import com.baeldung.controller.repository.UserRepository; +import com.baeldung.entity.Address; +import com.baeldung.entity.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +@EntityScan("com.baeldung.entity") +@EnableJpaRepositories("com.baeldung.controller.repository") +@EnableAutoConfiguration +public class Application { + + @Autowired + private UserRepository personRepository; + @Autowired + private AddressRepository addressRepository; + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @PostConstruct + private void initializeData() { + // Create John + final User john = new User("John"); + personRepository.save(john); + final Address addressOne = new Address("Fake Street 1", "Spain", john); + addressRepository.save(addressOne); + // Create Lisa + final User lisa = new User("Lisa"); + personRepository.save(lisa); + final Address addressTwo = new Address("Real Street 1", "Germany", lisa); + addressRepository.save(addressTwo); + } +} diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/QueryController.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/QueryController.java new file mode 100644 index 0000000000..e29932657f --- /dev/null +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/QueryController.java @@ -0,0 +1,34 @@ +package com.baeldung.controller; + +import com.baeldung.controller.repository.AddressRepository; +import com.baeldung.controller.repository.UserRepository; +import com.baeldung.entity.Address; +import com.baeldung.entity.User; +import com.querydsl.core.BooleanBuilder; +import com.querydsl.core.types.Predicate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.querydsl.binding.QuerydslPredicate; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class QueryController { + + @Autowired + private UserRepository personRepository; + @Autowired + private AddressRepository addressRepository; + + @GetMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE) + public Iterable queryOverUser(@QuerydslPredicate(root = User.class) Predicate predicate) { + final BooleanBuilder builder = new BooleanBuilder(); + return personRepository.findAll(builder.and(predicate)); + } + + @GetMapping(value = "/addresses", produces = MediaType.APPLICATION_JSON_VALUE) + public Iterable
queryOverAddress(@QuerydslPredicate(root = Address.class) Predicate predicate) { + final BooleanBuilder builder = new BooleanBuilder(); + return addressRepository.findAll(builder.and(predicate)); + } +} diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/AddressRepository.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/AddressRepository.java new file mode 100644 index 0000000000..2e88820c98 --- /dev/null +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/AddressRepository.java @@ -0,0 +1,19 @@ +package com.baeldung.controller.repository; + +import com.baeldung.entity.Address; +import com.baeldung.entity.QAddress; +import com.querydsl.core.types.dsl.StringExpression; +import com.querydsl.core.types.dsl.StringPath; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer; +import org.springframework.data.querydsl.binding.QuerydslBindings; +import org.springframework.data.querydsl.binding.SingleValueBinding; + +public interface AddressRepository + extends JpaRepository, QueryDslPredicateExecutor
, QuerydslBinderCustomizer { + @Override + default void customize(final QuerydslBindings bindings, final QAddress root) { + bindings.bind(String.class).first((SingleValueBinding) StringExpression::eq); + } +} diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/UserRepository.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/UserRepository.java new file mode 100644 index 0000000000..98ff2ac5e3 --- /dev/null +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/UserRepository.java @@ -0,0 +1,19 @@ +package com.baeldung.controller.repository; + +import com.baeldung.entity.QUser; +import com.baeldung.entity.User; +import com.querydsl.core.types.dsl.StringExpression; +import com.querydsl.core.types.dsl.StringPath; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer; +import org.springframework.data.querydsl.binding.QuerydslBindings; +import org.springframework.data.querydsl.binding.SingleValueBinding; + +public interface UserRepository + extends JpaRepository, QueryDslPredicateExecutor, QuerydslBinderCustomizer { + @Override + default void customize(final QuerydslBindings bindings, final QUser root) { + bindings.bind(String.class).first((SingleValueBinding) StringExpression::eq); + } +} diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/Address.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/Address.java new file mode 100644 index 0000000000..b01194adb7 --- /dev/null +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/Address.java @@ -0,0 +1,57 @@ +package com.baeldung.entity; + + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import javax.persistence.*; + +@Entity +@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) +public class Address { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", unique = true, nullable = false) + private Long id; + @Column + private String address; + @Column + private String country; + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + public Address() { + } + + public Address(String address, String country, User user) { + this.id = id; + this.address = address; + this.country = country; + this.user = user; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } +} diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/User.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/User.java new file mode 100644 index 0000000000..cfd484bb7a --- /dev/null +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/User.java @@ -0,0 +1,51 @@ +package com.baeldung.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import javax.persistence.*; + + +@Entity +@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", unique = true, nullable = false) + private Long id; + @Column + private String name; + @OneToOne(fetch = FetchType.LAZY, mappedBy = "user") + private Address address; + + public User() { + } + + public User(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } +} diff --git a/spring-data-rest-querydsl/src/main/resources/application.yml b/spring-data-rest-querydsl/src/main/resources/application.yml new file mode 100644 index 0000000000..f25c6ea0e3 --- /dev/null +++ b/spring-data-rest-querydsl/src/main/resources/application.yml @@ -0,0 +1,11 @@ +spring: + datasource: + driver-class-name: com.mysql.jdbc.Driver + hikari: + pool-name: hikari-pool + url: jdbc:mysql://localhost:3306/baeldung?verifyServerCertificate=false&useSSL=false&requireSSL=false + username: root + + jpa: + hibernate: + ddl-auto: create diff --git a/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java new file mode 100644 index 0000000000..ef86c2f36d --- /dev/null +++ b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.springdatarestquerydsl; + +import com.baeldung.Application; +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.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import java.nio.charset.Charset; + +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class) @WebAppConfiguration +public class IntegrationTest { + + final MediaType contentType = + new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); + + @Autowired private WebApplicationContext webApplicationContext; + + private MockMvc mockMvc; + + @Before public void setupMockMvc() { + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); + } + + @Test public void givenRequestHasBeenMade_whenQueryOverNameAttribute_thenGetJohn() throws Exception { + // Get John + mockMvc.perform(get("/personQuery?name=John")).andExpect(status().isOk()).andExpect(content().contentType(contentType)) + .andExpect(jsonPath("$", hasSize(1))).andExpect(jsonPath("$[0].name", is("John"))) + .andExpect(jsonPath("$[0].address.address", is("Fake Street 1"))) + .andExpect(jsonPath("$[0].address.country", is("Fake Country"))); + } + + @Test public void givenRequestHasBeenMade_whenQueryOverNameAttribute_thenGetLisa() throws Exception { + // Get Lisa + mockMvc.perform(get("/personQuery?name=Lisa")).andExpect(status().isOk()).andExpect(content().contentType(contentType)) + .andExpect(jsonPath("$", hasSize(1))).andExpect(jsonPath("$[0].name", is("Lisa"))) + .andExpect(jsonPath("$[0].address.address", is("Real Street 1"))) + .andExpect(jsonPath("$[0].address.country", is("Real Country"))); + } +} diff --git a/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/QuerydslIntegrationTest.java b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/QuerydslIntegrationTest.java new file mode 100644 index 0000000000..11e5ffca05 --- /dev/null +++ b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/QuerydslIntegrationTest.java @@ -0,0 +1,65 @@ +package com.baeldung.springdatarestquerydsl; + +import com.baeldung.Application; +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.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import java.nio.charset.Charset; + +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = Application.class) +@WebAppConfiguration +public class QuerydslIntegrationTest { + + final MediaType contentType = + new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); + + @Autowired + private WebApplicationContext webApplicationContext; + + private MockMvc mockMvc; + + @Before + public void setupMockMvc() { + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); + } + + @Test + public void givenRequest_whenQueryUserFilteringByCountrySpain_thenGetJohn() throws Exception { + mockMvc.perform(get("/users?address.country=Spain")).andExpect(status().isOk()).andExpect(content() + .contentType + (contentType)) + .andExpect(jsonPath("$", hasSize(1))) + .andExpect(jsonPath("$[0].name", is("John"))) + .andExpect(jsonPath("$[0].address.address", is("Fake Street 1"))) + .andExpect(jsonPath("$[0].address.country", is("Spain"))); + } + + @Test + public void givenRequest_whenQueryUserWithoutFilter_thenGetJohnAndLisa() throws Exception { + mockMvc.perform(get("/users")).andExpect(status().isOk()).andExpect(content() + .contentType + (contentType)) + .andExpect(jsonPath("$", hasSize(2))) + .andExpect(jsonPath("$[0].name", is("John"))) + .andExpect(jsonPath("$[0].address.address", is("Fake Street 1"))) + .andExpect(jsonPath("$[0].address.country", is("Spain"))) + .andExpect(jsonPath("$[1].name", is("Lisa"))) + .andExpect(jsonPath("$[1].address.address", is("Real Street 1"))) + .andExpect(jsonPath("$[1].address.country", is("Germany"))); + } +} diff --git a/spring-data-rest/README.md b/spring-data-rest/README.md index 445557d10b..09f8391406 100644 --- a/spring-data-rest/README.md +++ b/spring-data-rest/README.md @@ -19,3 +19,4 @@ To view the running application, visit [http://localhost:8080](http://localhost: - [AngularJS CRUD Application with Spring Data REST](http://www.baeldung.com/angularjs-crud-with-spring-data-rest) - [List of In-Memory Databases](http://www.baeldung.com/java-in-memory-databases) - [Projections and Excerpts in Spring Data REST](http://www.baeldung.com/spring-data-rest-projections-excerpts) +- [Spring Data REST Events with @RepositoryEventHandler](http://www.baeldung.com/spring-data-rest-events) diff --git a/spring-data-rest/pom.xml b/spring-data-rest/pom.xml index bad7a38281..0e525474e3 100644 --- a/spring-data-rest/pom.xml +++ b/spring-data-rest/pom.xml @@ -10,10 +10,10 @@ Intro to Spring Data REST - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerTest.java b/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerUnitTest.java similarity index 95% rename from spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerTest.java rename to spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerUnitTest.java index 9fb2d1014e..6db536c40c 100644 --- a/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerUnitTest.java @@ -7,7 +7,7 @@ import org.springframework.data.rest.core.annotation.RepositoryEventHandler; import static org.mockito.Mockito.mock; -public class AuthorEventHandlerTest { +public class AuthorEventHandlerUnitTest { @Test public void whenCreateAuthorThenSuccess() { diff --git a/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerTest.java b/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerUnitTest.java similarity index 95% rename from spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerTest.java rename to spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerUnitTest.java index 85699adb0d..28f0b91e1c 100644 --- a/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerTest.java +++ b/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerUnitTest.java @@ -7,7 +7,7 @@ import org.mockito.Mockito; import static org.mockito.Mockito.mock; -public class BookEventHandlerTest { +public class BookEventHandlerUnitTest { @Test public void whenCreateBookThenSuccess() { Book book = mock(Book.class); diff --git a/spring-data-spring-security/pom.xml b/spring-data-spring-security/pom.xml index afdf3c332c..467c38284d 100644 --- a/spring-data-spring-security/pom.xml +++ b/spring-data-spring-security/pom.xml @@ -11,10 +11,10 @@ Spring Data with Spring Security - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-dispatcher-servlet/pom.xml b/spring-dispatcher-servlet/pom.xml index 9fa02f157d..9dfd3c0f39 100644 --- a/spring-dispatcher-servlet/pom.xml +++ b/spring-dispatcher-servlet/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -90,7 +90,6 @@ - 4.3.7.RELEASE 3.0-r1655215 3.0.0 diff --git a/spring-ejb/README.md b/spring-ejb/README.md index 8fa8833f3a..d09b27db27 100644 --- a/spring-ejb/README.md +++ b/spring-ejb/README.md @@ -1,3 +1,4 @@ ### Relevant Articles - [Integration Guide for Spring and EJB](http://www.baeldung.com/spring-ejb) +- [Singleton Session Bean in Java EE](http://www.baeldung.com/java-ee-singleton-session-bean) diff --git a/spring-ejb/ejb-beans/src/test/java/com/baeldung/singletonbean/CountryStateCacheBeanTest.java b/spring-ejb/ejb-beans/src/test/java/com/baeldung/singletonbean/CountryStateCacheBeanUnitTest.java similarity index 98% rename from spring-ejb/ejb-beans/src/test/java/com/baeldung/singletonbean/CountryStateCacheBeanTest.java rename to spring-ejb/ejb-beans/src/test/java/com/baeldung/singletonbean/CountryStateCacheBeanUnitTest.java index 2207431702..4cec01a4f7 100644 --- a/spring-ejb/ejb-beans/src/test/java/com/baeldung/singletonbean/CountryStateCacheBeanTest.java +++ b/spring-ejb/ejb-beans/src/test/java/com/baeldung/singletonbean/CountryStateCacheBeanUnitTest.java @@ -14,7 +14,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -public class CountryStateCacheBeanTest { +public class CountryStateCacheBeanUnitTest { private EJBContainer ejbContainer = null; diff --git a/spring-ejb/spring-ejb-client/pom.xml b/spring-ejb/spring-ejb-client/pom.xml index f7b42212be..941105a220 100644 --- a/spring-ejb/spring-ejb-client/pom.xml +++ b/spring-ejb/spring-ejb-client/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-5 + parent-boot-1 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-groovy/pom.xml b/spring-groovy/pom.xml index eec78d21a6..c9e28deee6 100644 --- a/spring-groovy/pom.xml +++ b/spring-groovy/pom.xml @@ -12,9 +12,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 diff --git a/spring-jenkins-pipeline/pom.xml b/spring-jenkins-pipeline/pom.xml index c43952e277..6d26d18f96 100644 --- a/spring-jenkins-pipeline/pom.xml +++ b/spring-jenkins-pipeline/pom.xml @@ -9,10 +9,10 @@ Intro to Jenkins 2 and the power of pipelines - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index 3891be1ec3..db0d7e6df9 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -8,10 +8,10 @@ Intro to Kafka with Spring - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index 27075de747..6addb614f5 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -7,10 +7,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -33,7 +33,7 @@ io.katharsis - katharsis-servlet + katharsis-spring ${katharsis.version} diff --git a/spring-katharsis/src/main/java/org/baeldung/Application.java b/spring-katharsis/src/main/java/org/baeldung/Application.java index ee072305d8..5ce4ac7e08 100644 --- a/spring-katharsis/src/main/java/org/baeldung/Application.java +++ b/spring-katharsis/src/main/java/org/baeldung/Application.java @@ -1,10 +1,14 @@ package org.baeldung; +import io.katharsis.spring.boot.v3.KatharsisConfigV3; + import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.context.annotation.Import; @SpringBootApplication +@Import(KatharsisConfigV3.class) public class Application extends SpringBootServletInitializer { public static void main(String[] args) { diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/JsonApiFilter.java b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/JsonApiFilter.java deleted file mode 100644 index 3d0d441357..0000000000 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/JsonApiFilter.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.baeldung.persistence.katharsis; - -import io.katharsis.invoker.internal.legacy.KatharsisInvokerBuilder; -import io.katharsis.legacy.locator.JsonServiceLocator; -import io.katharsis.servlet.legacy.AbstractKatharsisFilter; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.stereotype.Component; - -@Component -public class JsonApiFilter extends AbstractKatharsisFilter implements BeanFactoryAware { - - private static final String DEFAULT_RESOURCE_SEARCH_PACKAGE = "org.baeldung.persistence"; - - private static final String RESOURCE_DEFAULT_DOMAIN = "http://localhost:8080"; - - private BeanFactory beanFactory; - - @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.beanFactory = beanFactory; - } - - @Override - protected KatharsisInvokerBuilder createKatharsisInvokerBuilder() { - final KatharsisInvokerBuilder builder = new KatharsisInvokerBuilder(); - - builder.resourceSearchPackage(DEFAULT_RESOURCE_SEARCH_PACKAGE).resourceDefaultDomain(RESOURCE_DEFAULT_DOMAIN).jsonServiceLocator(new JsonServiceLocator() { - @Override - public T getInstance(Class clazz) { - return beanFactory.getBean(clazz); - } - }); - - return builder; - } - -} diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java index 52ca40e26e..1998c414bb 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java @@ -1,7 +1,9 @@ package org.baeldung.persistence.katharsis; -import io.katharsis.legacy.queryParams.QueryParams; -import io.katharsis.legacy.repository.ResourceRepository; + +import io.katharsis.queryspec.QuerySpec; +import io.katharsis.repository.ResourceRepositoryV2; +import io.katharsis.resource.list.ResourceList; import org.baeldung.persistence.dao.RoleRepository; import org.baeldung.persistence.model.Role; @@ -9,23 +11,23 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component -public class RoleResourceRepository implements ResourceRepository { +public class RoleResourceRepository implements ResourceRepositoryV2 { @Autowired private RoleRepository roleRepository; @Override - public Role findOne(Long id, QueryParams params) { + public Role findOne(Long id, QuerySpec querySpec) { return roleRepository.findOne(id); } @Override - public Iterable findAll(QueryParams params) { - return roleRepository.findAll(); + public ResourceList findAll(QuerySpec querySpec) { + return querySpec.apply(roleRepository.findAll()); } @Override - public Iterable findAll(Iterable ids, QueryParams params) { - return roleRepository.findAll(ids); + public ResourceList findAll(Iterable ids, QuerySpec querySpec) { + return querySpec.apply(roleRepository.findAll(ids)); } @Override @@ -38,4 +40,14 @@ public class RoleResourceRepository implements ResourceRepository { roleRepository.delete(id); } + @Override + public Class getResourceClass() { + return Role.class; + } + + @Override + public S create(S entity) { + return save(entity); + } + } diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java index a36c3c3c0a..9b3de31601 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java @@ -1,7 +1,8 @@ package org.baeldung.persistence.katharsis; -import io.katharsis.legacy.queryParams.QueryParams; -import io.katharsis.legacy.repository.ResourceRepository; +import io.katharsis.queryspec.QuerySpec; +import io.katharsis.repository.ResourceRepositoryV2; +import io.katharsis.resource.list.ResourceList; import org.baeldung.persistence.dao.UserRepository; import org.baeldung.persistence.model.User; @@ -9,24 +10,24 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component -public class UserResourceRepository implements ResourceRepository { +public class UserResourceRepository implements ResourceRepositoryV2 { @Autowired private UserRepository userRepository; @Override - public User findOne(Long id, QueryParams params) { + public User findOne(Long id, QuerySpec querySpec) { return userRepository.findOne(id); } @Override - public Iterable findAll(QueryParams params) { - return userRepository.findAll(); + public ResourceList findAll(QuerySpec querySpec) { + return querySpec.apply(userRepository.findAll()); } @Override - public Iterable findAll(Iterable ids, QueryParams params) { - return userRepository.findAll(ids); + public ResourceList findAll(Iterable ids, QuerySpec querySpec) { + return querySpec.apply(userRepository.findAll(ids)); } @Override @@ -39,4 +40,14 @@ public class UserResourceRepository implements ResourceRepository { userRepository.delete(id); } + @Override + public Class getResourceClass() { + return User.class; + } + + @Override + public S create(S entity) { + return save(entity); + } + } diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java index 19007a285f..dbeb769fac 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java @@ -1,7 +1,8 @@ package org.baeldung.persistence.katharsis; -import io.katharsis.legacy.queryParams.QueryParams; -import io.katharsis.legacy.repository.RelationshipRepository; +import io.katharsis.queryspec.QuerySpec; +import io.katharsis.repository.RelationshipRepositoryV2; +import io.katharsis.resource.list.ResourceList; import java.util.HashSet; import java.util.Set; @@ -14,7 +15,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component -public class UserToRoleRelationshipRepository implements RelationshipRepository { +public class UserToRoleRelationshipRepository implements RelationshipRepositoryV2 { @Autowired private UserRepository userRepository; @@ -52,14 +53,25 @@ public class UserToRoleRelationshipRepository implements RelationshipRepository< } @Override - public Role findOneTarget(Long sourceId, String fieldName, QueryParams QueryParams) { + public Role findOneTarget(Long sourceId, String fieldName, QuerySpec querySpec) { // not for many-to-many return null; } @Override - public Iterable findManyTargets(Long sourceId, String fieldName, QueryParams QueryParams) { + public ResourceList findManyTargets(Long sourceId, String fieldName, QuerySpec querySpec) { final User user = userRepository.findOne(sourceId); - return user.getRoles(); + return querySpec.apply(user.getRoles()); } + + @Override + public Class getSourceResourceClass() { + return User.class; + } + + @Override + public Class getTargetResourceClass() { + return Role.class; + } + } diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/model/Role.java b/spring-katharsis/src/main/java/org/baeldung/persistence/model/Role.java index fcaf40ac2c..f391efd37c 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/model/Role.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/model/Role.java @@ -1,8 +1,8 @@ package org.baeldung.persistence.model; import io.katharsis.resource.annotations.JsonApiId; +import io.katharsis.resource.annotations.JsonApiRelation; import io.katharsis.resource.annotations.JsonApiResource; -import io.katharsis.resource.annotations.JsonApiToMany; import java.util.Set; @@ -25,7 +25,7 @@ public class Role { private String name; @ManyToMany(mappedBy = "roles") - @JsonApiToMany + @JsonApiRelation private Set users; // @@ -66,23 +66,30 @@ public class Role { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } final Role other = (Role) obj; if (id == null) { - if (other.id != null) + if (other.id != null) { return false; - } else if (!id.equals(other.id)) + } + } else if (!id.equals(other.id)) { return false; + } if (name == null) { - if (other.name != null) + if (other.name != null) { return false; - } else if (!name.equals(other.name)) + } + } else if (!name.equals(other.name)) { return false; + } return true; } diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java b/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java index 58a92002c8..7c55e29599 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java @@ -1,9 +1,9 @@ package org.baeldung.persistence.model; import io.katharsis.resource.annotations.JsonApiId; -import io.katharsis.resource.annotations.JsonApiIncludeByDefault; +import io.katharsis.resource.annotations.JsonApiRelation; import io.katharsis.resource.annotations.JsonApiResource; -import io.katharsis.resource.annotations.JsonApiToMany; +import io.katharsis.resource.annotations.SerializeType; import java.util.Set; @@ -31,8 +31,7 @@ public class User { @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) - @JsonApiToMany - @JsonApiIncludeByDefault + @JsonApiRelation(serialize=SerializeType.EAGER) private Set roles; public User() { @@ -87,15 +86,19 @@ public class User { @Override public boolean equals(final Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } final User user = (User) obj; - if (!email.equals(user.email)) + if (!email.equals(user.email)) { return false; + } return true; } diff --git a/spring-katharsis/src/main/resources/application.properties b/spring-katharsis/src/main/resources/application.properties index b55fdbba03..120b3c62ee 100644 --- a/spring-katharsis/src/main/resources/application.properties +++ b/spring-katharsis/src/main/resources/application.properties @@ -6,4 +6,7 @@ spring.jpa.hibernate.ddl-auto = create-drop spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect server.port=8082 -server.context-path=/spring-katharsis \ No newline at end of file +server.context-path=/spring-katharsis + +katharsis.domainName=http://localhost:8082/spring-katharsis +katharsis.pathPrefix=/ \ No newline at end of file diff --git a/spring-mobile/pom.xml b/spring-mobile/pom.xml index 6916bb9320..3d47bb106b 100644 --- a/spring-mobile/pom.xml +++ b/spring-mobile/pom.xml @@ -11,10 +11,10 @@ http://maven.apache.org - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-mockito/pom.xml b/spring-mockito/pom.xml index 63a5521c98..e27e25b4c8 100644 --- a/spring-mockito/pom.xml +++ b/spring-mockito/pom.xml @@ -12,16 +12,16 @@ Injecting Mockito Mocks into Spring Beans - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 org.springframework.boot - spring-boot-starter + spring-boot-starter-web org.mockito diff --git a/spring-mockito/src/main/java/com/baeldung/app/api/Flower.java b/spring-mockito/src/main/java/com/baeldung/app/api/Flower.java new file mode 100644 index 0000000000..dc1c36e3ff --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/app/api/Flower.java @@ -0,0 +1,28 @@ +package com.baeldung.app.api; + +public class Flower { + + private String name; + private Integer petals; + + public Flower(String name, Integer petals) { + this.name = name; + this.petals = petals; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getPetals() { + return petals; + } + + public void setPetals(Integer petals) { + this.petals = petals; + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/app/api/MessageApi.java b/spring-mockito/src/main/java/com/baeldung/app/api/MessageApi.java new file mode 100644 index 0000000000..edbe5a1d5a --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/app/api/MessageApi.java @@ -0,0 +1,31 @@ +package com.baeldung.app.api; + +public class MessageApi { + private String from; + private String to; + private String text; + + public String getFrom() { + return from; + } + + public void setFrom(String from) { + this.from = from; + } + + public String getTo() { + return to; + } + + public void setTo(String to) { + this.to = to; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/app/rest/FlowerController.java b/spring-mockito/src/main/java/com/baeldung/app/rest/FlowerController.java new file mode 100644 index 0000000000..b3d8888cec --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/app/rest/FlowerController.java @@ -0,0 +1,27 @@ +package com.baeldung.app.rest; + +import com.baeldung.app.api.Flower; +import com.baeldung.domain.service.FlowerService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping("/flowers") +public class FlowerController { + + @Autowired + private FlowerService flowerService; + + @PostMapping("/isAFlower") + public String isAFlower (@RequestBody String flower) { + return flowerService.analize(flower); + } + + @PostMapping("/isABigFlower") + public Boolean isABigFlower (@RequestBody Flower flower) { + return flowerService.isABigFlower(flower.getName(), flower.getPetals()); + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/app/rest/MessageController.java b/spring-mockito/src/main/java/com/baeldung/app/rest/MessageController.java new file mode 100644 index 0000000000..e23c2e7607 --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/app/rest/MessageController.java @@ -0,0 +1,34 @@ +package com.baeldung.app.rest; + +import com.baeldung.app.api.MessageApi; +import com.baeldung.domain.model.Message; +import com.baeldung.domain.service.MessageService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; + +import java.time.Instant; +import java.util.Date; +import java.util.UUID; + +@Controller +@RequestMapping("/message") +public class MessageController { + + @Autowired + private MessageService messageService; + + @PostMapping + public Message createMessage (@RequestBody MessageApi messageDTO) { + Message message = new Message(); + message.setText(messageDTO.getText()); + message.setFrom(messageDTO.getFrom()); + message.setTo(messageDTO.getTo()); + message.setDate(Date.from(Instant.now())); + message.setId(UUID.randomUUID()); + + return messageService.deliverMessage(message); + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/domain/model/Message.java b/spring-mockito/src/main/java/com/baeldung/domain/model/Message.java new file mode 100644 index 0000000000..a516d5619b --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/domain/model/Message.java @@ -0,0 +1,53 @@ +package com.baeldung.domain.model; + +import java.util.Date; +import java.util.UUID; + +public class Message { + + private String from; + private String to; + private String text; + private Date date; + private UUID id; + + public String getFrom() { + return from; + } + + public void setFrom(String from) { + this.from = from; + } + + public String getTo() { + return to; + } + + public void setTo(String to) { + this.to = to; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/domain/service/FlowerService.java b/spring-mockito/src/main/java/com/baeldung/domain/service/FlowerService.java new file mode 100644 index 0000000000..3c76cb5d76 --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/domain/service/FlowerService.java @@ -0,0 +1,28 @@ +package com.baeldung.domain.service; + +import org.springframework.stereotype.Service; + +import java.util.Arrays; +import java.util.List; + +@Service +public class FlowerService { + + private List flowers = Arrays.asList("Poppy", "Ageratum", "Carnation", "Diascia", "Lantana"); + + public String analize(String name) { + if(flowers.contains(name)) { + return "flower"; + } + return null; + } + + public boolean isABigFlower(String name, int petals) { + if(flowers.contains(name)) { + if(petals > 10) { + return true; + } + } + return false; + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/domain/service/MessageService.java b/spring-mockito/src/main/java/com/baeldung/domain/service/MessageService.java new file mode 100644 index 0000000000..d156c59571 --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/domain/service/MessageService.java @@ -0,0 +1,13 @@ +package com.baeldung.domain.service; + +import com.baeldung.domain.model.Message; +import org.springframework.stereotype.Service; + +@Service +public class MessageService { + + public Message deliverMessage (Message message) { + + return message; + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/domain/util/MessageMatcher.java b/spring-mockito/src/main/java/com/baeldung/domain/util/MessageMatcher.java new file mode 100644 index 0000000000..05cb43e4df --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/domain/util/MessageMatcher.java @@ -0,0 +1,27 @@ +package com.baeldung.domain.util; + +import com.baeldung.domain.model.Message; +import org.mockito.ArgumentMatcher; + +public class MessageMatcher extends ArgumentMatcher { + + private Message left; + + public MessageMatcher(Message message) { + this.left = message; + } + + @Override + public boolean matches(Object object) { + if (object instanceof Message) { + Message right = (Message) object; + return left.getFrom().equals(right.getFrom()) && + left.getTo().equals(right.getTo()) && + left.getText().equals(right.getText()) && + right.getDate() != null && + right.getId() != null; + } + + return false; + } +} \ No newline at end of file diff --git a/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java b/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationUnitTest.java similarity index 95% rename from spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java rename to spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationUnitTest.java index d70f916b12..573a37a9a4 100644 --- a/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java +++ b/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationUnitTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ActiveProfiles("test") @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = MocksApplication.class) -public class UserServiceIntegrationTest { +public class UserServiceIntegrationUnitTest { @Autowired private UserService userService; diff --git a/spring-mockito/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java b/spring-mockito/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java new file mode 100644 index 0000000000..f30af140af --- /dev/null +++ b/spring-mockito/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.app.rest; + +import com.baeldung.app.api.Flower; +import com.baeldung.domain.service.FlowerService; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.mockito.Matchers.anyInt; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class FlowerControllerUnitTest { + + @Mock + private FlowerService flowerService; + + @InjectMocks + private FlowerController flowerController; + + @Test + public void isAFlower_withMockito_OK() { + when(flowerService.analize(eq("violetta"))).thenReturn("Flower"); + + String response = flowerController.isAFlower("violetta"); + + Assert.assertEquals("Flower", response); + } + + @Test + public void isABigFlower_withMockito_OK() { + when(flowerService.isABigFlower(eq("violetta"), anyInt())).thenReturn(true); + + Flower flower = new Flower("violetta", 15); + + Boolean response = flowerController.isABigFlower(flower); + + Assert.assertTrue(response); + } +} diff --git a/spring-mockito/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java b/spring-mockito/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java new file mode 100644 index 0000000000..e303c85caf --- /dev/null +++ b/spring-mockito/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.app.rest; + +import com.baeldung.app.api.MessageApi; +import com.baeldung.domain.model.Message; +import com.baeldung.domain.service.MessageService; +import com.baeldung.domain.util.MessageMatcher; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.mockito.Mockito.times; + +@RunWith(MockitoJUnitRunner.class) +public class MessageControllerUnitTest { + + @Mock + private MessageService messageService; + + @InjectMocks + private MessageController messageController; + + @Test + public void createMessage_NewMessage_OK() { + MessageApi messageApi = new MessageApi(); + messageApi.setFrom("me"); + messageApi.setTo("you"); + messageApi.setText("Hello, you!"); + + messageController.createMessage(messageApi); + + Message message = new Message(); + message.setFrom("me"); + message.setTo("you"); + message.setText("Hello, you!"); + + Mockito.verify(messageService, times(1)).deliverMessage(Matchers.argThat(new MessageMatcher(message))); + } +} diff --git a/spring-mvc-email/pom.xml b/spring-mvc-email/pom.xml index 436b4155fa..40d83046ef 100644 --- a/spring-mvc-email/pom.xml +++ b/spring-mvc-email/pom.xml @@ -10,10 +10,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-mvc-forms-thymeleaf/pom.xml b/spring-mvc-forms-thymeleaf/pom.xml index 408e7643d2..59130a0133 100644 --- a/spring-mvc-forms-thymeleaf/pom.xml +++ b/spring-mvc-forms-thymeleaf/pom.xml @@ -69,6 +69,7 @@ UTF-8 UTF-8 3.0.9.RELEASE + com.baeldung.sessionattrs.SessionAttrsApplication diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Book.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Book.java new file mode 100644 index 0000000000..823ff436fb --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Book.java @@ -0,0 +1,73 @@ +package com.baeldung.listbindingexample; + +public class Book { + + private long id; + + private String title; + + private String author; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((author == null) ? 0 : author.hashCode()); + result = prime * result + (int) (id ^ (id >>> 32)); + result = prime * result + ((title == null) ? 0 : title.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Book other = (Book) obj; + if (author == null) { + if (other.author != null) + return false; + } else if (!author.equals(other.author)) + return false; + if (id != other.id) + return false; + if (title == null) { + if (other.title != null) + return false; + } else if (!title.equals(other.title)) + return false; + return true; + } + + @Override + public String toString() { + return "Book [id=" + id + ", title=" + title + ", author=" + author + "]"; + } +} diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BookService.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BookService.java new file mode 100644 index 0000000000..770e86ad68 --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BookService.java @@ -0,0 +1,10 @@ +package com.baeldung.listbindingexample; + +import java.util.List; + +public interface BookService { + + List findAll(); + + void saveAll(List books); +} diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BooksCreationDto.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BooksCreationDto.java new file mode 100644 index 0000000000..8e5654143a --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BooksCreationDto.java @@ -0,0 +1,29 @@ +package com.baeldung.listbindingexample; + +import java.util.ArrayList; +import java.util.List; + +public class BooksCreationDto { + + private List books; + + public BooksCreationDto() { + this.books = new ArrayList<>(); + } + + public BooksCreationDto(List books) { + this.books = books; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } + + public void addBook(Book book) { + this.books.add(book); + } +} diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Config.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Config.java new file mode 100644 index 0000000000..ffba2cea2c --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Config.java @@ -0,0 +1,33 @@ +package com.baeldung.listbindingexample; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; +import org.thymeleaf.templateresolver.ITemplateResolver; + +@EnableWebMvc +@Configuration +public class Config implements WebMvcConfigurer { + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("index"); + registry.setOrder(Ordered.HIGHEST_PRECEDENCE); + } + + @Bean + public ITemplateResolver templateResolver() { + ClassLoaderTemplateResolver resolver + = new ClassLoaderTemplateResolver(); + resolver.setPrefix("templates/books/"); + resolver.setSuffix(".html"); + resolver.setTemplateMode(TemplateMode.HTML); + resolver.setCharacterEncoding("UTF-8"); + return resolver; + } +} diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/InMemoryBookService.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/InMemoryBookService.java new file mode 100644 index 0000000000..56ca41c51f --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/InMemoryBookService.java @@ -0,0 +1,44 @@ +package com.baeldung.listbindingexample; + +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +@Service +public class InMemoryBookService implements BookService { + + static Map booksDB = new HashMap<>(); + + @Override + public List findAll() { + return new ArrayList(booksDB.values()); + } + + @Override + public void saveAll(List books) { + long nextId = getNextId(); + for (Book book : books) { + if (book.getId() == 0) { + book.setId(nextId++); + } + } + + Map bookMap = books.stream() + .collect(Collectors.toMap( + Book::getId, Function.identity())); + + booksDB.putAll(bookMap); + } + + private Long getNextId(){ + return booksDB.keySet().stream() + .mapToLong(value -> value) + .max() + .orElse(0) + 1; + } +} diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/ListBindingApplication.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/ListBindingApplication.java new file mode 100644 index 0000000000..af8608704b --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/ListBindingApplication.java @@ -0,0 +1,16 @@ +package com.baeldung.listbindingexample; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; + +@SpringBootApplication( + exclude = {SecurityAutoConfiguration.class, + DataSourceAutoConfiguration.class}) +public class ListBindingApplication { + + public static void main(String[] args) { + SpringApplication.run(ListBindingApplication.class, args); + } +} diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/MultipleBooksController.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/MultipleBooksController.java new file mode 100644 index 0000000000..2e177c7bbf --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/MultipleBooksController.java @@ -0,0 +1,59 @@ +package com.baeldung.listbindingexample; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +import java.util.ArrayList; +import java.util.List; + +@Controller +@RequestMapping("/books") +public class MultipleBooksController { + + @Autowired + private BookService bookService; + + @GetMapping(value = "/all") + public String showAll(Model model) { + model.addAttribute("books", bookService.findAll()); + + return "allBooks"; + } + + @GetMapping(value = "/create") + public String showCreateForm(Model model) { + BooksCreationDto booksForm = new BooksCreationDto(); + + for (int i = 1; i <= 3; i++) { + booksForm.addBook(new Book()); + } + + model.addAttribute("form", booksForm); + + return "createBooksForm"; + } + + @GetMapping(value = "/edit") + public String showEditForm(Model model) { + List books = new ArrayList<>(); + bookService.findAll().iterator().forEachRemaining(books::add); + + model.addAttribute("form", new BooksCreationDto(books)); + + return "editBooksForm"; + } + + @PostMapping(value = "/save") + public String saveBooks(@ModelAttribute BooksCreationDto form, Model model) { + bookService.saveAll(form.getBooks()); + + model.addAttribute("books", bookService.findAll()); + + return "redirect:/books/all"; + } +} diff --git a/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/allBooks.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/allBooks.html new file mode 100644 index 0000000000..9f75bec8bd --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/allBooks.html @@ -0,0 +1,40 @@ + + + All Books + + + +
+
+
+

Books

+
+
+
+
+ + + + + + + + + + + + + + + + +
Title Author
No Books Available
Title Author
+
+ +
+
+ + diff --git a/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/createBooksForm.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/createBooksForm.html new file mode 100644 index 0000000000..9f88762882 --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/createBooksForm.html @@ -0,0 +1,45 @@ + + + Add Books + + + +
+
+
+

Add Books

+
+
+
+
+ Back to All Books +
+
+ + + + + + + + + + + + + + + + + +
Title Author
+
+
+
+
+
+ + diff --git a/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/editBooksForm.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/editBooksForm.html new file mode 100644 index 0000000000..9278d98018 --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/editBooksForm.html @@ -0,0 +1,49 @@ + + + Edit Books + + + +
+
+
+

Add Books

+
+
+
+
+ Back to All Books +
+
+ + + + + + + + + + + + + + + + + + + +
Title Author
+
+
+
+
+
+ + diff --git a/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/index.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/index.html new file mode 100644 index 0000000000..59780b84aa --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/index.html @@ -0,0 +1,22 @@ + + + + Binding a List in Thymeleaf + + + + + + + +
+

+

Binding a List in Thymeleaf - Example

+

+
+ + + diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 1fd416d19f..877439145d 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -28,3 +28,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [The Spring @Controller and @RestController Annotations](http://www.baeldung.com/spring-controller-vs-restcontroller) - [Spring MVC @PathVariable with a dot (.) gets truncated](http://www.baeldung.com/spring-mvc-pathvariable-dot) - [A Quick Example of Spring Websockets’ @SendToUser Annotation](http://www.baeldung.com/spring-websockets-sendtouser) +- [Spring Boot Annotations](http://www.baeldung.com/spring-boot-annotations) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index f8d1d32f63..bc81a89bec 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -7,10 +7,10 @@ spring-mvc-java - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java similarity index 95% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerTest.java rename to spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java index 23b8c639d3..23be3a1655 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.baeldung.web.controller.SimpleBookController; -public class SimpleBookRestControllerTest { +public class SimpleBookControllerIntegrationTest { private MockMvc mockMvc; private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java similarity index 95% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerTest.java rename to spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java index 4be0ded963..c5bd53f1a7 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.baeldung.web.controller.SimpleBookController; -public class SimpleBookControllerTest { +public class SimpleBookRestControllerIntegrationTest { private MockMvc mockMvc; private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index 07d7221048..1464958865 100644 --- a/spring-mvc-simple/pom.xml +++ b/spring-mvc-simple/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-spring + parent-spring-5 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-5 @@ -48,7 +48,7 @@ org.springframework spring-webmvc - ${springframework.version} + ${spring.version} @@ -72,7 +72,7 @@ org.springframework spring-context-support - ${springframework.version} + ${spring.version} @@ -93,7 +93,7 @@ org.springframework spring-test - ${springframework.version} + ${spring.version} test @@ -159,7 +159,6 @@ 1.8 1.8 UTF-8 - 5.0.2.RELEASE 3.2.0 3.7.0 2.21.0 diff --git a/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/HelloServletTest.java b/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/HelloServletIntegrationTest.java similarity index 95% rename from spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/HelloServletTest.java rename to spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/HelloServletIntegrationTest.java index e8dd8f1b73..46cc280875 100644 --- a/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/HelloServletTest.java +++ b/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/HelloServletIntegrationTest.java @@ -8,7 +8,7 @@ import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; -public class HelloServletTest { +public class HelloServletIntegrationTest { @Test public void whenRequested_thenForwardToCorrectUrl() throws ServletException, IOException { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hello"); diff --git a/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/WelcomeServletTest.java b/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/WelcomeServletIntegrationTest.java similarity index 95% rename from spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/WelcomeServletTest.java rename to spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/WelcomeServletIntegrationTest.java index 9ec177a452..d942fdd8d6 100644 --- a/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/WelcomeServletTest.java +++ b/spring-mvc-simple/src/test/java/com/baeldung/spring/servlets/WelcomeServletIntegrationTest.java @@ -8,7 +8,7 @@ import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; -public class WelcomeServletTest { +public class WelcomeServletIntegrationTest { @Test public void whenRequested_thenRedirectedToCorrectUrl() throws ServletException, IOException { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome"); diff --git a/spring-mvc-tiles/pom.xml b/spring-mvc-tiles/pom.xml index 94908d5d8b..007f7c0844 100644 --- a/spring-mvc-tiles/pom.xml +++ b/spring-mvc-tiles/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -20,7 +20,7 @@ org.springframework spring-core - ${springframework.version} + ${spring.version} commons-logging @@ -31,12 +31,12 @@ org.springframework spring-web - ${springframework.version} + ${spring.version} org.springframework spring-webmvc - ${springframework.version} + ${spring.version} @@ -83,7 +83,6 @@ - 4.3.4.RELEASE 3.0.7 3.1.0 2.3.1 diff --git a/spring-mvc-velocity/pom.xml b/spring-mvc-velocity/pom.xml index 07d7182b7d..330de252e7 100644 --- a/spring-mvc-velocity/pom.xml +++ b/spring-mvc-velocity/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -125,9 +125,6 @@ - - 4.3.4.RELEASE - 1.6.6 diff --git a/spring-protobuf/pom.xml b/spring-protobuf/pom.xml index 5081634d9b..1dce122f27 100644 --- a/spring-protobuf/pom.xml +++ b/spring-protobuf/pom.xml @@ -7,10 +7,10 @@ spring-protobuf - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-quartz/pom.xml b/spring-quartz/pom.xml index 435e571180..2a449ce494 100644 --- a/spring-quartz/pom.xml +++ b/spring-quartz/pom.xml @@ -11,10 +11,10 @@ Demo project for Scheduling in Spring with Quartz - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-reactor/pom.xml b/spring-reactor/pom.xml index 1098f8b60d..cedaa5e381 100644 --- a/spring-reactor/pom.xml +++ b/spring-reactor/pom.xml @@ -9,10 +9,10 @@ http://maven.apache.org - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-remoting/pom.xml b/spring-remoting/pom.xml index aac8357c10..150c1a771c 100644 --- a/spring-remoting/pom.xml +++ b/spring-remoting/pom.xml @@ -11,10 +11,10 @@ Parent for all projects related to Spring Remoting. - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml index 7f3c21801c..090f09de3b 100644 --- a/spring-rest-angular/pom.xml +++ b/spring-rest-angular/pom.xml @@ -9,10 +9,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-rest-embedded-tomcat/pom.xml b/spring-rest-embedded-tomcat/pom.xml index 9ab9b4b718..0bb947f96d 100644 --- a/spring-rest-embedded-tomcat/pom.xml +++ b/spring-rest-embedded-tomcat/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-5 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-5 @@ -85,7 +85,6 @@ - 5.0.2.RELEASE 2.19.1 2.9.2 1.8 diff --git a/spring-rest-full/pom.xml b/spring-rest-full/pom.xml index fd2c485eaf..2beff519c0 100644 --- a/spring-rest-full/pom.xml +++ b/spring-rest-full/pom.xml @@ -9,10 +9,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-rest-full/src/test/java/org/baeldung/spring/ConfigTest.java b/spring-rest-full/src/test/java/org/baeldung/spring/ConfigIntegrationTest.java similarity index 75% rename from spring-rest-full/src/test/java/org/baeldung/spring/ConfigTest.java rename to spring-rest-full/src/test/java/org/baeldung/spring/ConfigIntegrationTest.java index 56f3de6cb0..77603da0dd 100644 --- a/spring-rest-full/src/test/java/org/baeldung/spring/ConfigTest.java +++ b/spring-rest-full/src/test/java/org/baeldung/spring/ConfigIntegrationTest.java @@ -6,9 +6,9 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration @ComponentScan("org.baeldung.test") -public class ConfigTest extends WebMvcConfigurerAdapter { +public class ConfigIntegrationTest extends WebMvcConfigurerAdapter { - public ConfigTest() { + public ConfigIntegrationTest() { super(); } diff --git a/spring-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java b/spring-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java index a899d387ab..912ad89ed7 100644 --- a/spring-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java +++ b/spring-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java @@ -8,9 +8,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; -import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Preconditions; diff --git a/spring-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java b/spring-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java index c0e1f9d04d..a6577e4de8 100644 --- a/spring-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java +++ b/spring-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java @@ -4,7 +4,7 @@ import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import org.baeldung.common.web.AbstractDiscoverabilityLiveTest; import org.baeldung.persistence.model.Foo; -import org.baeldung.spring.ConfigTest; +import org.baeldung.spring.ConfigIntegrationTest; import org.junit.runner.RunWith; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { ConfigIntegrationTest.class }, loader = AnnotationConfigContextLoader.class) @ActiveProfiles("test") public class FooDiscoverabilityLiveTest extends AbstractDiscoverabilityLiveTest { diff --git a/spring-rest-full/src/test/java/org/baeldung/web/FooLiveTest.java b/spring-rest-full/src/test/java/org/baeldung/web/FooLiveTest.java index 5a4f472fe3..65564a6845 100644 --- a/spring-rest-full/src/test/java/org/baeldung/web/FooLiveTest.java +++ b/spring-rest-full/src/test/java/org/baeldung/web/FooLiveTest.java @@ -4,7 +4,7 @@ import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import org.baeldung.common.web.AbstractBasicLiveTest; import org.baeldung.persistence.model.Foo; -import org.baeldung.spring.ConfigTest; +import org.baeldung.spring.ConfigIntegrationTest; import org.junit.runner.RunWith; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { ConfigIntegrationTest.class }, loader = AnnotationConfigContextLoader.class) @ActiveProfiles("test") public class FooLiveTest extends AbstractBasicLiveTest { diff --git a/spring-rest-full/src/test/java/org/baeldung/web/FooPageableLiveTest.java b/spring-rest-full/src/test/java/org/baeldung/web/FooPageableLiveTest.java index 62a8983356..3f637c5213 100644 --- a/spring-rest-full/src/test/java/org/baeldung/web/FooPageableLiveTest.java +++ b/spring-rest-full/src/test/java/org/baeldung/web/FooPageableLiveTest.java @@ -13,7 +13,7 @@ import java.util.List; import org.baeldung.common.web.AbstractBasicLiveTest; import org.baeldung.persistence.model.Foo; -import org.baeldung.spring.ConfigTest; +import org.baeldung.spring.ConfigIntegrationTest; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ActiveProfiles; @@ -22,7 +22,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { ConfigIntegrationTest.class }, loader = AnnotationConfigContextLoader.class) @ActiveProfiles("test") public class FooPageableLiveTest extends AbstractBasicLiveTest { diff --git a/spring-rest-query-language/pom.xml b/spring-rest-query-language/pom.xml index d20a97268b..c16c6b583d 100644 --- a/spring-rest-query-language/pom.xml +++ b/spring-rest-query-language/pom.xml @@ -9,10 +9,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-rest-simple/README.md b/spring-rest-simple/README.md index 982e16d5a5..9345cb70cc 100644 --- a/spring-rest-simple/README.md +++ b/spring-rest-simple/README.md @@ -6,3 +6,5 @@ - [Spring RequestMapping](http://www.baeldung.com/spring-requestmapping) - [ETags for REST with Spring](http://www.baeldung.com/etags-for-rest-with-spring) - [Spring and Apache FileUpload](http://www.baeldung.com/spring-apache-file-upload) +- [Spring RestTemplate Error Handling](http://www.baeldung.com/spring-rest-template-error-handling) + diff --git a/spring-rest-simple/pom.xml b/spring-rest-simple/pom.xml index 1c6c6e1044..e774dc6ad9 100644 --- a/spring-rest-simple/pom.xml +++ b/spring-rest-simple/pom.xml @@ -31,7 +31,8 @@ org.springframework.boot - spring-boot-test + spring-boot-starter-test + test @@ -240,7 +241,7 @@ cargo-maven2-plugin ${cargo-maven2-plugin.version} - true + tomcat8x embedded diff --git a/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java b/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java index ec92ad8349..309a36609a 100644 --- a/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java +++ b/spring-rest-simple/src/main/java/org/baeldung/config/WebConfig.java @@ -1,8 +1,5 @@ package org.baeldung.config; -import java.text.SimpleDateFormat; -import java.util.List; - import org.baeldung.config.converter.KryoHttpMessageConverter; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @@ -19,6 +16,9 @@ import org.springframework.web.servlet.config.annotation.ContentNegotiationConfi import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import java.text.SimpleDateFormat; +import java.util.List; + /* * Please note that main web configuration is in src/main/webapp/WEB-INF/api-servlet.xml */ diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/exception/NotFoundException.java b/spring-rest-simple/src/main/java/org/baeldung/web/exception/NotFoundException.java new file mode 100644 index 0000000000..5b4d80a659 --- /dev/null +++ b/spring-rest-simple/src/main/java/org/baeldung/web/exception/NotFoundException.java @@ -0,0 +1,4 @@ +package org.baeldung.web.exception; + +public class NotFoundException extends RuntimeException { +} diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/handler/RestTemplateResponseErrorHandler.java b/spring-rest-simple/src/main/java/org/baeldung/web/handler/RestTemplateResponseErrorHandler.java new file mode 100644 index 0000000000..b1b87e89a5 --- /dev/null +++ b/spring-rest-simple/src/main/java/org/baeldung/web/handler/RestTemplateResponseErrorHandler.java @@ -0,0 +1,43 @@ +package org.baeldung.web.handler; + +import org.baeldung.web.exception.NotFoundException; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.stereotype.Component; +import org.springframework.web.client.ResponseErrorHandler; + +import java.io.IOException; + +@Component +public class RestTemplateResponseErrorHandler + implements ResponseErrorHandler { + + @Override + public boolean hasError(ClientHttpResponse httpResponse) + throws IOException { + + return (httpResponse + .getStatusCode() + .series() == HttpStatus.Series.CLIENT_ERROR || httpResponse + .getStatusCode() + .series() == HttpStatus.Series.SERVER_ERROR); + } + + @Override + public void handleError(ClientHttpResponse httpResponse) + throws IOException { + + if (httpResponse + .getStatusCode() + .series() == HttpStatus.Series.SERVER_ERROR) { + //Handle SERVER_ERROR + } else if (httpResponse + .getStatusCode() + .series() == HttpStatus.Series.CLIENT_ERROR) { + //Handle CLIENT_ERROR + if (httpResponse.getStatusCode() == HttpStatus.NOT_FOUND) { + throw new NotFoundException(); + } + } + } +} diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/model/Bar.java b/spring-rest-simple/src/main/java/org/baeldung/web/model/Bar.java new file mode 100644 index 0000000000..474e2070a5 --- /dev/null +++ b/spring-rest-simple/src/main/java/org/baeldung/web/model/Bar.java @@ -0,0 +1,22 @@ +package org.baeldung.web.model; + +public class Bar { + private String id; + private String name; + + 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; + } +} diff --git a/spring-rest-simple/src/main/java/org/baeldung/web/service/BarConsumerService.java b/spring-rest-simple/src/main/java/org/baeldung/web/service/BarConsumerService.java new file mode 100644 index 0000000000..4188677b4f --- /dev/null +++ b/spring-rest-simple/src/main/java/org/baeldung/web/service/BarConsumerService.java @@ -0,0 +1,26 @@ +package org.baeldung.web.service; + +import org.baeldung.web.handler.RestTemplateResponseErrorHandler; +import org.baeldung.web.model.Bar; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +@Service +public class BarConsumerService { + + private RestTemplate restTemplate; + + @Autowired + public BarConsumerService(RestTemplateBuilder restTemplateBuilder) { + RestTemplate restTemplate = restTemplateBuilder + .errorHandler(new RestTemplateResponseErrorHandler()) + .build(); + } + + public Bar fetchBarById(String barId) { + return restTemplate.getForObject("/bars/4242", Bar.class); + } + +} diff --git a/spring-rest-simple/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java b/spring-rest-simple/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java new file mode 100644 index 0000000000..2dfa81f441 --- /dev/null +++ b/spring-rest-simple/src/test/java/org/baeldung/web/handler/RestTemplateResponseErrorHandlerIntegrationTest.java @@ -0,0 +1,48 @@ +package org.baeldung.web.handler; + +import org.baeldung.web.exception.NotFoundException; +import org.baeldung.web.model.Bar; +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.autoconfigure.web.client.RestClientTest; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.client.ExpectedCount; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestTemplate; + +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = { NotFoundException.class, Bar.class }) +@RestClientTest +public class RestTemplateResponseErrorHandlerIntegrationTest { + + @Autowired private MockRestServiceServer server; + @Autowired private RestTemplateBuilder builder; + + @Test(expected = NotFoundException.class) + public void givenRemoteApiCall_when404Error_thenThrowNotFound() { + Assert.assertNotNull(this.builder); + Assert.assertNotNull(this.server); + + RestTemplate restTemplate = this.builder + .errorHandler(new RestTemplateResponseErrorHandler()) + .build(); + + this.server + .expect(ExpectedCount.once(), requestTo("/bars/4242")) + .andExpect(method(HttpMethod.GET)) + .andRespond(withStatus(HttpStatus.NOT_FOUND)); + + Bar response = restTemplate.getForObject("/bars/4242", Bar.class); + this.server.verify(); + } +} \ No newline at end of file diff --git a/spring-rest/README.md b/spring-rest/README.md index 6c6f39e544..d1dcf554a5 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -19,3 +19,8 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [RequestBody and ResponseBody Annotations](http://www.baeldung.com/requestbody-and-responsebody-annotations) - [Introduction to CheckStyle](http://www.baeldung.com/checkstyle-java) - [How to Change the Default Port in Spring Boot](http://www.baeldung.com/spring-boot-change-port) +- [Guide to DeferredResult in Spring](http://www.baeldung.com/spring-deferred-result) +- [Spring Custom Property Editor](http://www.baeldung.com/spring-mvc-custom-property-editor) +- [Using the Spring RestTemplate Interceptor](http://www.baeldung.com/spring-rest-template-interceptor) +- [Configure a RestTemplate with RestTemplateBuilder](http://www.baeldung.com/spring-rest-template-builder) + diff --git a/spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java b/spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java index 3619f43f8a..8743af20fe 100644 --- a/spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java +++ b/spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java @@ -3,12 +3,10 @@ package org.baeldung.config; import java.util.ArrayList; import java.util.List; -import org.baeldung.interceptors.RestTemplateLoggingInterceptor; +import org.baeldung.interceptors.RestTemplateHeaderModifierInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.http.client.BufferingClientHttpRequestFactory; import org.springframework.http.client.ClientHttpRequestInterceptor; -import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.util.CollectionUtils; import org.springframework.web.client.RestTemplate; @@ -17,13 +15,13 @@ public class RestClientConfig { @Bean public RestTemplate restTemplate() { - RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())); + RestTemplate restTemplate = new RestTemplate(); List interceptors = restTemplate.getInterceptors(); if (CollectionUtils.isEmpty(interceptors)) { interceptors = new ArrayList(); } - interceptors.add(new RestTemplateLoggingInterceptor()); + interceptors.add(new RestTemplateHeaderModifierInterceptor()); restTemplate.setInterceptors(interceptors); return restTemplate; } diff --git a/spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateHeaderModifierInterceptor.java b/spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateHeaderModifierInterceptor.java new file mode 100644 index 0000000000..fabb904634 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateHeaderModifierInterceptor.java @@ -0,0 +1,18 @@ +package org.baeldung.interceptors; + +import java.io.IOException; + +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; + +public class RestTemplateHeaderModifierInterceptor implements ClientHttpRequestInterceptor { + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + ClientHttpResponse response = execution.execute(request, body); + response.getHeaders().add("Foo", "bar"); + return response; + } +} diff --git a/spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateLoggingInterceptor.java b/spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateLoggingInterceptor.java deleted file mode 100644 index 03a9cdc806..0000000000 --- a/spring-rest/src/main/java/org/baeldung/interceptors/RestTemplateLoggingInterceptor.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.baeldung.interceptors; - -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.http.HttpRequest; -import org.springframework.http.client.ClientHttpRequestExecution; -import org.springframework.http.client.ClientHttpRequestInterceptor; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.util.StreamUtils; - -public class RestTemplateLoggingInterceptor implements ClientHttpRequestInterceptor { - - @Override - public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { - logRequest(body); - ClientHttpResponse response = execution.execute(request, body); - logResponse(response); - response.getHeaders().add("Foo", "bar"); - return response; - } - - private void logRequest(byte[] body) { - if (body.length > 0) { - String payLoad = new String(body, StandardCharsets.UTF_8); - System.out.println(payLoad); - } - } - - private void logResponse(ClientHttpResponse response) throws IOException { - long contentLength = response.getHeaders() - .getContentLength(); - if (contentLength != 0) { - String payLoad = StreamUtils.copyToString(response.getBody(), StandardCharsets.UTF_8); - System.out.println(payLoad); - } - } -} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java new file mode 100644 index 0000000000..a39994ae67 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java @@ -0,0 +1,32 @@ +package org.baeldung.resttemplate.configuration; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; + +import java.io.IOException; + +/** + * interceptor to log incoming requests + */ +public class CustomClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { + + private static final Logger LOGGER = LoggerFactory.getLogger(CustomClientHttpRequestInterceptor.class); + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + + logRequestDetails(request); + + return execution.execute(request, body); + } + + private void logRequestDetails(HttpRequest request) { + LOGGER.info("Request Headers: {}", request.getHeaders()); + LOGGER.info("Request Method: {}", request.getMethod()); + LOGGER.info("Request URI: {}", request.getURI()); + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java new file mode 100644 index 0000000000..5e8220d064 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java @@ -0,0 +1,14 @@ +package org.baeldung.resttemplate.configuration; + +import org.springframework.boot.web.client.RestTemplateCustomizer; +import org.springframework.web.client.RestTemplate; + +/** + * customize rest template with an interceptor + */ +public class CustomRestTemplateCustomizer implements RestTemplateCustomizer { + @Override + public void customize(RestTemplate restTemplate) { + restTemplate.getInterceptors().add(new CustomClientHttpRequestInterceptor()); + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java new file mode 100644 index 0000000000..ee404db4f8 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java @@ -0,0 +1,37 @@ +package org.baeldung.resttemplate.configuration; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestTemplate; + +/** + * Controller to test RestTemplate configuration + */ +@RestController +public class HelloController { + + private static final String RESOURCE_URL = "http://localhost:8082/spring-rest/baz"; + private RestTemplate restTemplate; + + @Autowired + public HelloController(RestTemplateBuilder builder) { + this.restTemplate = builder.build(); + } + + @RequestMapping("/foo") + public String foo() { + + ResponseEntity response = restTemplate.getForEntity(RESOURCE_URL, String.class); + + return response.getBody(); + } + + @RequestMapping("/baz") + public String baz() { + return "Foo"; + } + +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/RestTemplateConfigurationApplication.java b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/RestTemplateConfigurationApplication.java new file mode 100644 index 0000000000..76fc346aca --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/RestTemplateConfigurationApplication.java @@ -0,0 +1,14 @@ +package org.baeldung.resttemplate.configuration; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@EnableAutoConfiguration +public class RestTemplateConfigurationApplication { + + public static void main(String[] args) { + SpringApplication.run(RestTemplateConfigurationApplication.class, args); + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java new file mode 100644 index 0000000000..4e121185b1 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java @@ -0,0 +1,28 @@ +package org.baeldung.resttemplate.configuration; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; + +@Configuration +@EnableAutoConfiguration +@ComponentScan("org.baeldung.resttemplate.configuration") +public class SpringConfig { + + @Bean + @Qualifier("customRestTemplateCustomizer") + public CustomRestTemplateCustomizer customRestTemplateCustomizer() { + return new CustomRestTemplateCustomizer(); + } + + @Bean + @DependsOn(value = {"customRestTemplateCustomizer"}) + public RestTemplateBuilder restTemplateBuilder() { + return new RestTemplateBuilder(customRestTemplateCustomizer()); + } + +} diff --git a/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorTest.java b/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java similarity index 97% rename from spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorTest.java rename to spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java index e87adbc712..a84f866dfe 100644 --- a/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorTest.java +++ b/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java @@ -10,7 +10,7 @@ import com.baeldung.propertyeditor.creditcard.CreditCard; import com.baeldung.propertyeditor.creditcard.CreditCardEditor; @RunWith(MockitoJUnitRunner.class) -public class CreditCardEditorTest { +public class CreditCardEditorUnitTest { private CreditCardEditor creditCardEditor; diff --git a/spring-security-acl/pom.xml b/spring-security-acl/pom.xml index 7ddbf66365..88502bd268 100644 --- a/spring-security-acl/pom.xml +++ b/spring-security-acl/pom.xml @@ -11,10 +11,10 @@ Spring Security ACL - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-security-cache-control/pom.xml b/spring-security-cache-control/pom.xml index 890ff5bd3f..85b8b5a203 100644 --- a/spring-security-cache-control/pom.xml +++ b/spring-security-cache-control/pom.xml @@ -8,10 +8,10 @@ 1.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-security-client/spring-security-jsp-authentication/pom.xml b/spring-security-client/spring-security-jsp-authentication/pom.xml index 9b1ebc6fdc..637fd3dbdb 100644 --- a/spring-security-client/spring-security-jsp-authentication/pom.xml +++ b/spring-security-client/spring-security-jsp-authentication/pom.xml @@ -12,10 +12,10 @@ Spring Security JSP Authentication tag sample - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-security-client/spring-security-jsp-authorize/pom.xml b/spring-security-client/spring-security-jsp-authorize/pom.xml index ee8c9bacbd..94f70ed5f0 100644 --- a/spring-security-client/spring-security-jsp-authorize/pom.xml +++ b/spring-security-client/spring-security-jsp-authorize/pom.xml @@ -12,10 +12,10 @@ Spring Security JSP Authorize tag sample - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-security-client/spring-security-jsp-config/pom.xml b/spring-security-client/spring-security-jsp-config/pom.xml index 0ec72c3527..54dc2fe947 100644 --- a/spring-security-client/spring-security-jsp-config/pom.xml +++ b/spring-security-client/spring-security-jsp-config/pom.xml @@ -12,10 +12,10 @@ Spring Security JSP configuration - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-security-client/spring-security-mvc/pom.xml b/spring-security-client/spring-security-mvc/pom.xml index a6c3065cc8..5064aec7e8 100644 --- a/spring-security-client/spring-security-mvc/pom.xml +++ b/spring-security-client/spring-security-mvc/pom.xml @@ -12,10 +12,10 @@ Spring Security MVC - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml index 345daa9570..7bea8124e7 100644 --- a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml @@ -12,10 +12,10 @@ Spring Security thymeleaf authentication tag sample - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-security-client/spring-security-thymeleaf-authorize/pom.xml b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml index 3e66e9f613..b03464877a 100644 --- a/spring-security-client/spring-security-thymeleaf-authorize/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml @@ -12,10 +12,10 @@ Spring Security thymeleaf authorize tag sample - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-security-client/spring-security-thymeleaf-config/pom.xml b/spring-security-client/spring-security-thymeleaf-config/pom.xml index f5d4306754..3abe9d8c8b 100644 --- a/spring-security-client/spring-security-thymeleaf-config/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-config/pom.xml @@ -12,10 +12,10 @@ Spring Security thymeleaf configuration sample project - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-security-core/pom.xml b/spring-security-core/pom.xml index 27c6741790..a11743d9fa 100644 --- a/spring-security-core/pom.xml +++ b/spring-security-core/pom.xml @@ -9,10 +9,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-security-mvc-custom/pom.xml b/spring-security-mvc-custom/pom.xml index a320f6b137..52ec1e4ef0 100644 --- a/spring-security-mvc-custom/pom.xml +++ b/spring-security-mvc-custom/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -193,8 +193,7 @@ - 4.3.4.RELEASE - 4.2.0.RELEASE + 4.2.6.RELEASE 5.2.5.Final diff --git a/spring-security-mvc-digest-auth/pom.xml b/spring-security-mvc-digest-auth/pom.xml index 9387220b2a..a0a6a9647e 100644 --- a/spring-security-mvc-digest-auth/pom.xml +++ b/spring-security-mvc-digest-auth/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -35,7 +35,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -46,55 +46,55 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} org.springframework spring-oxm - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} @@ -149,7 +149,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -200,8 +200,7 @@ - 4.3.4.RELEASE - 4.2.0.RELEASE + 4.2.6.RELEASE 5.2.5.Final diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml index 286b189d87..6a9aa5eebe 100644 --- a/spring-security-mvc-ldap/pom.xml +++ b/spring-security-mvc-ldap/pom.xml @@ -9,10 +9,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-security-mvc-login/pom.xml b/spring-security-mvc-login/pom.xml index ee11bf067c..6f4bd8c8e0 100644 --- a/spring-security-mvc-login/pom.xml +++ b/spring-security-mvc-login/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -40,7 +40,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -51,43 +51,43 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} @@ -111,7 +111,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -167,8 +167,7 @@ - 4.3.6.RELEASE - 4.2.1.RELEASE + 4.2.6.RELEASE 5.2.5.Final diff --git a/spring-security-mvc-persisted-remember-me/pom.xml b/spring-security-mvc-persisted-remember-me/pom.xml index 5c3ac4b7c4..f8fa4400c9 100644 --- a/spring-security-mvc-persisted-remember-me/pom.xml +++ b/spring-security-mvc-persisted-remember-me/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -37,7 +37,7 @@ org.springframework spring-orm - ${org.springframework.version} + ${spring.version} @@ -45,7 +45,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -56,43 +56,43 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} @@ -189,8 +189,7 @@ - 4.3.4.RELEASE - 4.2.0.RELEASE + 4.2.6.RELEASE 5.2.5.Final diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index 130778151f..da0bede349 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -40,7 +40,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -51,43 +51,43 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} @@ -160,8 +160,7 @@ - 4.3.4.RELEASE - 4.2.0.RELEASE + 4.2.6.RELEASE 5.2.5.Final diff --git a/spring-security-mvc-socket/pom.xml b/spring-security-mvc-socket/pom.xml index 6168740cb7..5cd2c080d2 100644 --- a/spring-security-mvc-socket/pom.xml +++ b/spring-security-mvc-socket/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -20,7 +20,7 @@ org.springframework spring-core - ${springframework.version} + ${spring.version} commons-logging @@ -31,7 +31,7 @@ org.springframework spring-web - ${springframework.version} + ${spring.version} commons-logging @@ -42,7 +42,7 @@ org.springframework spring-webmvc - ${springframework.version} + ${spring.version} commons-logging @@ -84,12 +84,12 @@ org.springframework spring-websocket - ${springframework.version} + ${spring.version} org.springframework spring-messaging - ${springframework.version} + ${spring.version} org.springframework.security @@ -174,8 +174,7 @@ - 4.3.8.RELEASE - 4.2.3.RELEASE + 4.2.6.RELEASE 2.8.7 1.7.25 5.2.10.Final diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml index bed3cd033d..a30b783842 100644 --- a/spring-security-rest-basic-auth/pom.xml +++ b/spring-security-rest-basic-auth/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -35,7 +35,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -46,49 +46,49 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} org.springframework spring-oxm - ${org.springframework.version} + ${spring.version} @@ -166,7 +166,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -271,8 +271,7 @@ - 4.3.6.RELEASE - 4.2.1.RELEASE + 4.2.6.RELEASE 5.2.5.Final diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index cfa3ad4b99..1ee324bcdb 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -9,10 +9,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index e29012a3a5..e6721c9fc7 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -35,7 +35,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -46,43 +46,43 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} @@ -138,7 +138,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -284,8 +284,7 @@ - 4.3.4.RELEASE - 4.2.0.RELEASE + 4.2.6.RELEASE 0.21.0.RELEASE diff --git a/spring-security-sso/pom.xml b/spring-security-sso/pom.xml index 938636ff18..f68b9addac 100644 --- a/spring-security-sso/pom.xml +++ b/spring-security-sso/pom.xml @@ -9,10 +9,10 @@ pom - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-security-stormpath/pom.xml b/spring-security-stormpath/pom.xml index 17973165ea..71a7123c2c 100644 --- a/spring-security-stormpath/pom.xml +++ b/spring-security-stormpath/pom.xml @@ -9,10 +9,10 @@ http://maven.apache.org - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-security-thymeleaf/pom.xml b/spring-security-thymeleaf/pom.xml index aa36e5f59a..28d6126b55 100644 --- a/spring-security-thymeleaf/pom.xml +++ b/spring-security-thymeleaf/pom.xml @@ -10,10 +10,10 @@ Spring Security with Thymeleaf tutorial - parent-boot-5 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-2 diff --git a/spring-security-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/SecurityConfiguration.java b/spring-security-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/SecurityConfiguration.java index 687c0c2e39..0a4344db4d 100644 --- a/spring-security-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/SecurityConfiguration.java +++ b/spring-security-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/SecurityConfiguration.java @@ -1,11 +1,13 @@ package com.baeldung.springsecuritythymeleaf; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @@ -33,11 +35,16 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user") - .password("password") + .password(passwordEncoder().encode("password")) .roles("USER") .and() .withUser("admin") - .password("admin") + .password(passwordEncoder().encode("admin")) .roles("ADMIN"); } + + @Bean + public BCryptPasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } } diff --git a/spring-security-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/SpringSecurityThymeleafApplicationTests.java b/spring-security-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/SpringSecurityThymeleafApplicationIntegrationTest.java similarity index 90% rename from spring-security-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/SpringSecurityThymeleafApplicationTests.java rename to spring-security-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/SpringSecurityThymeleafApplicationIntegrationTest.java index dea254dd31..c852d05e73 100644 --- a/spring-security-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/SpringSecurityThymeleafApplicationTests.java +++ b/spring-security-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/SpringSecurityThymeleafApplicationIntegrationTest.java @@ -11,7 +11,7 @@ import org.springframework.web.context.WebApplicationContext; @RunWith(SpringRunner.class) @SpringBootTest -public class SpringSecurityThymeleafApplicationTests { +public class SpringSecurityThymeleafApplicationIntegrationTest { @Autowired ViewController viewController; diff --git a/spring-security-x509/pom.xml b/spring-security-x509/pom.xml index 89fed39920..d6a4b5693b 100644 --- a/spring-security-x509/pom.xml +++ b/spring-security-x509/pom.xml @@ -9,10 +9,10 @@ pom - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-session/pom.xml b/spring-session/pom.xml index c1c872ca74..4c256663b0 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -7,10 +7,10 @@ jar - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-sleuth/pom.xml b/spring-sleuth/pom.xml index 2fee474dbe..418edeaec7 100644 --- a/spring-sleuth/pom.xml +++ b/spring-sleuth/pom.xml @@ -8,10 +8,10 @@ jar - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-social-login/pom.xml b/spring-social-login/pom.xml index d2e9497bcf..d08600a8e4 100644 --- a/spring-social-login/pom.xml +++ b/spring-social-login/pom.xml @@ -6,10 +6,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiLiveTest.java similarity index 99% rename from spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java rename to spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiLiveTest.java index 0b94027df0..42be6b950b 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiLiveTest.java @@ -28,7 +28,7 @@ import java.util.Map; * API tests for PetApi */ @Ignore -public class PetApiTest { +public class PetApiLiveTest { private final PetApi api = new PetApi(); diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiLiveTest.java similarity index 98% rename from spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java rename to spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiLiveTest.java index ce332bee0d..be0cb8030d 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiLiveTest.java @@ -26,7 +26,7 @@ import java.util.Map; * API tests for StoreApi */ @Ignore -public class StoreApiTest { +public class StoreApiLiveTest { private final StoreApi api = new StoreApi(); diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiLiveTest.java similarity index 99% rename from spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java rename to spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiLiveTest.java index 59e7a39679..5dae1430a0 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiLiveTest.java @@ -26,7 +26,7 @@ import java.util.Map; * API tests for UserApi */ @Ignore -public class UserApiTest { +public class UserApiLiveTest { private final UserApi api = new UserApi(); diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md index 9346b74c89..27af6c077a 100644 --- a/spring-thymeleaf/README.md +++ b/spring-thymeleaf/README.md @@ -14,6 +14,7 @@ - [Working with Fragments in Thymeleaf](http://www.baeldung.com/spring-thymeleaf-fragments) - [Conditionals in Thymeleaf](http://www.baeldung.com/spring-thymeleaf-conditionals) - [Iteration in Thymeleaf](http://www.baeldung.com/thymeleaf-iteration) +- [Working With Arrays in Thymeleaf](http://www.baeldung.com/thymeleaf-arrays) ### Build the Project diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index d13356b3d7..6e0b7f6545 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -173,4 +173,4 @@ 2.2 - \ No newline at end of file + diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BookController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BookController.java new file mode 100644 index 0000000000..4c69a60b8e --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BookController.java @@ -0,0 +1,48 @@ +package com.baeldung.thymeleaf.controller; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; + +import com.baeldung.thymeleaf.model.Book; +import com.baeldung.thymeleaf.model.Page; +import com.baeldung.thymeleaf.utils.BookUtils; + +@Controller +public class BookController { + + private static int currentPage = 1; + private static int pageSize = 5; + + @RequestMapping(value = "/listBooks", method = RequestMethod.GET) + public String listBooks(Model model, @RequestParam("page") Optional page, @RequestParam("size") Optional size) { + page.ifPresent(p -> currentPage = p); + size.ifPresent(s -> pageSize = s); + + List books = BookUtils.buildBooks(); + Page bookPage = new Page(books, pageSize, currentPage); + + model.addAttribute("books", bookPage.getList()); + model.addAttribute("selectedPage", bookPage.getCurrentPage()); + model.addAttribute("pageSize", pageSize); + + int totalPages = bookPage.getTotalPages(); + model.addAttribute("totalPages", totalPages); + + if (totalPages > 1) { + List pageNumbers = IntStream.rangeClosed(1, totalPages) + .boxed() + .collect(Collectors.toList()); + model.addAttribute("pageNumbers", pageNumbers); + } + + return "listBooks.html"; + } +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Book.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Book.java new file mode 100644 index 0000000000..0203231175 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Book.java @@ -0,0 +1,29 @@ +package com.baeldung.thymeleaf.model; + +public class Book { + private int id; + private String name; + + public Book(int id, String name) { + super(); + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Page.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Page.java new file mode 100644 index 0000000000..e9dd0a8135 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Page.java @@ -0,0 +1,61 @@ +package com.baeldung.thymeleaf.model; + +import java.util.Collections; +import java.util.List; + +public class Page { + + private List list; + + private int pageSize = 0; + + private int currentPage = 0; + + private int totalPages = 0; + + public Page(List list, int pageSize, int currentPage) { + + if (list.isEmpty()) { + this.list = list; + } + + if (pageSize <= 0 || pageSize > list.size() || currentPage <= 0) { + throw new IllegalArgumentException("invalid page size or current page!"); + } + + this.pageSize = pageSize; + + this.currentPage = currentPage; + + if (list.size() % pageSize == 0) { + this.totalPages = list.size() / pageSize; + } else { + this.totalPages = list.size() / pageSize + 1; + } + + int startItem = (currentPage - 1) * pageSize; + if (list.size() < startItem) { + this.list = Collections.emptyList(); + } + + int toIndex = Math.min(startItem + pageSize, list.size()); + this.list = list.subList(startItem, toIndex); + } + + public List getList() { + return list; + } + + public int getPageSize() { + return pageSize; + } + + public int getCurrentPage() { + return currentPage; + } + + public int getTotalPages() { + return totalPages; + } + +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java new file mode 100644 index 0000000000..3cd9e6a92e --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java @@ -0,0 +1,28 @@ +package com.baeldung.thymeleaf.utils; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.IntStream; + +import com.baeldung.thymeleaf.model.Book; + +public class BookUtils { + + private static List books = new ArrayList(); + + private static final int NUM_BOOKS = 30; + + private static final int MIN_BOOK_NUM = 1000; + + public static List buildBooks() { + if (books.isEmpty()) { + IntStream.range(0, NUM_BOOKS).forEach(n -> { + books.add(new Book(MIN_BOOK_NUM + n + 1, "Spring in Action")); + }); + + } + + return books; + } + +} diff --git a/spring-thymeleaf/src/main/resources/messages_en.properties b/spring-thymeleaf/src/main/resources/messages_en.properties index 373c20f1d1..b534d448b6 100644 --- a/spring-thymeleaf/src/main/resources/messages_en.properties +++ b/spring-thymeleaf/src/main/resources/messages_en.properties @@ -1,12 +1,13 @@ -msg.id=ID -msg.name=Name -msg.gender=Gender -msg.percent=Percentage -welcome.message=Welcome Student !!! -msg.AddStudent=Add Student -msg.ListStudents=List Students -msg.Home=Home -msg.ListTeachers=List Teachers -msg.courses=Courses -msg.skills=Skills +msg.id=ID +msg.name=Name +msg.gender=Gender +msg.percent=Percentage +welcome.message=Welcome Student !!! +msg.AddStudent=Add Student +msg.ListStudents=List Students +msg.Home=Home +msg.ListTeachers=List Teachers +msg.ListBooks=List Books with paging +msg.courses=Courses +msg.skills=Skills msg.active=Active \ No newline at end of file diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html index 3d4f8b530f..b458f7270c 100644 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/home.html @@ -21,6 +21,9 @@ + + + diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/listBooks.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/listBooks.html new file mode 100644 index 0000000000..3f102c545c --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/listBooks.html @@ -0,0 +1,58 @@ + + + + +Book List + + +

Book List

+ + + + + + + + + +
+ +
+ +
+
+ +
+

+ +

+
+ + + + diff --git a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/FragmentsTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/FragmentsIntegrationTest.java similarity index 98% rename from spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/FragmentsTest.java rename to spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/FragmentsIntegrationTest.java index 93261b02df..5bc45d0004 100644 --- a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/FragmentsTest.java +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/FragmentsIntegrationTest.java @@ -33,7 +33,7 @@ import static org.hamcrest.Matchers.containsString; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) -public class FragmentsTest { +public class FragmentsIntegrationTest { @Autowired WebApplicationContext wac; diff --git a/spring-userservice/pom.xml b/spring-userservice/pom.xml index 872b8ed352..c372beaa3c 100644 --- a/spring-userservice/pom.xml +++ b/spring-userservice/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -20,12 +20,12 @@ org.springframework spring-orm - ${org.springframework.version} + ${spring.version} org.springframework spring-context - ${org.springframework.version} + ${spring.version} @@ -100,14 +100,14 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -118,12 +118,12 @@ org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} @@ -216,8 +216,7 @@ - 4.2.0.RELEASE - 4.3.4.RELEASE + 4.2.6.RELEASE 1.4.2.RELEASE 3.21.0-GA diff --git a/spring-zuul/pom.xml b/spring-zuul/pom.xml index b1036c9a8a..37bdb09367 100644 --- a/spring-zuul/pom.xml +++ b/spring-zuul/pom.xml @@ -8,10 +8,10 @@ pom - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/stripe/pom.xml b/stripe/pom.xml index b6dae6e680..ca165934a0 100644 --- a/stripe/pom.xml +++ b/stripe/pom.xml @@ -10,10 +10,10 @@ Demo project for Stripe API - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/struts-2/pom.xml b/struts-2/pom.xml index bb23600446..51e5b9a55c 100644 --- a/struts-2/pom.xml +++ b/struts-2/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 diff --git a/testing-modules/junit-5/README.md b/testing-modules/junit-5/README.md index 0a9dccf666..6ab00e58d5 100644 --- a/testing-modules/junit-5/README.md +++ b/testing-modules/junit-5/README.md @@ -12,3 +12,5 @@ - [JUnit Assert an Exception is Thrown](http://www.baeldung.com/junit-assert-exception) - [@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll](http://www.baeldung.com/junit-before-beforeclass-beforeeach-beforeall) - [Migrating from JUnit 4 to JUnit 5](http://www.baeldung.com/junit-5-migration) + + diff --git a/testing-modules/junit-5/pom.xml b/testing-modules/junit-5/pom.xml index cfffa29aec..b33fd2fe14 100644 --- a/testing-modules/junit-5/pom.xml +++ b/testing-modules/junit-5/pom.xml @@ -56,6 +56,11 @@ + + org.junit.platform + junit-platform-engine + ${junit.platform.version} + org.junit.platform junit-platform-runner @@ -96,8 +101,8 @@ UTF-8 1.8 5.1.0 - 1.0.1 - 4.12.1 + 1.1.0 + 5.2.0 2.8.2 1.4.196 2.11.0 diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/EmployeesTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/EmployeesUnitTest.java similarity index 93% rename from testing-modules/junit-5/src/test/java/com/baeldung/EmployeesTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/EmployeesUnitTest.java index 71bb52284b..1ea116be6d 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/EmployeesTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/EmployeesUnitTest.java @@ -19,13 +19,13 @@ import static org.junit.jupiter.api.Assertions.*; @ExtendWith({ EnvironmentExtension.class, EmployeeDatabaseSetupExtension.class, EmployeeDaoParameterResolver.class }) @ExtendWith(LoggingExtension.class) @ExtendWith(IgnoreFileNotFoundExceptionExtension.class) -public class EmployeesTest { +public class EmployeesUnitTest { private EmployeeJdbcDao employeeDao; private Logger logger; - public EmployeesTest(EmployeeJdbcDao employeeDao) { + public EmployeesUnitTest(EmployeeJdbcDao employeeDao) { this.employeeDao = employeeDao; } diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsUnitTest.java similarity index 92% rename from testing-modules/junit-5/src/test/java/com/baeldung/GreetingsTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/GreetingsUnitTest.java index efde4e7404..a07162ceed 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/GreetingsUnitTest.java @@ -9,7 +9,7 @@ import org.junit.runner.RunWith; import com.baeldung.junit5.Greetings; @RunWith(JUnitPlatform.class) -public class GreetingsTest { +public class GreetingsUnitTest { @Test void whenCallingSayHello_thenReturnHello() { diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/RegisterExtensionUnitTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/RegisterExtensionUnitTest.java new file mode 100644 index 0000000000..721cfdb013 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/RegisterExtensionUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung; + +import com.baeldung.extensions.RegisterExtensionSampleExtension; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +/** + * This test demonstrates the use of the same extension in two ways. + * 1. Once as instance level field: Only method level callbacks are called. + * 2. Once as class level static field: All methods are called. + */ +public class RegisterExtensionUnitTest { + + @RegisterExtension + static RegisterExtensionSampleExtension staticExtension = new RegisterExtensionSampleExtension("static version"); + + @RegisterExtension + RegisterExtensionSampleExtension instanceLevelExtension = new RegisterExtensionSampleExtension("instance version"); + + @Test + public void demoTest() { + Assertions.assertEquals("instance version", instanceLevelExtension.getType()); + } + +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java similarity index 92% rename from testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java index f97e2ba9c7..002aae34a8 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionUnitTest.java @@ -4,7 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; -public class ExceptionAssertionTest { +public class ExceptionAssertionUnitTest { @Test public void whenExceptionThrown_thenAssertionSucceeds() { String test = null; diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/extensions/RegisterExtensionSampleExtension.java b/testing-modules/junit-5/src/test/java/com/baeldung/extensions/RegisterExtensionSampleExtension.java new file mode 100644 index 0000000000..64f4d8fd3e --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/extensions/RegisterExtensionSampleExtension.java @@ -0,0 +1,34 @@ +package com.baeldung.extensions; + +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This extension is meant to demonstrate the use of RegisterExtension. + */ +public class RegisterExtensionSampleExtension implements BeforeAllCallback, BeforeEachCallback { + + private final String type; + Logger logger = LoggerFactory.getLogger(RegisterExtensionSampleExtension.class); + + public RegisterExtensionSampleExtension(String type) { + this.type = type; + } + + @Override + public void beforeAll(ExtensionContext extensionContext) throws Exception { + logger.info("Type {} In beforeAll : {}", type, extensionContext.getDisplayName()); + } + + @Override + public void beforeEach(ExtensionContext extensionContext) throws Exception { + logger.info("Type {} In beforeEach : {}", type, extensionContext.getDisplayName()); + } + + public String getType() { + return type; + } +} diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java similarity index 93% rename from testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java index 3b89508c88..317a0797ed 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/junit5/spring/GreetingsSpringUnitTest.java @@ -11,7 +11,7 @@ import com.baeldung.junit5.Greetings; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = { SpringTestConfiguration.class }) -public class GreetingsSpringTest { +public class GreetingsSpringUnitTest { @Test void whenCallingSayHello_thenReturnHello() { diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java similarity index 74% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java index fd7fd93d66..45671f200d 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AnnotationTestExampleUnitTest.java @@ -5,10 +5,10 @@ import org.junit.Test; import org.junit.experimental.categories.Category; import com.baeldung.migration.junit4.categories.Annotations; -import com.baeldung.migration.junit4.categories.JUnit4Tests; +import com.baeldung.migration.junit4.categories.JUnit4UnitTest; -@Category(value = { Annotations.class, JUnit4Tests.class }) -public class AnnotationTestExampleTest { +@Category(value = { Annotations.class, JUnit4UnitTest.class }) +public class AnnotationTestExampleUnitTest { @Test(expected = Exception.class) public void shouldRaiseAnException() throws Exception { throw new Exception("This is my expected exception"); diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java similarity index 94% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java index ff2a05a8c4..63446f583d 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/AssertionsExampleUnitTest.java @@ -8,7 +8,7 @@ import java.util.List; import org.junit.Ignore; import org.junit.Test; -public class AssertionsExampleTest { +public class AssertionsExampleUnitTest { @Test @Ignore public void shouldFailBecauseTheNumbersAreNotEqualld() { diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java similarity index 92% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java index e26b10e7e5..aa3e46defb 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeAndAfterAnnotationsUnitTest.java @@ -15,9 +15,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(JUnit4.class) -public class BeforeAndAfterAnnotationsTest { +public class BeforeAndAfterAnnotationsUnitTest { - private static final Logger LOG = LoggerFactory.getLogger(BeforeAndAfterAnnotationsTest.class); + private static final Logger LOG = LoggerFactory.getLogger(BeforeAndAfterAnnotationsUnitTest.class); private List list; diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java similarity index 87% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java index 31717362ef..8a82a75d3d 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/BeforeClassAndAfterClassAnnotationsUnitTest.java @@ -9,9 +9,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(JUnit4.class) -public class BeforeClassAndAfterClassAnnotationsTest { +public class BeforeClassAndAfterClassAnnotationsUnitTest { - private static final Logger LOG = LoggerFactory.getLogger(BeforeClassAndAfterClassAnnotationsTest.class); + private static final Logger LOG = LoggerFactory.getLogger(BeforeClassAndAfterClassAnnotationsUnitTest.class); @BeforeClass public static void setup() { diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java similarity index 93% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java index 6cd2559f57..afe4af8c4a 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionUnitTest.java @@ -4,7 +4,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -public class ExceptionAssertionTest { +public class ExceptionAssertionUnitTest { @Rule public ExpectedException exceptionRule = ExpectedException.none(); diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java similarity index 91% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java index 10af6a9254..969d1b370e 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/RuleExampleUnitTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import com.baeldung.migration.junit4.rules.TraceUnitTestRule; -public class RuleExampleTest { +public class RuleExampleUnitTest { @Rule public final TraceUnitTestRule traceRuleTests = new TraceUnitTestRule(); diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4Tests.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java similarity index 61% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4Tests.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java index 6af63d58ab..dc5d4349f3 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4Tests.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/categories/JUnit4UnitTest.java @@ -1,5 +1,5 @@ package com.baeldung.migration.junit4.categories; -public interface JUnit4Tests { +public interface JUnit4UnitTest { } diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java similarity index 94% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java index 07d8ae64e4..c2bbfd4d07 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java @@ -12,7 +12,7 @@ import org.junit.runner.RunWith; @Tag("annotations") @Tag("junit5") @RunWith(JUnitPlatform.class) -public class AnnotationTestExampleTest { +public class AnnotationTestExampleUnitTest { @Test public void shouldRaiseAnException() throws Exception { Assertions.assertThrows(Exception.class, () -> { diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java similarity index 96% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java index 3cfe4c59f5..c35611aad1 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java @@ -10,7 +10,7 @@ import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; @RunWith(JUnitPlatform.class) -public class AssertionsExampleTest { +public class AssertionsExampleUnitTest { @Test @Disabled public void shouldFailBecauseTheNumbersAreNotEqual() { diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java similarity index 88% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java index 9af837dcb1..b81e9b7b8e 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java @@ -9,9 +9,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(JUnitPlatform.class) -public class BeforeAllAndAfterAllAnnotationsTest { +public class BeforeAllAndAfterAllAnnotationsUnitTest { - private static final Logger LOG = LoggerFactory.getLogger(BeforeAllAndAfterAllAnnotationsTest.class); + private static final Logger LOG = LoggerFactory.getLogger(BeforeAllAndAfterAllAnnotationsUnitTest.class); @BeforeAll public static void setup() { diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java similarity index 91% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java index 6302992a5b..be916d66ea 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java @@ -15,9 +15,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(JUnitPlatform.class) -public class BeforeEachAndAfterEachAnnotationsTest { +public class BeforeEachAndAfterEachAnnotationsUnitTest { - private static final Logger LOG = LoggerFactory.getLogger(BeforeEachAndAfterEachAnnotationsTest.class); + private static final Logger LOG = LoggerFactory.getLogger(BeforeEachAndAfterEachAnnotationsUnitTest.class); private List list; diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java similarity index 92% rename from testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java index a05360250b..7b1bcda730 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java @@ -9,7 +9,7 @@ import com.baeldung.migration.junit5.extensions.TraceUnitExtension; @RunWith(JUnitPlatform.class) @ExtendWith(TraceUnitExtension.class) -public class RuleExampleTest { +public class RuleExampleUnitTest { @Test public void whenTracingTests() { diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorUnitTest.java similarity index 98% rename from testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorTest.java rename to testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorUnitTest.java index cd6f2b7e4f..3db44c9d63 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorTest.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/param/PersonValidatorUnitTest.java @@ -13,7 +13,7 @@ import org.junit.runner.RunWith; @RunWith(JUnitPlatform.class) @DisplayName("Testing PersonValidator") -public class PersonValidatorTest { +public class PersonValidatorUnitTest { /** * Nested class, uses ExtendWith diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/suites/AllTests.java b/testing-modules/junit-5/src/test/java/com/baeldung/suites/AllUnitTest.java similarity index 92% rename from testing-modules/junit-5/src/test/java/com/baeldung/suites/AllTests.java rename to testing-modules/junit-5/src/test/java/com/baeldung/suites/AllUnitTest.java index 29452efc3d..30b92ad428 100644 --- a/testing-modules/junit-5/src/test/java/com/baeldung/suites/AllTests.java +++ b/testing-modules/junit-5/src/test/java/com/baeldung/suites/AllUnitTest.java @@ -7,6 +7,6 @@ import org.junit.runner.RunWith; @RunWith(JUnitPlatform.class) @SelectPackages("com.baeldung") // @SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class}) -public class AllTests { +public class AllUnitTest { } diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/LazyVerificationTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/LazyVerificationUnitTest.java similarity index 96% rename from testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/LazyVerificationTest.java rename to testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/LazyVerificationUnitTest.java index 43b39d6859..0e6921c7a1 100644 --- a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/LazyVerificationTest.java +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/LazyVerificationUnitTest.java @@ -11,7 +11,7 @@ import org.mockito.exceptions.base.MockitoAssertionError; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.VerificationCollector; -public class LazyVerificationTest { +public class LazyVerificationUnitTest { @Test public void whenLazilyVerified_thenReportsMultipleFailures() { diff --git a/testing-modules/mockito/README.md b/testing-modules/mockito/README.md index 5a8d2289a4..05cc7ca936 100644 --- a/testing-modules/mockito/README.md +++ b/testing-modules/mockito/README.md @@ -17,3 +17,4 @@ - [Hamcrest Text Matchers](http://www.baeldung.com/hamcrest-text-matchers) - [Hamcrest File Matchers](http://www.baeldung.com/hamcrest-file-matchers) - [Hamcrest Custom Matchers](http://www.baeldung.com/hamcrest-custom-matchers) +- [Hamcrest Common Core Matchers](http://www.baeldung.com/hamcrest-core-matchers) diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorTest.java b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorIntegrationTest.java similarity index 97% rename from testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorTest.java rename to testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorIntegrationTest.java index 2836bcd317..5e311c60f2 100644 --- a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorTest.java +++ b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/LuckyNumberGeneratorIntegrationTest.java @@ -14,7 +14,7 @@ import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) @PrepareForTest(fullyQualifiedNames = "com.baeldung.powermockito.introduction.LuckyNumberGenerator") -public class LuckyNumberGeneratorTest { +public class LuckyNumberGeneratorIntegrationTest { @Test public final void givenPrivateMethodWithReturn_whenUsingPowerMockito_thenCorrect() throws Exception { diff --git a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java index 4a98bbcb87..1b6431f0c2 100644 --- a/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java +++ b/testing-modules/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoIntegrationTest.java @@ -7,6 +7,8 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.*; @RunWith(PowerMockRunner.class) @@ -23,7 +25,7 @@ public class PowerMockitoIntegrationTest { when(collaborator.helloMethod()).thenReturn("Hello Baeldung!"); String welcome = collaborator.helloMethod(); - Mockito.verify(collaborator).helloMethod(); + verify(collaborator).helloMethod(); assertEquals("Hello Baeldung!", welcome); } @@ -42,7 +44,7 @@ public class PowerMockitoIntegrationTest { assertEquals("Hello Baeldung!", firstWelcome); assertEquals("Hello Baeldung!", secondWelcome); - verifyStatic(Mockito.times(2)); + verifyStatic(times(2)); CollaboratorWithStaticMethods.firstMethod(Mockito.anyString()); verifyStatic(Mockito.never()); @@ -67,7 +69,7 @@ public class PowerMockitoIntegrationTest { when(mock.finalMethod()).thenReturn("I am a final mock method."); returnValue = mock.finalMethod(); - Mockito.verify(mock).finalMethod(); + verify(mock,times(3)).finalMethod(); assertEquals("I am a final mock method.", returnValue); when(mock, "privateMethod").thenReturn("I am a private mock method."); diff --git a/testing-modules/mockito/src/test/java/org/baeldung/bddmockito/BDDMockitoTest.java b/testing-modules/mockito/src/test/java/org/baeldung/bddmockito/BDDMockitoIntegrationTest.java similarity index 96% rename from testing-modules/mockito/src/test/java/org/baeldung/bddmockito/BDDMockitoTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/bddmockito/BDDMockitoIntegrationTest.java index 9cc586fb84..e772b5e049 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/bddmockito/BDDMockitoTest.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/bddmockito/BDDMockitoIntegrationTest.java @@ -10,7 +10,7 @@ import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; -public class BDDMockitoTest { +public class BDDMockitoIntegrationTest { PhoneBookService phoneBookService; PhoneBookRepository phoneBookRepository; diff --git a/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestCoreMatchersTest.java b/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestCoreMatchersUnitTest.java similarity index 99% rename from testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestCoreMatchersTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestCoreMatchersUnitTest.java index 8f3e96c956..d66ed98e8d 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestCoreMatchersTest.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/hamcrest/HamcrestCoreMatchersUnitTest.java @@ -11,7 +11,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.StringEndsWith.endsWith; import static org.hamcrest.core.StringStartsWith.startsWith; -public class HamcrestCoreMatchersTest { +public class HamcrestCoreMatchersUnitTest { @Test public void givenTestInput_WhenUsingIsForMatch() { diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java index f846907fd7..6ec3b34db5 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoMockIntegrationTest.java @@ -24,7 +24,7 @@ public class MockitoMockIntegrationTest { } @Rule - private ExpectedException thrown = ExpectedException.none(); + public ExpectedException thrown = ExpectedException.none(); @Test public void whenUsingSimpleMock_thenCorrect() { diff --git a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsTest.java b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsUnitTest.java similarity index 97% rename from testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsTest.java rename to testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsUnitTest.java index 4de9a88dcc..49360f8d6c 100644 --- a/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsTest.java +++ b/testing-modules/mockito/src/test/java/org/baeldung/mockito/MockitoVoidMethodsUnitTest.java @@ -11,7 +11,7 @@ import org.mockito.stubbing.Answer; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) -public class MockitoVoidMethodsTest { +public class MockitoVoidMethodsUnitTest { @Test public void whenAddCalledVerified() { diff --git a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedUnitTest.java similarity index 93% rename from testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedTest.java rename to testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedUnitTest.java index af2ef3e6da..afacd8d8ad 100755 --- a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedTest.java +++ b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedUnitTest.java @@ -11,7 +11,7 @@ import java.util.NoSuchElementException; import static org.easymock.EasyMock.*; @RunWith(EasyMockRunner.class) -public class BaeldungReaderAnnotatedTest { +public class BaeldungReaderAnnotatedUnitTest { @Mock ArticleReader mockArticleReader; diff --git a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedWithRuleTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedWithRuleUnitTest.java similarity index 93% rename from testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedWithRuleTest.java rename to testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedWithRuleUnitTest.java index 28ed1484fc..086ed88888 100755 --- a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedWithRuleTest.java +++ b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderAnnotatedWithRuleUnitTest.java @@ -9,7 +9,7 @@ import java.util.NoSuchElementException; import static org.easymock.EasyMock.*; -public class BaeldungReaderAnnotatedWithRuleTest { +public class BaeldungReaderAnnotatedWithRuleUnitTest { @Rule public EasyMockRule mockRule = new EasyMockRule(this); diff --git a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockDelegationTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockDelegationUnitTest.java similarity index 91% rename from testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockDelegationTest.java rename to testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockDelegationUnitTest.java index 3ff0d6416e..89d3a2baee 100755 --- a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockDelegationTest.java +++ b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockDelegationUnitTest.java @@ -5,7 +5,7 @@ import org.junit.*; import static org.easymock.EasyMock.*; -public class BaeldungReaderMockDelegationTest { +public class BaeldungReaderMockDelegationUnitTest { EasyMockSupport easyMockSupport = new EasyMockSupport(); diff --git a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockSupportTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockSupportUnitTest.java similarity index 91% rename from testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockSupportTest.java rename to testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockSupportUnitTest.java index 3bed89927f..cd0c906949 100755 --- a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockSupportTest.java +++ b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderMockSupportUnitTest.java @@ -10,7 +10,7 @@ import static org.easymock.EasyMock.*; import static org.junit.Assert.assertEquals; @RunWith(EasyMockRunner.class) -public class BaeldungReaderMockSupportTest extends EasyMockSupport { +public class BaeldungReaderMockSupportUnitTest extends EasyMockSupport { @TestSubject BaeldungReader baeldungReader = new BaeldungReader(); @Mock ArticleReader mockArticleReader; diff --git a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderTest.java b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderUnitTest.java similarity index 96% rename from testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderTest.java rename to testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderUnitTest.java index 5b485357fd..31f6af116c 100755 --- a/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderTest.java +++ b/testing-modules/mocks/mock-comparisons/src/test/java/com/baeldung/easymock/BaeldungReaderUnitTest.java @@ -7,7 +7,7 @@ import java.util.NoSuchElementException; import static org.easymock.EasyMock.*; import static org.junit.Assert.assertEquals; -public class BaeldungReaderTest { +public class BaeldungReaderUnitTest { private BaeldungReader baeldungReader; diff --git a/testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java index aa0c6696a4..834d266cc6 100644 --- a/testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java +++ b/testing-modules/rest-testing/src/test/java/com/baeldung/rest/wiremock/introduction/JUnitManagedIntegrationTest.java @@ -1,19 +1,5 @@ package com.baeldung.rest.wiremock.introduction; -import com.github.tomakehurst.wiremock.junit.WireMockRule; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.junit.Rule; -import org.junit.Test; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Scanner; - import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; @@ -29,16 +15,46 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.junit.Assert.assertEquals; +import java.io.IOException; +import java.io.InputStream; +import java.net.ServerSocket; +import java.util.Scanner; + +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.junit.Rule; +import org.junit.Test; +import com.github.tomakehurst.wiremock.junit.WireMockRule; + public class JUnitManagedIntegrationTest { private static final String BAELDUNG_WIREMOCK_PATH = "/baeldung/wiremock"; private static final String APPLICATION_JSON = "application/json"; - + static int port; + + static { + + try { + // Get a free port + ServerSocket s = new ServerSocket(0); + port = s.getLocalPort(); + s.close(); + + } catch (IOException e) { + // No OPS + } + } + @Rule - public WireMockRule wireMockRule = new WireMockRule(); + public WireMockRule wireMockRule = new WireMockRule(port); @Test public void givenJUnitManagedServer_whenMatchingURL_thenCorrect() throws IOException { + stubFor(get(urlPathMatching("/baeldung/.*")) .willReturn(aResponse() .withStatus(200) @@ -46,7 +62,7 @@ public class JUnitManagedIntegrationTest { .withBody("\"testing-library\": \"WireMock\""))); CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet request = new HttpGet("http://localhost:8080/baeldung/wiremock"); + HttpGet request = new HttpGet(String.format("http://localhost:%s/baeldung/wiremock", port)); HttpResponse httpResponse = httpClient.execute(request); String stringResponse = convertHttpResponseToString(httpResponse); @@ -66,7 +82,7 @@ public class JUnitManagedIntegrationTest { .withBody("!!! Service Unavailable !!!"))); CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet request = new HttpGet("http://localhost:8080/baeldung/wiremock"); + HttpGet request = new HttpGet(String.format("http://localhost:%s/baeldung/wiremock", port)); request.addHeader("Accept", "text/html"); HttpResponse httpResponse = httpClient.execute(request); String stringResponse = convertHttpResponseToString(httpResponse); @@ -91,7 +107,7 @@ public class JUnitManagedIntegrationTest { StringEntity entity = new StringEntity(jsonString); CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpPost request = new HttpPost("http://localhost:8080/baeldung/wiremock"); + HttpPost request = new HttpPost(String.format("http://localhost:%s/baeldung/wiremock", port)); request.addHeader("Content-Type", APPLICATION_JSON); request.setEntity(entity); HttpResponse response = httpClient.execute(request); @@ -137,7 +153,7 @@ public class JUnitManagedIntegrationTest { private HttpResponse generateClientAndReceiveResponseForPriorityTests() throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet request = new HttpGet("http://localhost:8080/baeldung/wiremock"); + HttpGet request = new HttpGet(String.format("http://localhost:%s/baeldung/wiremock", port)); request.addHeader("Accept", "text/xml"); return httpClient.execute(request); } diff --git a/testing-modules/testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java b/testing-modules/testing/src/test/java/com/baeldung/introductionjukito/CalculatorUnitTest.java similarity index 98% rename from testing-modules/testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java rename to testing-modules/testing/src/test/java/com/baeldung/introductionjukito/CalculatorUnitTest.java index 313e1d2938..193a4b9cd8 100644 --- a/testing-modules/testing/src/test/java/com/baeldung/introductionjukito/CalculatorTest.java +++ b/testing-modules/testing/src/test/java/com/baeldung/introductionjukito/CalculatorUnitTest.java @@ -8,7 +8,7 @@ import org.junit.runner.RunWith; import static org.junit.Assert.*; @RunWith(JukitoRunner.class) -public class CalculatorTest { +public class CalculatorUnitTest { public static class Module extends JukitoModule { diff --git a/testing-modules/testing/src/test/java/com/baeldung/junit/AdditionTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/AdditionUnitTest.java similarity index 88% rename from testing-modules/testing/src/test/java/com/baeldung/junit/AdditionTest.java rename to testing-modules/testing/src/test/java/com/baeldung/junit/AdditionUnitTest.java index 0d492f8058..ae6fa355fa 100644 --- a/testing-modules/testing/src/test/java/com/baeldung/junit/AdditionTest.java +++ b/testing-modules/testing/src/test/java/com/baeldung/junit/AdditionUnitTest.java @@ -4,7 +4,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; -public class AdditionTest { +public class AdditionUnitTest { Calculator calculator = new Calculator(); @Test diff --git a/testing-modules/testing/src/test/java/com/baeldung/junit/CalculatorTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/CalculatorUnitTest.java similarity index 91% rename from testing-modules/testing/src/test/java/com/baeldung/junit/CalculatorTest.java rename to testing-modules/testing/src/test/java/com/baeldung/junit/CalculatorUnitTest.java index d1b35d1442..d5ca847106 100644 --- a/testing-modules/testing/src/test/java/com/baeldung/junit/CalculatorTest.java +++ b/testing-modules/testing/src/test/java/com/baeldung/junit/CalculatorUnitTest.java @@ -7,7 +7,7 @@ import org.junit.runners.JUnit4; import static org.junit.Assert.assertEquals; @RunWith(JUnit4.class) -public class CalculatorTest { +public class CalculatorUnitTest { Calculator calculator = new Calculator(); @Test diff --git a/testing-modules/testing/src/test/java/com/baeldung/junit/SubstractionTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/SubstractionUnitTest.java similarity index 87% rename from testing-modules/testing/src/test/java/com/baeldung/junit/SubstractionTest.java rename to testing-modules/testing/src/test/java/com/baeldung/junit/SubstractionUnitTest.java index 9650d83afe..fd98395ebc 100644 --- a/testing-modules/testing/src/test/java/com/baeldung/junit/SubstractionTest.java +++ b/testing-modules/testing/src/test/java/com/baeldung/junit/SubstractionUnitTest.java @@ -4,7 +4,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; -public class SubstractionTest { +public class SubstractionUnitTest { Calculator calculator = new Calculator(); @Test diff --git a/testing-modules/testing/src/test/java/com/baeldung/junit/SuiteTest.java b/testing-modules/testing/src/test/java/com/baeldung/junit/SuiteUnitTest.java similarity index 67% rename from testing-modules/testing/src/test/java/com/baeldung/junit/SuiteTest.java rename to testing-modules/testing/src/test/java/com/baeldung/junit/SuiteUnitTest.java index 428319e72e..76d19f84b2 100644 --- a/testing-modules/testing/src/test/java/com/baeldung/junit/SuiteTest.java +++ b/testing-modules/testing/src/test/java/com/baeldung/junit/SuiteUnitTest.java @@ -6,7 +6,7 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ - AdditionTest.class, - SubstractionTest.class}) -public class SuiteTest { + AdditionUnitTest.class, + SubstractionUnitTest.class}) +public class SuiteUnitTest { } diff --git a/testing-modules/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java b/testing-modules/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilUnitTest.java similarity index 98% rename from testing-modules/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java rename to testing-modules/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilUnitTest.java index f1659437ec..6c98454da0 100644 --- a/testing-modules/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilTest.java +++ b/testing-modules/testing/src/test/java/com/baeldung/junitparams/SafeAdditionUtilUnitTest.java @@ -9,7 +9,7 @@ import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; @RunWith(JUnitParamsRunner.class) -public class SafeAdditionUtilTest { +public class SafeAdditionUtilUnitTest { private SafeAdditionUtil serviceUnderTest = new SafeAdditionUtil(); diff --git a/testing-modules/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java b/testing-modules/testing/src/test/java/com/baeldung/lambdabehave/CalculatorUnitTest.java similarity index 98% rename from testing-modules/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java rename to testing-modules/testing/src/test/java/com/baeldung/lambdabehave/CalculatorUnitTest.java index d179c6eb0e..5b6cd73332 100644 --- a/testing-modules/testing/src/test/java/com/baeldung/lambdabehave/CalculatorTest.java +++ b/testing-modules/testing/src/test/java/com/baeldung/lambdabehave/CalculatorUnitTest.java @@ -7,7 +7,7 @@ import com.insightfullogic.lambdabehave.generators.SourceGenerator; import org.junit.runner.RunWith; @RunWith(JunitSuiteRunner.class) -public class CalculatorTest { +public class CalculatorUnitTest { private Calculator calculator; diff --git a/twilio/README.md b/twilio/README.md new file mode 100644 index 0000000000..9d230610c7 --- /dev/null +++ b/twilio/README.md @@ -0,0 +1,5 @@ + + +### Relevant Articles: + +- [Sending SMS in Java with Twilio](http://www.baeldung.com/java-sms-twilio) diff --git a/undertow/dependency-reduced-pom.xml b/undertow/dependency-reduced-pom.xml deleted file mode 100644 index a4a17f94d6..0000000000 --- a/undertow/dependency-reduced-pom.xml +++ /dev/null @@ -1,90 +0,0 @@ - - - - parent-modules - com.baeldung - 1.0.0-SNAPSHOT - - 4.0.0 - com.baeldung.undertow - undertow - undertow - 1.0-SNAPSHOT - http://maven.apache.org - - ${project.artifactId} - - - maven-shade-plugin - - - package - - shade - - - - - - maven-jar-plugin - - - - com.baeldung.undertow.SimpleServer - - - - - - - - - junit - junit - 4.12 - test - - - org.hamcrest - hamcrest-core - 1.3 - test - - - org.hamcrest - hamcrest-library - 1.3 - test - - - org.hamcrest - hamcrest-all - 1.3 - test - - - org.mockito - mockito-core - 2.8.9 - test - - - byte-buddy - net.bytebuddy - - - byte-buddy-agent - net.bytebuddy - - - objenesis - org.objenesis - - - - - - 1.8 - 1.8 - - diff --git a/vavr/README.md b/vavr/README.md index c8570db04c..b7ba72229b 100644 --- a/vavr/README.md +++ b/vavr/README.md @@ -11,3 +11,4 @@ - [Introduction to Future in Vavr](http://www.baeldung.com/vavr-future) - [Introduction to VRaptor in Java](http://www.baeldung.com/vraptor) - [Introduction to Vavr’s Either](http://www.baeldung.com/vavr-either) +- [Interoperability Between Java and Vavr](http://www.baeldung.com/java-vavr) diff --git a/vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java b/vavr/src/test/java/com/baeldung/vavr/future/FutureUnitTest.java similarity index 99% rename from vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java rename to vavr/src/test/java/com/baeldung/vavr/future/FutureUnitTest.java index d5345cad55..c398cc4095 100644 --- a/vavr/src/test/java/com/baeldung/vavr/future/FutureTest.java +++ b/vavr/src/test/java/com/baeldung/vavr/future/FutureUnitTest.java @@ -13,7 +13,7 @@ import static java.util.concurrent.Executors.newSingleThreadExecutor; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -public class FutureTest { +public class FutureUnitTest { private static final String error = "Failed to get underlying value."; private static final String HELLO = "Welcome to Baeldung!"; diff --git a/xml/README.md b/xml/README.md index 7c3ebccac6..80c6a069f0 100644 --- a/xml/README.md +++ b/xml/README.md @@ -2,3 +2,4 @@ - [Intro to XPath with Java](http://www.baeldung.com/java-xpath) - [Introduction to JiBX](http://www.baeldung.com/jibx) - [XML Libraries Support in Java](http://www.baeldung.com/java-xml-libraries) +- [DOM parsing with Xerces](http://www.baeldung.com/java-xerces-dom-parsing) diff --git a/xmlunit-2/pom.xml b/xmlunit-2/pom.xml index 171f3de03c..0a32b90af5 100644 --- a/xmlunit-2/pom.xml +++ b/xmlunit-2/pom.xml @@ -4,7 +4,6 @@ com.baeldung xmlunit-2 1.0 - XMLUnit-2 com.baeldung