diff --git a/README.md b/README.md index 1d916c8409..6dff78aa7a 100644 --- a/README.md +++ b/README.md @@ -40,3 +40,5 @@ 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/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/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/autovalue/README.md b/autovalue/README.md index 2385e82847..c6a08359ef 100644 --- a/autovalue/README.md +++ b/autovalue/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: - [Introduction to AutoValue](http://www.baeldung.com/introduction-to-autovalue) +- [Introduction to AutoFactory](http://www.baeldung.com/autofactory) diff --git a/azure/.gitignore b/azure/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/azure/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/azure/README.md b/azure/README.md new file mode 100644 index 0000000000..c60186e1ce --- /dev/null +++ b/azure/README.md @@ -0,0 +1,4 @@ +### Relevant Articles: + +- [Deploy Spring Boot App to Azure](http://www.baeldung.com/spring-boot-azure) + diff --git a/azure/docker/Dockerfile b/azure/docker/Dockerfile new file mode 100644 index 0000000000..f865518330 --- /dev/null +++ b/azure/docker/Dockerfile @@ -0,0 +1,6 @@ +FROM frolvlad/alpine-oraclejdk8:slim +VOLUME /tmp +ADD azure-0.1.jar app.jar +RUN sh -c 'touch /app.jar' +EXPOSE 8080 +ENTRYPOINT [ "sh", "-c", "java -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ] diff --git a/azure/pom.xml b/azure/pom.xml new file mode 100644 index 0000000000..c5175a4fec --- /dev/null +++ b/azure/pom.xml @@ -0,0 +1,131 @@ + + + 4.0.0 + + com.baeldung + azure + 0.1 + war + azure + Demo project for Spring Boot on Azure + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + baeldungadr + ${azure.containerRegistry}.azurecr.io + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + + + + mysql + mysql-connector-java + 5.1.6 + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.spotify + docker-maven-plugin + 1.1.0 + + ${docker.image.prefix}/${project.artifactId} + https://${docker.image.prefix} + ${azure.containerRegistry} + docker + + + / + ${project.build.directory} + ${project.build.finalName}.jar + + + + + + com.microsoft.azure + azure-webapp-maven-plugin + 1.1.0 + + + azure-auth + + baeldung-group + baeldung-webapp + baeldung-plan + 1.8 + + + + + + + + + + spring.datasource.url + jdbc:h2:file:~/test + + + + spring.datasource.username + sa + + + + spring.datasource.password + + + + + + + + + + + + + + + + + + + + + diff --git a/azure/src/main/java/com/baeldung/springboot/azure/AzureApplication.java b/azure/src/main/java/com/baeldung/springboot/azure/AzureApplication.java new file mode 100644 index 0000000000..5233f6bdf4 --- /dev/null +++ b/azure/src/main/java/com/baeldung/springboot/azure/AzureApplication.java @@ -0,0 +1,19 @@ +package com.baeldung.springboot.azure; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +@SpringBootApplication +public class AzureApplication extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(AzureApplication.class); + } + + public static void main(String[] args) { + SpringApplication.run(AzureApplication.class, args); + } +} diff --git a/azure/src/main/java/com/baeldung/springboot/azure/TestController.java b/azure/src/main/java/com/baeldung/springboot/azure/TestController.java new file mode 100644 index 0000000000..9a18bf4d65 --- /dev/null +++ b/azure/src/main/java/com/baeldung/springboot/azure/TestController.java @@ -0,0 +1,34 @@ +package com.baeldung.springboot.azure; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import static com.baeldung.springboot.azure.User.userNamed; + +/** + * @author aiet + */ +@RestController +public class TestController { + + @GetMapping("/hello") + public String hello() { + return "hello azure!"; + } + + @Autowired private UserRepository userRepository; + + @PostMapping("/user") + public String register(@RequestParam String name) { + userRepository.save(userNamed(name)); + return "registered"; + } + + @GetMapping("/user") + public Iterable userlist() { + return userRepository.findAll(); + } +} diff --git a/azure/src/main/java/com/baeldung/springboot/azure/User.java b/azure/src/main/java/com/baeldung/springboot/azure/User.java new file mode 100644 index 0000000000..d7a25aa246 --- /dev/null +++ b/azure/src/main/java/com/baeldung/springboot/azure/User.java @@ -0,0 +1,43 @@ +package com.baeldung.springboot.azure; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +/** + * @author aiet + */ +@Entity +public class User { + + public User() { + } + + public static User userNamed(String name) { + User u = new User(); + u.setName(name); + return u; + } + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Integer id; + private String name; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/azure/src/main/java/com/baeldung/springboot/azure/UserRepository.java b/azure/src/main/java/com/baeldung/springboot/azure/UserRepository.java new file mode 100644 index 0000000000..74a23f3180 --- /dev/null +++ b/azure/src/main/java/com/baeldung/springboot/azure/UserRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.springboot.azure; + +import org.springframework.data.repository.CrudRepository; + +/** + * @author aiet + */ +public interface UserRepository extends CrudRepository { +} diff --git a/azure/src/main/resources/application.properties b/azure/src/main/resources/application.properties new file mode 100644 index 0000000000..32ee873194 --- /dev/null +++ b/azure/src/main/resources/application.properties @@ -0,0 +1,16 @@ +server.port=8080 +server.address=0.0.0.0 +spring.jpa.hibernate.ddl-auto=create + +logging.file=azure.log +logging.level.root=info + +spring.datasource.url=jdbc:h2:file:~/test +spring.datasource.username=sa +spring.datasource.password= + +#spring.datasource.url=jdbc:mysql://localhost:3306/localdb +#spring.datasource.username=your-db-username +#spring.datasource.password=your-db-password + + diff --git a/azure/src/test/java/com/baeldung/springboot/azure/AzureApplicationTests.java b/azure/src/test/java/com/baeldung/springboot/azure/AzureApplicationTests.java new file mode 100644 index 0000000000..91632be11a --- /dev/null +++ b/azure/src/test/java/com/baeldung/springboot/azure/AzureApplicationTests.java @@ -0,0 +1,16 @@ +package com.baeldung.springboot.azure; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class AzureApplicationTests { + + @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/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/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/hashtable/HashtableUnitTest.java b/core-java-8/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java index e8c42c94e1..8d30596ab4 100644 --- a/core-java-8/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java @@ -233,7 +233,7 @@ public class HashtableUnitTest { Hashtable table = new Hashtable(); String[] animals = { "cat", "dog", "dog", "cat", "bird", "mouse", "mouse" }; for (String animal : animals) { - table.compute(animal, (key, value) -> (value == null ? Integer.valueOf(1) : Integer.valueOf(value) + 1)); + table.compute(animal, (key, value) -> (value == null ? 1 : value + 1)); } assertThat(table.values(), hasItems(2, 2, 2, 1)); @@ -271,4 +271,4 @@ public class HashtableUnitTest { assertThat(table.values(), hasItems("cat - a small domesticated carnivorous mammal", "dog - another animal")); } -} +} \ No newline at end of file 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/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/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-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/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 e0cea14b20..510eac9dbc 100644 --- a/core-java-collections/README.md +++ b/core-java-collections/README.md @@ -28,3 +28,5 @@ - [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set) - [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/main/java/com/baeldung/java/iterable/IterableSize.java b/core-java-collections/src/main/java/com/baeldung/java/iterable/IterableSize.java new file mode 100644 index 0000000000..03864f16f2 --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/java/iterable/IterableSize.java @@ -0,0 +1,65 @@ +package com.baeldung.java.iterable; + +import java.util.Collection; +import java.util.stream.StreamSupport; + +import org.apache.commons.collections4.IterableUtils; + +import com.google.common.collect.Iterables; + +/** + * Provides methods for getting the size of an {@link Iterable} object. + */ +public class IterableSize { + + /** + * Get the size of {@code Iterable} using Java 7. + * + * @param data the iterable + * @return the size of the iterable + */ + public static int sizeUsingJava7(final Iterable data) { + + if (data instanceof Collection) { + return ((Collection) data).size(); + } + int counter = 0; + for (final Object i : data) { + counter++; + } + return counter; + } + + /** + * Get the size of {@code Iterable} using Java 8. + * + * @param data the iterable + * @return the size of the iterable + */ + public static long sizeUsingJava8(final Iterable data) { + + return StreamSupport.stream(data.spliterator(), false).count(); + } + + /** + * Get the size of {@code Iterable} using Apache Collections. + * + * @param data the iterable + * @return the size of the iterable + */ + public static int sizeUsingApacheCollections(final Iterable data) { + + return IterableUtils.size(data); + } + + /** + * Get the size of {@code Iterable} using Google Guava. + * + * @param data the iterable + * @return the size of the iterable + */ + public static int sizeUsingGoogleGuava(final Iterable data) { + + return Iterables.size(data); + } +} 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/IterableSizeUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/iterable/IterableSizeUnitTest.java new file mode 100644 index 0000000000..4bc413dee0 --- /dev/null +++ b/core-java-collections/src/test/java/com/baeldung/java/iterable/IterableSizeUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.java.iterable; + +import static org.junit.Assert.assertEquals; + +import java.sql.SQLException; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.google.common.collect.Lists; + +class IterableSizeUnitTest { + + private final List list = Lists.newArrayList("Apple", "Orange", "Banana"); + + private Iterable data; + + @Test + void whenUsingJava7_iterableOfCollectionType_thenCorrectSize() { + + final int size = IterableSize.sizeUsingJava7(list); + + assertEquals(3, size); + } + + @Test + void whenUsingJava7_iterableNotOfCollectionType_thenCorrect() { + + final SQLException exception = new SQLException(); + exception.setNextException(new SQLException()); + final int size = IterableSize.sizeUsingJava7(exception); + + assertEquals(2, size); + } + + @Test + void whenUsingJava8_thenCorrect() { + + final long size = IterableSize.sizeUsingJava8(list); + + assertEquals(3, size); + } + + @Test + void whenUsingApacheCollections_thenCorrect() { + + final int size = IterableSize.sizeUsingApacheCollections(list); + + assertEquals(3, size); + } + + @Test + void whenUsingGoogleGuava_thenCorrect() { + + final int size = IterableSize.sizeUsingGoogleGuava(list); + + assertEquals(3, size); + } +} \ No newline at end of file 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/pom.xml b/core-java-io/pom.xml index 1437b85ac2..21e931656d 100644 --- a/core-java-io/pom.xml +++ b/core-java-io/pom.xml @@ -196,6 +196,12 @@ ${hsqldb.version} runtime + + + org.asynchttpclient + async-http-client + ${async-http-client.version} + @@ -365,6 +371,7 @@ 2.4.0 2.1.0.1 1.19 + 2.4.5 \ No newline at end of file diff --git a/core-java-io/src/main/java/com/baeldung/download/FileDownload.java b/core-java-io/src/main/java/com/baeldung/download/FileDownload.java new file mode 100644 index 0000000000..c7dd154023 --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/download/FileDownload.java @@ -0,0 +1,89 @@ +package com.baeldung.download; + +import org.apache.commons.io.FileUtils; +import org.asynchttpclient.*; + +import java.io.*; +import java.net.*; +import java.nio.channels.Channels; +import java.nio.channels.FileChannel; +import java.nio.channels.ReadableByteChannel; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.concurrent.ExecutionException; + +public class FileDownload { + + public static void downloadWithJavaIO(String url, String localFilename) { + + try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream()); FileOutputStream fileOutputStream = new FileOutputStream(localFilename)) { + + byte dataBuffer[] = new byte[1024]; + int bytesRead; + while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { + fileOutputStream.write(dataBuffer, 0, bytesRead); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void downloadWithJava7IO(String url, String localFilename) { + + try (InputStream in = new URL(url).openStream()) { + Files.copy(in, Paths.get(localFilename), StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void downloadWithJavaNIO(String fileURL, String localFilename) throws IOException { + + URL url = new URL(fileURL); + try (ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream()); + FileOutputStream fileOutputStream = new FileOutputStream(localFilename); FileChannel fileChannel = fileOutputStream.getChannel()) { + + fileChannel.transferFrom(readableByteChannel, 0, Long.MAX_VALUE); + } + } + + public static void downloadWithApacheCommons(String url, String localFilename) { + + int CONNECT_TIMEOUT = 10000; + int READ_TIMEOUT = 10000; + try { + FileUtils.copyURLToFile(new URL(url), new File(localFilename), CONNECT_TIMEOUT, READ_TIMEOUT); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public static void downloadWithAHC(String url, String localFilename) throws ExecutionException, InterruptedException, IOException { + + FileOutputStream stream = new FileOutputStream(localFilename); + AsyncHttpClient client = Dsl.asyncHttpClient(); + + client.prepareGet(url) + .execute(new AsyncCompletionHandler() { + + @Override + public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception { + stream.getChannel() + .write(bodyPart.getBodyByteBuffer()); + return State.CONTINUE; + } + + @Override + public FileOutputStream onCompleted(Response response) throws Exception { + return stream; + } + }) + .get(); + + stream.getChannel().close(); + client.close(); + } + +} diff --git a/core-java-io/src/main/java/com/baeldung/download/ResumableDownload.java b/core-java-io/src/main/java/com/baeldung/download/ResumableDownload.java new file mode 100644 index 0000000000..55ff485e40 --- /dev/null +++ b/core-java-io/src/main/java/com/baeldung/download/ResumableDownload.java @@ -0,0 +1,62 @@ +package com.baeldung.download; + +import java.io.*; +import java.net.*; + +public class ResumableDownload { + + public static long downloadFile(String downloadUrl, String saveAsFileName) throws IOException, URISyntaxException { + + File outputFile = new File(saveAsFileName); + URLConnection downloadFileConnection = new URI(downloadUrl).toURL() + .openConnection(); + return transferDataAndGetBytesDownloaded(downloadFileConnection, outputFile); + } + + private static long transferDataAndGetBytesDownloaded(URLConnection downloadFileConnection, File outputFile) throws IOException { + + long bytesDownloaded = 0; + try (InputStream is = downloadFileConnection.getInputStream(); OutputStream os = new FileOutputStream(outputFile, true)) { + + byte[] buffer = new byte[1024]; + + int bytesCount; + while ((bytesCount = is.read(buffer)) > 0) { + os.write(buffer, 0, bytesCount); + bytesDownloaded += bytesCount; + } + } + return bytesDownloaded; + } + + public static long downloadFileWithResume(String downloadUrl, String saveAsFileName) throws IOException, URISyntaxException { + File outputFile = new File(saveAsFileName); + + URLConnection downloadFileConnection = addFileResumeFunctionality(downloadUrl, outputFile); + return transferDataAndGetBytesDownloaded(downloadFileConnection, outputFile); + } + + private static URLConnection addFileResumeFunctionality(String downloadUrl, File outputFile) throws IOException, URISyntaxException, ProtocolException, ProtocolException { + long existingFileSize = 0L; + URLConnection downloadFileConnection = new URI(downloadUrl).toURL() + .openConnection(); + + if (outputFile.exists() && downloadFileConnection instanceof HttpURLConnection) { + HttpURLConnection httpFileConnection = (HttpURLConnection) downloadFileConnection; + + HttpURLConnection tmpFileConn = (HttpURLConnection) new URI(downloadUrl).toURL() + .openConnection(); + tmpFileConn.setRequestMethod("HEAD"); + long fileLength = tmpFileConn.getContentLengthLong(); + existingFileSize = outputFile.length(); + + if (existingFileSize < fileLength) { + httpFileConnection.setRequestProperty("Range", "bytes=" + existingFileSize + "-" + fileLength); + } else { + throw new IOException("File Download already completed."); + } + } + return downloadFileConnection; + } + +} 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/download/FileDownloadIntegrationTest.java b/core-java-io/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java new file mode 100644 index 0000000000..81ac391958 --- /dev/null +++ b/core-java-io/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java @@ -0,0 +1,91 @@ +package com.baeldung.download; + +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.concurrent.ExecutionException; + +import javax.xml.bind.DatatypeConverter; + +import org.junit.After; +import org.junit.BeforeClass; +import org.junit.Test; + +public class FileDownloadIntegrationTest { + + static String FILE_URL = "http://ovh.net/files/1Mio.dat"; + static String FILE_NAME = "file.dat"; + static String FILE_MD5_HASH = "6cb91af4ed4c60c11613b75cd1fc6116"; + + @Test + public void givenJavaIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException { + + FileDownload.downloadWithJavaIO(FILE_URL, FILE_NAME); + assertTrue(checkMd5Hash(FILE_NAME)); + } + + @Test + public void givenJavaNIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException { + + FileDownload.downloadWithJavaNIO(FILE_URL, FILE_NAME); + assertTrue(checkMd5Hash(FILE_NAME)); + } + + @Test + public void givenJava7IO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException { + + FileDownload.downloadWithJava7IO(FILE_URL, FILE_NAME); + assertTrue(checkMd5Hash(FILE_NAME)); + } + + @Test + public void givenAHCLibrary_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException, ExecutionException, InterruptedException { + + FileDownload.downloadWithAHC(FILE_URL, FILE_NAME); + assertTrue(checkMd5Hash(FILE_NAME)); + } + + @Test + public void givenApacheCommonsIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException { + + FileDownload.downloadWithApacheCommons(FILE_URL, FILE_NAME); + assertTrue(checkMd5Hash(FILE_NAME)); + } + + @Test + public void givenJavaIO_whenDownloadingFileStops_thenDownloadShouldBeResumedCorrectly() throws NoSuchAlgorithmException, IOException, URISyntaxException { + + ResumableDownload.downloadFileWithResume(FILE_URL, FILE_NAME); + assertTrue(checkMd5Hash(FILE_NAME)); + } + + private boolean checkMd5Hash(String filename) throws IOException, NoSuchAlgorithmException { + + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(Files.readAllBytes(Paths.get(filename))); + byte[] digest = md.digest(); + String myChecksum = DatatypeConverter.printHexBinary(digest); + + return myChecksum.equalsIgnoreCase(FILE_MD5_HASH); + } + + @BeforeClass + public static void setup() throws IOException { + if (Files.exists(Paths.get(FILE_NAME))) { + Files.delete(Paths.get(FILE_NAME)); + } + } + + @After + public void cleanup() throws IOException { + if (Files.exists(Paths.get(FILE_NAME))) { + Files.delete(Paths.get(FILE_NAME)); + } + } +} 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..8322106c24 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"; diff --git a/core-java/README.md b/core-java/README.md index cc3097006c..9bc7d9f7ee 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -139,5 +139,15 @@ - [Sending Emails with Java](http://www.baeldung.com/java-email) - [Introduction to SSL in Java](http://www.baeldung.com/java-ssl) - [Java KeyStore API](http://www.baeldung.com/java-keystore) -- [Using Java Assertions](http://www.baeldung.com/java-assert) +- [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) +- [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) + + 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/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/extension/Extension.java b/core-java/src/main/java/com/baeldung/extension/Extension.java new file mode 100644 index 0000000000..4045af8b30 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/extension/Extension.java @@ -0,0 +1,23 @@ +package com.baeldung.extension; + +import com.google.common.io.Files; +import org.apache.commons.io.FilenameUtils; + +public class Extension { + //Instead of file name we can also specify full path of a file eg. /baeldung/com/demo/abc.java + public String getExtensionByApacheCommonLib(String filename) { + return FilenameUtils.getExtension(filename); + } + + public String getExtensionByStringHandling(String filename) { + String fileExtension = ""; + if (filename.contains(".") && filename.lastIndexOf(".") != 0) { + fileExtension = filename.substring(filename.lastIndexOf(".") + 1); + } + return fileExtension; + } + + public String getExtensionByGuava(String filename) { + return Files.getFileExtension(filename); + } +} 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/LinkedList.java b/core-java/src/main/java/com/baeldung/linkedlist/LinkedList.java new file mode 100644 index 0000000000..12c73f2489 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/linkedlist/LinkedList.java @@ -0,0 +1,58 @@ +package com.baeldung.linkedlist; + +/** + * Implementation of a singly linked list. + */ +public class LinkedList { + private Node head; + private Node tail; + + public Node head() { + return head; + } + + public void add(String data) { + Node newNode = new Node(data); + + if (head == null) { + head = newNode; + tail = newNode; + } else { + tail.next = newNode; + tail = newNode; + } + } + + public static 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/main/java/com/baeldung/linkedlist/MiddleElementLookup.java b/core-java/src/main/java/com/baeldung/linkedlist/MiddleElementLookup.java new file mode 100644 index 0000000000..27684c93d2 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/linkedlist/MiddleElementLookup.java @@ -0,0 +1,79 @@ +package com.baeldung.linkedlist; + +import com.baeldung.linkedlist.LinkedList.Node; + +public class MiddleElementLookup { + + public static String findMiddleElement(Node head) { + if (head == null) { + return null; + } + + // 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 current.data(); + } + + public static String findMiddleElement1PassRecursively(Node head) { + if (head == null) { + return null; + } + + MiddleAuxRecursion middleAux = new MiddleAuxRecursion(); + findMiddleRecursively(head, middleAux); + return 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 String findMiddleElement1PassIteratively(Node head) { + if (head == null) { + return null; + } + + Node slowPointer = head; + Node fastPointer = head; + + while (fastPointer.hasNext() && fastPointer.next() + .hasNext()) { + fastPointer = fastPointer.next() + .next(); + slowPointer = slowPointer.next(); + } + + return slowPointer.data(); + } + + private static class MiddleAuxRecursion { + Node middle; + int length = 0; + } + +} 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/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/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 new file mode 100644 index 0000000000..d1cfe7df19 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.chararraypassword; + +import org.junit.Test; + +import java.util.Arrays; + +import static org.assertj.core.api.Assertions.assertThat; + +public class PasswordStoreExamplesUnitTest { + + String stringPassword = "password"; + char[] charPassword = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; + + @Test + public void givenStringHashCode_WhenStringValueChanged_ThenHashCodesNotEqualAndValesNotEqual() { + String originalHashCode = Integer.toHexString(stringPassword.hashCode()); + + stringPassword = "********"; + String changedHashCode = Integer.toHexString(stringPassword.hashCode()); + + assertThat(originalHashCode).isNotEqualTo(changedHashCode); + assertThat(stringPassword).isNotEqualTo("password"); + } + + @Test + public void givenStringHashCode_WhenStringValueChangedAndStringValueReassigned_ThenHashCodesEqualAndValesEqual() { + String originalHashCode = Integer.toHexString(stringPassword.hashCode()); + + stringPassword = "********"; + stringPassword = "password"; + String reassignedHashCode = Integer.toHexString(stringPassword.hashCode()); + + assertThat(originalHashCode).isEqualTo(reassignedHashCode); + 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()); + + Arrays.fill(charPassword, '*'); + String changedHashCode = Integer.toHexString(charPassword.hashCode()); + + assertThat(originalHashCode).isEqualTo(changedHashCode); + assertThat(charPassword).isNotEqualTo(new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}); + } + + @Test + public void whenCallingToStringOfString_ThenValuesEqual() { + assertThat(stringPassword.toString()).isEqualTo("password"); + } + + @Test + public void whenCallingToStringOfCharArray_ThenValuesNotEqual() { + assertThat(charPassword.toString()).isNotEqualTo("password"); + } +} 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/ExtensionUnitTest.java b/core-java/src/test/java/com/baeldung/extension/ExtensionUnitTest.java new file mode 100644 index 0000000000..8c6e261c91 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/extension/ExtensionUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.extension; + +import org.junit.Assert; +import org.junit.Test; + +public class ExtensionUnitTest { + private Extension extension = new Extension(); + + @Test + public void getExtension_whenApacheCommonIO_thenExtensionIsTrue() { + String expectedExtension = "txt"; + String actualExtension = extension.getExtensionByApacheCommonLib("jarvis.txt"); + Assert.assertEquals(expectedExtension, actualExtension); + } + + @Test + public void getExtension_whenStringHandle_thenExtensionIsTrue() { + String expectedExtension = "java"; + String actualExtension = extension.getExtensionByStringHandling("Demo.java"); + Assert.assertEquals(expectedExtension, actualExtension); + } + + @Test + public void getExtension_whenGuava_thenExtensionIsTrue() { + String expectedExtension = "class"; + String actualExtension = extension.getExtensionByGuava("baeldung/Demo.class"); + Assert.assertEquals(expectedExtension, actualExtension); + } +} 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..d456259612 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/linkedlist/MiddleElementLookupUnitTest.java @@ -0,0 +1,58 @@ +package com.baeldung.linkedlist; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class MiddleElementLookupUnitTest { + + @Test + public void whenFindingMiddle_thenMiddleFound() { + String middle = MiddleElementLookup.findMiddleElement(createList(5).head()); + assertEquals("3", middle); + + middle = MiddleElementLookup.findMiddleElement(createList(4).head()); + assertEquals("2", middle); + } + + @Test + public void whenFindingMiddle1PassRecursively_thenMiddleFound() { + String middle = MiddleElementLookup.findMiddleElement1PassRecursively(createList(5).head()); + assertEquals("3", middle); + + middle = MiddleElementLookup.findMiddleElement1PassRecursively(createList(4).head()); + assertEquals("2", middle); + } + + @Test + public void whenFindingMiddle1PassIteratively_thenMiddleFound() { + String middle = MiddleElementLookup.findMiddleElement1PassIteratively(createList(5).head()); + assertEquals("3", middle); + + middle = MiddleElementLookup.findMiddleElement1PassIteratively(createList(4).head()); + assertEquals("2", middle); + } + + @Test + public void whenListEmptyOrNull_thenMiddleNull() { + String middle = MiddleElementLookup.findMiddleElement(null); + assertEquals(null, middle); + + middle = MiddleElementLookup.findMiddleElement1PassIteratively(null); + assertEquals(null, middle); + + middle = MiddleElementLookup.findMiddleElement1PassRecursively(null); + assertEquals(null, middle); + } + + private static LinkedList createList(int n) { + LinkedList list = new LinkedList(); + + for (int i = 1; i <= n; i++) { + list.add(String.valueOf(i)); + } + + return list; + } + +} 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/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/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 ce47cc2541..7fcdc68429 100644 --- a/core-kotlin/README.md +++ b/core-kotlin/README.md @@ -26,3 +26,7 @@ - [Reading from a File in Kotlin](http://www.baeldung.com/kotlin-read-file) - [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/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/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/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/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/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/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/javax-servlets/README.md b/javax-servlets/README.md index 84330ac94c..ef8ec168cf 100644 --- a/javax-servlets/README.md +++ b/javax-servlets/README.md @@ -2,3 +2,4 @@ - [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) 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..9a85a69fff --- /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 Double salary; + + public Employee(int id, String name, String department, Double 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 Double getSalary() { + return salary; + } + + public void setSalary(Double 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..ea82ca5055 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/EmployeeServlet.java @@ -0,0 +1,37 @@ +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 { + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws IOException { + + int id = Integer.parseInt(request.getParameter("id")); + String name = request.getParameter("name"); + String department = request.getParameter("department"); + Double salary = Double.parseDouble(request.getParameter("salary")); + + Employee employee = new Employee(id, name, department, salary); + String employeeJsonString = new 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..c96ad0a858 --- /dev/null +++ b/javax-servlets/src/test/java/com/baeldung/servlets/EmployeeServletIntegrationTest.java @@ -0,0 +1,60 @@ +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"; + Double salary = 5000.0; + employee = new Employee(id, name, department, salary); + + //when + when(httpServletRequest.getParameter("id")).thenReturn(String.valueOf(id)); + when(httpServletRequest.getParameter("name")).thenReturn(name); + when(httpServletRequest.getParameter("department")).thenReturn(department); + when(httpServletRequest.getParameter("salary")).thenReturn(String.valueOf(salary)); + + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + when(httpServletResponse.getWriter()).thenReturn(pw); + + EmployeeServlet employeeServlet = new EmployeeServlet(); + employeeServlet.doPost(httpServletRequest, httpServletResponse); + + String employeeJsonString = sw.getBuffer().toString().trim(); + Employee fetchedEmployee = new Gson().fromJson(employeeJsonString, Employee.class); + assertEquals(fetchedEmployee, employee); + } + +} 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/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/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/.gitignore b/kotlin-js/.gitignore new file mode 100644 index 0000000000..1db5e66882 --- /dev/null +++ b/kotlin-js/.gitignore @@ -0,0 +1,13 @@ +/bin/ + +#ignore gradle +.gradle/ + + +#ignore build and generated files +build/ +node/ + +#ignore installed node modules and package lock file +node_modules/ +package-lock.json diff --git a/kotlin-js/build.gradle b/kotlin-js/build.gradle new file mode 100755 index 0000000000..9efef0f475 --- /dev/null +++ b/kotlin-js/build.gradle @@ -0,0 +1,27 @@ +buildscript { + ext.kotlin_version = '1.2.41' + repositories { + mavenCentral() + } + dependencies { + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +group 'com.baeldung' +version '1.0-SNAPSHOT' +apply plugin: 'kotlin2js' + +repositories { + mavenCentral() +} + +dependencies { + compile "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version" + testCompile "org.jetbrains.kotlin:kotlin-test-js:$kotlin_version" +} + +compileKotlin2Js.kotlinOptions { + moduleKind = "commonjs" + outputFile = "node/crypto.js" +} diff --git a/kotlin-js/gradle/wrapper/gradle-wrapper.jar b/kotlin-js/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..01b8bf6b1f Binary files /dev/null and b/kotlin-js/gradle/wrapper/gradle-wrapper.jar differ diff --git a/kotlin-js/gradle/wrapper/gradle-wrapper.properties b/kotlin-js/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..933b6473ce --- /dev/null +++ b/kotlin-js/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip diff --git a/kotlin-js/gradlew b/kotlin-js/gradlew new file mode 100755 index 0000000000..cccdd3d517 --- /dev/null +++ b/kotlin-js/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/kotlin-js/gradlew.bat b/kotlin-js/gradlew.bat new file mode 100755 index 0000000000..e95643d6a2 --- /dev/null +++ b/kotlin-js/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/kotlin-js/package.json b/kotlin-js/package.json new file mode 100755 index 0000000000..c75313e3ff --- /dev/null +++ b/kotlin-js/package.json @@ -0,0 +1,17 @@ +{ + "name": "kotlin-node.js", + "version": "1.0.0", + "description": "Example of using NodeJS in Kotlin", + "main": "crypto.js", + "dependencies": { + "express": "^4.15.2", + "fs": "0.0.1-security", + "kotlin": "^1.1.0", + "node.js": "0.0.0", + "request": "^2.85.0" + }, + "devDependencies": {}, + "scripts": { + "start": "node node/crypto.js" + } +} diff --git a/kotlin-js/settings.gradle b/kotlin-js/settings.gradle new file mode 100755 index 0000000000..64767a30c5 --- /dev/null +++ b/kotlin-js/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'KotlinNode' diff --git a/kotlin-js/src/main/kotlin/com/baeldung/kotlinjs/CryptoRate.kt b/kotlin-js/src/main/kotlin/com/baeldung/kotlinjs/CryptoRate.kt new file mode 100755 index 0000000000..92ef4a7356 --- /dev/null +++ b/kotlin-js/src/main/kotlin/com/baeldung/kotlinjs/CryptoRate.kt @@ -0,0 +1,27 @@ +package com.baeldung.kotlinjs + +external fun require(module: String): dynamic + +data class CryptoCurrency(var name: String, var price: Float) + +fun main(args: Array) { + println("Crypto Currency price API!") + val express = require("express") + val app = express() + + app.get("/crypto", { _, res -> + res.send(generateCryptoRates()) + }) + + app.listen(3000, { + println("Listening on port 3000") + }) +} +fun generateCryptoRates(): Array{ + val cryptoCurrency = arrayOf( + CryptoCurrency("Bitcoin", 90000F), + CryptoCurrency("ETH",1000F), + CryptoCurrency("TRX",10F) + ); + return cryptoCurrency +} \ No newline at end of file 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/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/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..e4404a6528 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,7 +6,7 @@ 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; @@ -14,7 +14,7 @@ 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/lombok/README.md b/lombok/README.md index 4dc1c2d09d..1a787e32c7 100644 --- a/lombok/README.md +++ b/lombok/README.md @@ -1,2 +1,3 @@ ## Relevant Articles: - [Introduction to Project Lombok](http://www.baeldung.com/intro-to-project-lombok) +- [Using Lombok’s @Builder Annotation](http://www.baeldung.com/lombok-builder) 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/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/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-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/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/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/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/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-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/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 bca9f953c1..20efe30281 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,8 @@ parent-boot-5 parent-boot-2 - parent-spring + parent-spring-4 + parent-spring-5 parent-java asm atomix @@ -30,6 +31,7 @@ apache-opennlp autovalue axon + azure bootique cdi @@ -260,6 +262,7 @@ performance-tests twilio spring-boot-ctx-fluent + java-ee-8-security-api @@ -373,7 +376,7 @@ 5 true - false + true true true true 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/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-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..9c317e9966 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 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/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-all/README.md b/spring-all/README.md index 173f410620..215f9a64d2 100644 --- a/spring-all/README.md +++ b/spring-all/README.md @@ -28,3 +28,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [How To Do @Async in Spring](http://www.baeldung.com/spring-async) - [Quick Guide to the Spring @Order Annotation](http://www.baeldung.com/spring-order) - [Spring Web Contexts](http://www.baeldung.com/spring-web-contexts) +- [Spring Cache – Creating a Custom KeyGenerator](http://www.baeldung.com/spring-cache-custom-keygenerator) 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..ecc72c85f5 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -15,25 +15,6 @@ ../parent-boot-2 - - org.springframework.boot 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-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-ops/README.MD b/spring-boot-ops/README.MD new file mode 100644 index 0000000000..5ac223397c --- /dev/null +++ b/spring-boot-ops/README.MD @@ -0,0 +1,13 @@ +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: + +- [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters) +- [A Custom Data Binder in Spring MVC](http://www.baeldung.com/spring-mvc-custom-data-binder) +- [Introduction to WebJars](http://www.baeldung.com/maven-webjars) +- [A Quick Guide to Maven Wrapper](http://www.baeldung.com/maven-wrapper) +- [Shutdown a Spring Boot Application](http://www.baeldung.com/spring-boot-shutdown) +- [Create a Fat Jar App with Spring Boot](http://www.baeldung.com/deployable-fat-jar-spring-boot) +- [Spring Boot Dependency Management with a Custom Parent](http://www.baeldung.com/spring-boot-dependency-management-custom-parent) + diff --git a/spring-boot-ops/README.md b/spring-boot-ops/README.md new file mode 100644 index 0000000000..7de2fed24f --- /dev/null +++ b/spring-boot-ops/README.md @@ -0,0 +1,12 @@ +### The Course +The "REST With Spring" Classes: http://bit.ly/restwithspring + +### Relevant Articles: + +- [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters) +- [A Custom Data Binder in Spring MVC](http://www.baeldung.com/spring-mvc-custom-data-binder) +- [Introduction to WebJars](http://www.baeldung.com/maven-webjars) +- [A Quick Guide to Maven Wrapper](http://www.baeldung.com/maven-wrapper) +- [Shutdown a Spring Boot Application](http://www.baeldung.com/spring-boot-shutdown) +- [Create a Fat Jar App with Spring Boot](http://www.baeldung.com/deployable-fat-jar-spring-boot) +- [Spring Boot Dependency Management with a Custom Parent](http://www.baeldung.com/spring-boot-dependency-management-custom-parent) \ No newline at end of file diff --git a/spring-boot-ops/pom.xml b/spring-boot-ops/pom.xml index 0d0ccc0ef2..b6adb27fb2 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,58 @@ org.springframework.boot spring-boot-maven-plugin
+ + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + org.baeldung.boot.Application + + + +
+ + + 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-ops/src/main/resources/application.properties b/spring-boot-ops/src/main/resources/application.properties deleted file mode 100644 index e69de29bb2..0000000000 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/README.MD b/spring-boot/README.MD index 79f66b4a38..dd3f930126 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,10 @@ 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) 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/README.md b/spring-cloud/README.md index b7a0a5fad7..31d9ffb684 100644 --- a/spring-cloud/README.md +++ b/spring-cloud/README.md @@ -26,3 +26,4 @@ - [Instance Profile Credentials using Spring Cloud](http://www.baeldung.com/spring-cloud-instance-profiles) - [An Intro to Spring Cloud Security](http://www.baeldung.com/spring-cloud-security) - [An Intro to Spring Cloud Task](http://www.baeldung.com/spring-cloud-task) +- [Running Spring Boot Applications With Minikube](http://www.baeldung.com/spring-boot-minikube) 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-core/README.md b/spring-core/README.md index 5f50b35553..cec85534f5 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -14,3 +14,4 @@ - [Injecting Prototype Beans into a Singleton Instance in Spring](http://www.baeldung.com/spring-inject-prototype-bean-into-singleton) - [How to Inject a Property Value Into a Class Not Managed by Spring?](http://www.baeldung.com/inject-properties-value-non-spring-class) - [@Lookup Annotation in Spring](http://www.baeldung.com/spring-lookup) +- [BeanNameAware and BeanFactoryAware Interfaces in Spring](http://www.baeldung.com/spring-bean-name-factory-aware) 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/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/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-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/src/main/java/com/baeldung/spring/data/keyvalue/services/EmployeeService.java b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/EmployeeService.java index dd89609be7..83117b3baa 100644 --- a/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/EmployeeService.java +++ b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/EmployeeService.java @@ -1,12 +1,14 @@ package com.baeldung.spring.data.keyvalue.services; +import java.util.Optional; + import com.baeldung.spring.data.keyvalue.vo.Employee; public interface EmployeeService { void save(Employee employee); - Employee get(Integer id); + Optional get(Integer id); Iterable fetchAll(); diff --git a/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithKeyValueTemplate.java b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithKeyValueTemplate.java index 26f1756add..3eb1d0f66a 100644 --- a/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithKeyValueTemplate.java +++ b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithKeyValueTemplate.java @@ -27,9 +27,8 @@ public class EmployeeServicesWithKeyValueTemplate implements EmployeeService { } @Override - public Employee get(Integer id) { - Optional employee = keyValueTemplate.findById(id, Employee.class); - return employee.isPresent() ? employee.get() : null; + public Optional get(Integer id) { + return keyValueTemplate.findById(id, Employee.class); } @Override diff --git a/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithRepository.java b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithRepository.java index 73f3493a6b..70e00dadc0 100644 --- a/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithRepository.java +++ b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithRepository.java @@ -1,5 +1,7 @@ package com.baeldung.spring.data.keyvalue.services.impl; +import java.util.Optional; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -26,8 +28,8 @@ public class EmployeeServicesWithRepository implements EmployeeService { } @Override - public Employee get(Integer id) { - return employeeRepository.findById(id).get(); + public Optional get(Integer id) { + return employeeRepository.findById(id); } @Override diff --git a/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/vo/Employee.java b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/vo/Employee.java index 208e6e1735..1063c578f3 100644 --- a/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/vo/Employee.java +++ b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/vo/Employee.java @@ -6,7 +6,7 @@ import org.springframework.data.annotation.Id; import org.springframework.data.keyvalue.annotation.KeySpace; @KeySpace("employees") -public class Employee implements Serializable { +public class Employee { @Id private Integer id; diff --git a/spring-data-keyvalue/src/test/java/com/baeldung/spring/data/keyvalue/services/test/EmployeeServicesWithKeyValueRepositoryIntegrationTest.java b/spring-data-keyvalue/src/test/java/com/baeldung/spring/data/keyvalue/services/test/EmployeeServicesWithKeyValueRepositoryIntegrationTest.java index e376f1b804..37b0a69a2d 100644 --- a/spring-data-keyvalue/src/test/java/com/baeldung/spring/data/keyvalue/services/test/EmployeeServicesWithKeyValueRepositoryIntegrationTest.java +++ b/spring-data-keyvalue/src/test/java/com/baeldung/spring/data/keyvalue/services/test/EmployeeServicesWithKeyValueRepositoryIntegrationTest.java @@ -50,7 +50,7 @@ public class EmployeeServicesWithKeyValueRepositoryIntegrationTest { @Test public void test2_whenEmployeeGet_thenEmployeeIsReturnedFromMap() { - Employee employeeFetched = employeeService.get(1); + Employee employeeFetched = employeeService.get(1).get(); assertEquals(employeeFetched, employee1); } diff --git a/spring-data-keyvalue/src/test/java/com/baeldung/spring/data/keyvalue/services/test/EmployeeServicesWithRepositoryIntegrationTest.java b/spring-data-keyvalue/src/test/java/com/baeldung/spring/data/keyvalue/services/test/EmployeeServicesWithRepositoryIntegrationTest.java index bb034d6aee..d0ed1506f8 100644 --- a/spring-data-keyvalue/src/test/java/com/baeldung/spring/data/keyvalue/services/test/EmployeeServicesWithRepositoryIntegrationTest.java +++ b/spring-data-keyvalue/src/test/java/com/baeldung/spring/data/keyvalue/services/test/EmployeeServicesWithRepositoryIntegrationTest.java @@ -46,7 +46,7 @@ public class EmployeeServicesWithRepositoryIntegrationTest { @Test public void test2_whenEmployeeGet_thenEmployeeIsReturnedFromMap() { - Employee employeeFetched = employeeService.get(1); + Employee employeeFetched = employeeService.get(1).get(); assertEquals(employeeFetched, employee1); } 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-rest/README.md b/spring-data-rest/README.md index fa4a264abb..445557d10b 100644 --- a/spring-data-rest/README.md +++ b/spring-data-rest/README.md @@ -1,4 +1,4 @@ -###The Course +### The Course The "REST With Spring" Classes: http://bit.ly/restwithspring # About this project @@ -13,8 +13,9 @@ The application uses [Spring Boot](http://projects.spring.io/spring-boot/), so i # Viewing the running application To view the running application, visit [http://localhost:8080](http://localhost:8080) in your browser -###Relevant Articles: +### Relevant Articles: - [Guide to Spring Data REST Validators](http://www.baeldung.com/spring-data-rest-validators) - [Working with Relationships in Spring Data REST](http://www.baeldung.com/spring-data-rest-relationships) - [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) diff --git a/spring-data-rest/src/main/java/com/baeldung/config/MvcConfig.java b/spring-data-rest/src/main/java/com/baeldung/config/MvcConfig.java index bed1a6f846..82cb936348 100644 --- a/spring-data-rest/src/main/java/com/baeldung/config/MvcConfig.java +++ b/spring-data-rest/src/main/java/com/baeldung/config/MvcConfig.java @@ -1,5 +1,7 @@ package com.baeldung.config; +import com.baeldung.events.AuthorEventHandler; +import com.baeldung.events.BookEventHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @@ -22,4 +24,14 @@ public class MvcConfig extends WebMvcConfigurerAdapter{ configurer.enable(); } + @Bean + AuthorEventHandler authorEventHandler() { + return new AuthorEventHandler(); + } + + @Bean + BookEventHandler bookEventHandler(){ + return new BookEventHandler(); + } + } diff --git a/spring-data-rest/src/main/java/com/baeldung/events/AuthorEventHandler.java b/spring-data-rest/src/main/java/com/baeldung/events/AuthorEventHandler.java new file mode 100644 index 0000000000..5a8ae05c08 --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/events/AuthorEventHandler.java @@ -0,0 +1,40 @@ +package com.baeldung.events; + +import com.baeldung.models.Author; +import com.baeldung.models.Book; +import org.springframework.data.rest.core.annotation.*; + +import java.util.logging.Logger; + +@RepositoryEventHandler +public class AuthorEventHandler { + Logger logger = Logger.getLogger("Class AuthorEventHandler"); + public AuthorEventHandler(){ + super(); + } + + @HandleBeforeCreate + public void handleAuthorBeforeCreate(Author author){ + logger.info("Inside Author Before Create...."); + String name = author.getName(); + } + + @HandleAfterCreate + public void handleAuthorAfterCreate(Author author){ + logger.info("Inside Author After Create ...."); + String name = author.getName(); + } + + @HandleBeforeDelete + public void handleAuthorBeforeDelete(Author author){ + logger.info("Inside Author Before Delete ...."); + String name = author.getName(); + } + + @HandleAfterDelete + public void handleAuthorAfterDelete(Author author){ + logger.info("Inside Author After Delete ...."); + String name = author.getName(); + } + +} diff --git a/spring-data-rest/src/main/java/com/baeldung/events/BookEventHandler.java b/spring-data-rest/src/main/java/com/baeldung/events/BookEventHandler.java new file mode 100644 index 0000000000..3953e6ce0d --- /dev/null +++ b/spring-data-rest/src/main/java/com/baeldung/events/BookEventHandler.java @@ -0,0 +1,26 @@ +package com.baeldung.events; + +import java.util.logging.Logger; +import com.baeldung.models.Author; +import com.baeldung.models.Book; +import org.apache.commons.logging.Log; +import org.springframework.data.rest.core.annotation.HandleAfterDelete; +import org.springframework.data.rest.core.annotation.HandleBeforeCreate; +import org.springframework.data.rest.core.annotation.RepositoryEventHandler; + +@RepositoryEventHandler +public class BookEventHandler { + Logger logger = Logger.getLogger("Class BookEventHandler"); + @HandleBeforeCreate + public void handleBookBeforeCreate(Book book){ + + logger.info("Inside Book Before Create ...."); + book.getAuthors(); + } + + @HandleBeforeCreate + public void handleAuthorBeforeCreate(Author author){ + logger.info("Inside Author Before Create ...."); + author.getBooks(); + } +} diff --git a/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerTest.java b/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerTest.java new file mode 100644 index 0000000000..9fb2d1014e --- /dev/null +++ b/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerTest.java @@ -0,0 +1,29 @@ +package com.baeldung.events; + +import com.baeldung.models.Author; +import org.junit.Test; +import org.mockito.Mockito; +import org.springframework.data.rest.core.annotation.RepositoryEventHandler; + +import static org.mockito.Mockito.mock; + +public class AuthorEventHandlerTest { + + @Test + public void whenCreateAuthorThenSuccess() { + Author author = mock(Author.class); + AuthorEventHandler authorEventHandler = new AuthorEventHandler(); + authorEventHandler.handleAuthorBeforeCreate(author); + Mockito.verify(author,Mockito.times(1)).getName(); + + } + + @Test + public void whenDeleteAuthorThenSuccess() { + Author author = mock(Author.class); + AuthorEventHandler authorEventHandler = new AuthorEventHandler(); + authorEventHandler.handleAuthorAfterDelete(author); + Mockito.verify(author,Mockito.times(1)).getName(); + + } +} diff --git a/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerTest.java b/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerTest.java new file mode 100644 index 0000000000..85699adb0d --- /dev/null +++ b/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerTest.java @@ -0,0 +1,28 @@ +package com.baeldung.events; + +import com.baeldung.models.Author; +import com.baeldung.models.Book; +import org.junit.Test; +import org.mockito.Mockito; + +import static org.mockito.Mockito.mock; + +public class BookEventHandlerTest { + @Test + public void whenCreateBookThenSuccess() { + Book book = mock(Book.class); + BookEventHandler bookEventHandler = new BookEventHandler(); + bookEventHandler.handleBookBeforeCreate(book); + Mockito.verify(book,Mockito.times(1)).getAuthors(); + + } + + @Test + public void whenCreateAuthorThenSuccess() { + Author author = mock(Author.class); + BookEventHandler bookEventHandler = new BookEventHandler(); + bookEventHandler.handleAuthorBeforeCreate(author); + Mockito.verify(author,Mockito.times(1)).getBooks(); + + } +} 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-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-mvc-java/README.md b/spring-mvc-java/README.md index 5f62f71211..1fd416d19f 100644 --- a/spring-mvc-java/README.md +++ b/spring-mvc-java/README.md @@ -2,7 +2,7 @@ ## Spring MVC with Java Configuration Example Project -###The Course +### The Course The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: @@ -26,4 +26,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [The HttpMediaTypeNotAcceptableException in Spring MVC](http://www.baeldung.com/spring-httpmediatypenotacceptable) - [Spring MVC and the @ModelAttribute Annotation](http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation) - [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) \ No newline at end of file +- [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) 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-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/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-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 83cb450564..c1183b500a 100644 --- a/spring-rest/README.md +++ b/spring-rest/README.md @@ -1,6 +1,6 @@ ## Spring REST Example Project -###The Course +### The Course The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: @@ -18,3 +18,8 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring – Log Incoming Requests](http://www.baeldung.com/spring-http-logging) - [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) + 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-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-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/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-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/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/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..c20731cfe6 --- /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 " + type + " In beforeAll : " + extensionContext.getDisplayName()); + } + + @Override + public void beforeEach(ExtensionContext extensionContext) throws Exception { + logger.info("Type " + type + " In beforeEach : " + 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/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/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/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/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)