diff --git a/.gitignore b/.gitignore index 51f3d69d9f..e78c1e7e24 100644 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,9 @@ spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties *.springBeans 20171220-JMeter.csv + +.factorypath +dependency-reduced-pom.xml +*.so +*.dylib +*.dll diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java index 8b47fa0fdf..5ca2d626f1 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tictactoe/Board.java @@ -148,7 +148,7 @@ public class Board { System.out.println("Game Draw"); break; case IN_PROGRESS: - System.out.println("Game In rogress"); + System.out.println("Game In Progress"); break; } } diff --git a/algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/MiddleElementLookup.java b/algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/MiddleElementLookup.java new file mode 100644 index 0000000000..7e25e0456b --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/MiddleElementLookup.java @@ -0,0 +1,88 @@ +package com.baeldung.algorithms.middleelementlookup; + +import java.util.LinkedList; +import java.util.Optional; + +public class MiddleElementLookup { + + public static Optional findMiddleElementLinkedList(LinkedList linkedList) { + if (linkedList == null || linkedList.isEmpty()) { + return Optional.empty(); + } + + return Optional.ofNullable(linkedList.get((linkedList.size() - 1) / 2)); + } + + public static Optional findMiddleElementFromHead(Node head) { + if (head == null) { + return Optional.empty(); + } + + // calculate the size of the list + Node current = head; + int size = 1; + while (current.hasNext()) { + current = current.next(); + size++; + } + + // iterate till the middle element + current = head; + for (int i = 0; i < (size - 1) / 2; i++) { + current = current.next(); + } + + return Optional.ofNullable(current.data()); + } + + public static Optional findMiddleElementFromHead1PassRecursively(Node head) { + if (head == null) { + return Optional.empty(); + } + + MiddleAuxRecursion middleAux = new MiddleAuxRecursion(); + findMiddleRecursively(head, middleAux); + return Optional.ofNullable(middleAux.middle.data()); + } + + private static void findMiddleRecursively(Node node, MiddleAuxRecursion middleAux) { + if (node == null) { + // reached the end + middleAux.length = middleAux.length / 2; + return; + } + middleAux.length++; + findMiddleRecursively(node.next(), middleAux); + + if (middleAux.length == 0) { + // found the middle + middleAux.middle = node; + } + + middleAux.length--; + } + + public static Optional findMiddleElementFromHead1PassIteratively(Node head) { + if (head == null) { + return Optional.empty(); + } + + Node slowPointer = head; + Node fastPointer = head; + + while (fastPointer.hasNext() && fastPointer.next() + .hasNext()) { + fastPointer = fastPointer.next() + .next(); + slowPointer = slowPointer.next(); + } + + return Optional.ofNullable(slowPointer.data()); + } + + private static class MiddleAuxRecursion { + Node middle; + int length = 0; + } + +} diff --git a/algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/Node.java b/algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/Node.java new file mode 100644 index 0000000000..2a594937e3 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/middleelementlookup/Node.java @@ -0,0 +1,34 @@ +package com.baeldung.algorithms.middleelementlookup; + +public class Node { + private Node next; + private String data; + + public Node(String data) { + this.data = data; + } + + public String data() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public boolean hasNext() { + return next != null; + } + + public Node next() { + return next; + } + + public void setNext(Node next) { + this.next = next; + } + + public String toString() { + return this.data; + } +} diff --git a/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/MiddleElementLookupUnitTest.java b/algorithms/src/test/java/algorithms/MiddleElementLookupUnitTest.java new file mode 100644 index 0000000000..01f9ca2f76 --- /dev/null +++ b/algorithms/src/test/java/algorithms/MiddleElementLookupUnitTest.java @@ -0,0 +1,118 @@ +package algorithms; + +import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup; +import com.baeldung.algorithms.middleelementlookup.Node; +import org.junit.Test; + +import java.util.LinkedList; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +public class MiddleElementLookupUnitTest { + + @Test + public void whenFindingMiddleLinkedList_thenMiddleFound() { + assertEquals("3", MiddleElementLookup + .findMiddleElementLinkedList(createLinkedList(5)) + .get()); + assertEquals("2", MiddleElementLookup + .findMiddleElementLinkedList(createLinkedList(4)) + .get()); + } + + @Test + public void whenFindingMiddleFromHead_thenMiddleFound() { + assertEquals("3", MiddleElementLookup + .findMiddleElementFromHead(createNodesList(5)) + .get()); + assertEquals("2", MiddleElementLookup + .findMiddleElementFromHead(createNodesList(4)) + .get()); + } + + @Test + public void whenFindingMiddleFromHead1PassRecursively_thenMiddleFound() { + assertEquals("3", MiddleElementLookup + .findMiddleElementFromHead1PassRecursively(createNodesList(5)) + .get()); + assertEquals("2", MiddleElementLookup + .findMiddleElementFromHead1PassRecursively(createNodesList(4)) + .get()); + } + + @Test + public void whenFindingMiddleFromHead1PassIteratively_thenMiddleFound() { + assertEquals("3", MiddleElementLookup + .findMiddleElementFromHead1PassIteratively(createNodesList(5)) + .get()); + assertEquals("2", MiddleElementLookup + .findMiddleElementFromHead1PassIteratively(createNodesList(4)) + .get()); + } + + @Test + public void whenListEmptyOrNull_thenMiddleNotFound() { + // null list + assertFalse(MiddleElementLookup + .findMiddleElementLinkedList(null) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead(null) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead1PassIteratively(null) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead1PassRecursively(null) + .isPresent()); + + // empty LinkedList + assertFalse(MiddleElementLookup + .findMiddleElementLinkedList(new LinkedList<>()) + .isPresent()); + + // LinkedList with nulls + LinkedList nullsList = new LinkedList<>(); + nullsList.add(null); + nullsList.add(null); + assertFalse(MiddleElementLookup + .findMiddleElementLinkedList(nullsList) + .isPresent()); + + // nodes with null values + assertFalse(MiddleElementLookup + .findMiddleElementFromHead(new Node(null)) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead1PassIteratively(new Node(null)) + .isPresent()); + assertFalse(MiddleElementLookup + .findMiddleElementFromHead1PassRecursively(new Node(null)) + .isPresent()); + } + + private static LinkedList createLinkedList(int n) { + LinkedList list = new LinkedList<>(); + + for (int i = 1; i <= n; i++) { + list.add(String.valueOf(i)); + } + + return list; + } + + private static Node createNodesList(int n) { + Node head = new Node("1"); + Node current = head; + + for (int i = 2; i <= n; i++) { + Node newNode = new Node(String.valueOf(i)); + current.setNext(newNode); + current = newNode; + } + + return head; + } + +} diff --git a/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/analysis/AnalysisRunnerLiveTest.java b/algorithms/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java new file mode 100644 index 0000000000..1e9188f726 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java @@ -0,0 +1,139 @@ +package com.baeldung.algorithms.analysis; + +import org.junit.Test; + +public class AnalysisRunnerLiveTest { + + int n = 10; + int total = 0; + + @Test + public void whenConstantComplexity_thenConstantRuntime() { + + System.out.println("**** n = " + n + " ****"); + System.out.println(); + + // Constant Time + System.out.println("**** Constant time ****"); + + System.out.println("Hey - your input is: " + n); + System.out.println("Running time not dependent on input size!"); + System.out.println(); + } + + @Test + public void whenLogarithmicComplexity_thenLogarithmicRuntime() { + // Logarithmic Time + System.out.println("**** Logarithmic Time ****"); + for (int i = 1; i < n; i = i * 2) { + // System.out.println("Hey - I'm busy looking at: " + i); + total++; + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenLinearComplexity_thenLinearRuntime() { + // Linear Time + System.out.println("**** Linear Time ****"); + for (int i = 0; i < n; i++) { + // System.out.println("Hey - I'm busy looking at: " + i); + total++; + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + + } + + @Test + public void whenNLogNComplexity_thenNLogNRuntime() { + // N Log N Time + System.out.println("**** nlogn Time ****"); + total = 0; + for ( + + int i = 1; i <= n; i++) { + for (int j = 1; j < n; j = j * 2) { + // System.out.println("Hey - I'm busy looking at: " + i + " and " + j); + total++; + } + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenQuadraticComplexity_thenQuadraticRuntime() { + // Quadratic Time + System.out.println("**** Quadratic Time ****"); + total = 0; + for ( + + int i = 1; i <= n; i++) { + for (int j = 1; j <= n; j++) { + // System.out.println("Hey - I'm busy looking at: " + i + " and " + j); + total++; + } + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenCubicComplexity_thenCubicRuntime() { + // Cubic Time + System.out.println("**** Cubic Time ****"); + total = 0; + for ( + + int i = 1; i <= n; i++) { + for (int j = 1; j <= n; j++) { + for (int k = 1; k <= n; k++) { + // System.out.println("Hey - I'm busy looking at: " + i + " and " + j + " and " + k); + total++; + } + } + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenExponentialComplexity_thenExponentialRuntime() { + // Exponential Time + System.out.println("**** Exponential Time ****"); + total = 0; + for ( + + int i = 1; i <= Math.pow(2, n); i++) { + // System.out.println("Hey - I'm busy looking at: " + i); + total++; + } + System.out.println("Total amount of times run: " + total); + System.out.println(); + } + + @Test + public void whenFactorialComplexity_thenFactorialRuntime() { + // Factorial Time + System.out.println("**** Factorial Time ****"); + total = 0; + for ( + + int i = 1; i <= + + factorial(n); i++) { + // System.out.println("Hey - I'm busy looking at: " + i); + total++; + } + System.out.println("Total amount of times run: " + total); + } + + static int factorial(int n) { + if (n == 0 || n == 1) + return 1; + else + return n * factorial(n - 1); + } +} 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 93% rename from algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java index 7774eb3e67..c7f3f7dc38 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java @@ -4,7 +4,7 @@ import static org.junit.Assert.*; import org.junit.Test; -public class BubbleSortTest { +public class BubbleSortUnitTest { @Test public void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() { diff --git a/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceTest.java b/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java similarity index 80% rename from algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java index bab2f480a5..0df4715b80 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java @@ -7,13 +7,13 @@ import org.junit.runners.Parameterized; import static org.junit.Assert.assertEquals; @RunWith(Parameterized.class) -public class EditDistanceTest extends EditDistanceDataProvider { +public class EditDistanceUnitTest extends EditDistanceDataProvider { private String x; private String y; private int result; - public EditDistanceTest(String a, String b, int res) { + public EditDistanceUnitTest(String a, String b, int res) { super(); x = a; y = b; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java similarity index 72% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java index 7f9b8acdbd..af2430ec55 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java @@ -6,11 +6,11 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class CycleDetectionBruteForceTest extends CycleDetectionTestBase { +public class CycleDetectionBruteForceUnitTest extends CycleDetectionTestBase { boolean cycleExists; Node head; - public CycleDetectionBruteForceTest(Node head, boolean cycleExists) { + public CycleDetectionBruteForceUnitTest(Node head, boolean cycleExists) { super(); this.cycleExists = cycleExists; this.head = head; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java similarity index 70% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java index 17d339bc33..ce31c84067 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java @@ -6,11 +6,11 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class CycleDetectionByFastAndSlowIteratorsTest extends CycleDetectionTestBase { +public class CycleDetectionByFastAndSlowIteratorsUnitTest extends CycleDetectionTestBase { boolean cycleExists; Node head; - public CycleDetectionByFastAndSlowIteratorsTest(Node head, boolean cycleExists) { + public CycleDetectionByFastAndSlowIteratorsUnitTest(Node head, boolean cycleExists) { super(); this.cycleExists = cycleExists; this.head = head; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java similarity index 72% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java index 73a2cc7861..4451c3d3c9 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java @@ -6,11 +6,11 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class CycleDetectionByHashingTest extends CycleDetectionTestBase { +public class CycleDetectionByHashingUnitTest extends CycleDetectionTestBase { boolean cycleExists; Node head; - public CycleDetectionByHashingTest(Node head, boolean cycleExists) { + public CycleDetectionByHashingUnitTest(Node head, boolean cycleExists) { super(); this.cycleExists = cycleExists; this.head = head; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java similarity index 76% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java index 6484c9988e..f69e3c35ba 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java @@ -6,11 +6,11 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class CycleRemovalBruteForceTest extends CycleDetectionTestBase { +public class CycleRemovalBruteForceUnitTest extends CycleDetectionTestBase { boolean cycleExists; Node head; - public CycleRemovalBruteForceTest(Node head, boolean cycleExists) { + public CycleRemovalBruteForceUnitTest(Node head, boolean cycleExists) { super(); this.cycleExists = cycleExists; this.head = head; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java similarity index 75% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java index 7bfd89c502..c17aa6eeab 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java @@ -6,11 +6,11 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class CycleRemovalByCountingLoopNodesTest extends CycleDetectionTestBase { +public class CycleRemovalByCountingLoopNodesUnitTest extends CycleDetectionTestBase { boolean cycleExists; Node head; - public CycleRemovalByCountingLoopNodesTest(Node head, boolean cycleExists) { + public CycleRemovalByCountingLoopNodesUnitTest(Node head, boolean cycleExists) { super(); this.cycleExists = cycleExists; this.head = head; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java similarity index 74% rename from algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java index c77efb3e3e..06ff840a59 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java @@ -6,11 +6,11 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) -public class CycleRemovalWithoutCountingLoopNodesTest extends CycleDetectionTestBase { +public class CycleRemovalWithoutCountingLoopNodesUnitTest extends CycleDetectionTestBase { boolean cycleExists; Node head; - public CycleRemovalWithoutCountingLoopNodesTest(Node head, boolean cycleExists) { + public CycleRemovalWithoutCountingLoopNodesUnitTest(Node head, boolean cycleExists) { super(); this.cycleExists = cycleExists; this.head = head; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterTest.java b/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java similarity index 98% rename from algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java index a4a169f158..26643e9c1e 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import com.baeldung.algorithms.numberwordconverter.NumberWordConverter; -public class NumberWordConverterTest { +public class NumberWordConverterUnitTest { @Test public void whenMoneyNegative_thenReturnInvalidInput() { diff --git a/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java b/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorUnitTest.java similarity index 93% rename from algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorUnitTest.java index 4995e938b7..ffa1404eac 100644 --- a/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/prime/PrimeGeneratorUnitTest.java @@ -7,7 +7,7 @@ import java.util.List; import org.junit.Test; import static org.junit.Assert.*; -public class PrimeGeneratorTest { +public class PrimeGeneratorUnitTest { @Test public void whenBruteForced_returnsSuccessfully() { final List primeNumbers = primeNumbersBruteForce(20); diff --git a/algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java b/algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java similarity index 97% rename from algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java rename to algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java index c085d54689..0b0d6ae822 100644 --- a/algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphTest.java +++ b/algorithms/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java @@ -12,7 +12,7 @@ import org.jgrapht.graph.SimpleWeightedGraph; import org.junit.Before; import org.junit.Test; -public class CompleteGraphTest { +public class CompleteGraphUnitTest { static SimpleWeightedGraph completeGraph; static int size = 10; diff --git a/algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java b/algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java similarity index 99% rename from algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java rename to algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java index 7f4cc99715..3aebaf49a2 100644 --- a/algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphTests.java +++ b/algorithms/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java @@ -24,7 +24,7 @@ import org.jgrapht.traverse.DepthFirstIterator; import org.junit.Before; import org.junit.Test; -public class DirectedGraphTests { +public class DirectedGraphUnitTest { DirectedGraph directedGraph; @Before diff --git a/algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java b/algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java similarity index 97% rename from algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java rename to algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java index 6f0fb92ab7..8cf1b70898 100644 --- a/algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitTest.java +++ b/algorithms/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java @@ -12,7 +12,7 @@ import org.jgrapht.graph.SimpleWeightedGraph; import org.junit.Before; import org.junit.Test; -public class EulerianCircuitTest { +public class EulerianCircuitUnitTest { SimpleWeightedGraph simpleGraph; @Before diff --git a/animal-sniffer-mvn-plugin/pom.xml b/animal-sniffer-mvn-plugin/pom.xml index ab7b38f6e0..9ccc7354af 100644 --- a/animal-sniffer-mvn-plugin/pom.xml +++ b/animal-sniffer-mvn-plugin/pom.xml @@ -5,7 +5,7 @@ animal-sniffer-mvn-plugin jar 1.0-SNAPSHOT - example-animal-sniffer-mvn-plugin + animal-sniffer-mvn-plugin http://maven.apache.org diff --git a/antlr/pom.xml b/antlr/pom.xml new file mode 100644 index 0000000000..15fe79afca --- /dev/null +++ b/antlr/pom.xml @@ -0,0 +1,66 @@ + + 4.0.0 + antlr + antlr + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + org.antlr + antlr4-maven-plugin + ${antlr.version} + + + + antlr4 + + + + + + org.codehaus.mojo + build-helper-maven-plugin + ${mojo.version} + + + generate-sources + + add-source + + + + ${basedir}/target/generated-sources/antlr4 + + + + + + + + + + org.antlr + antlr4-runtime + ${antlr.version} + + + junit + junit + ${junit.version} + test + + + + 1.8 + 4.7.1 + 4.12 + 3.0.0 + + \ No newline at end of file diff --git a/antlr/src/main/antlr4/com/baeldung/antlr/Java8.g4 b/antlr/src/main/antlr4/com/baeldung/antlr/Java8.g4 new file mode 100644 index 0000000000..5cde8f9ace --- /dev/null +++ b/antlr/src/main/antlr4/com/baeldung/antlr/Java8.g4 @@ -0,0 +1,1775 @@ +/* + * [The "BSD license"] + * Copyright (c) 2014 Terence Parr + * Copyright (c) 2014 Sam Harwell + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * A Java 8 grammar for ANTLR 4 derived from the Java Language Specification + * chapter 19. + * + * NOTE: This grammar results in a generated parser that is much slower + * than the Java 7 grammar in the grammars-v4/java directory. This + * one is, however, extremely close to the spec. + * + * You can test with + * + * $ antlr4 Java8.g4 + * $ javac *.java + * $ grun Java8 compilationUnit *.java + * + * Or, +~/antlr/code/grammars-v4/java8 $ java Test . +/Users/parrt/antlr/code/grammars-v4/java8/./Java8BaseListener.java +/Users/parrt/antlr/code/grammars-v4/java8/./Java8Lexer.java +/Users/parrt/antlr/code/grammars-v4/java8/./Java8Listener.java +/Users/parrt/antlr/code/grammars-v4/java8/./Java8Parser.java +/Users/parrt/antlr/code/grammars-v4/java8/./Test.java +Total lexer+parser dateTime 30844ms. + */ +grammar Java8; + +/* + * Productions from §3 (Lexical Structure) + */ + +literal + : IntegerLiteral + | FloatingPointLiteral + | BooleanLiteral + | CharacterLiteral + | StringLiteral + | NullLiteral + ; + +/* + * Productions from §4 (Types, Values, and Variables) + */ + +primitiveType + : annotation* numericType + | annotation* 'boolean' + ; + +numericType + : integralType + | floatingPointType + ; + +integralType + : 'byte' + | 'short' + | 'int' + | 'long' + | 'char' + ; + +floatingPointType + : 'float' + | 'double' + ; + +referenceType + : classOrInterfaceType + | typeVariable + | arrayType + ; + +classOrInterfaceType + : ( classType_lfno_classOrInterfaceType + | interfaceType_lfno_classOrInterfaceType + ) + ( classType_lf_classOrInterfaceType + | interfaceType_lf_classOrInterfaceType + )* + ; + +classType + : annotation* Identifier typeArguments? + | classOrInterfaceType '.' annotation* Identifier typeArguments? + ; + +classType_lf_classOrInterfaceType + : '.' annotation* Identifier typeArguments? + ; + +classType_lfno_classOrInterfaceType + : annotation* Identifier typeArguments? + ; + +interfaceType + : classType + ; + +interfaceType_lf_classOrInterfaceType + : classType_lf_classOrInterfaceType + ; + +interfaceType_lfno_classOrInterfaceType + : classType_lfno_classOrInterfaceType + ; + +typeVariable + : annotation* Identifier + ; + +arrayType + : primitiveType dims + | classOrInterfaceType dims + | typeVariable dims + ; + +dims + : annotation* '[' ']' (annotation* '[' ']')* + ; + +typeParameter + : typeParameterModifier* Identifier typeBound? + ; + +typeParameterModifier + : annotation + ; + +typeBound + : 'extends' typeVariable + | 'extends' classOrInterfaceType additionalBound* + ; + +additionalBound + : '&' interfaceType + ; + +typeArguments + : '<' typeArgumentList '>' + ; + +typeArgumentList + : typeArgument (',' typeArgument)* + ; + +typeArgument + : referenceType + | wildcard + ; + +wildcard + : annotation* '?' wildcardBounds? + ; + +wildcardBounds + : 'extends' referenceType + | 'super' referenceType + ; + +/* + * Productions from §6 (Names) + */ + +packageName + : Identifier + | packageName '.' Identifier + ; + +typeName + : Identifier + | packageOrTypeName '.' Identifier + ; + +packageOrTypeName + : Identifier + | packageOrTypeName '.' Identifier + ; + +expressionName + : Identifier + | ambiguousName '.' Identifier + ; + +methodName + : Identifier + ; + +ambiguousName + : Identifier + | ambiguousName '.' Identifier + ; + +/* + * Productions from §7 (Packages) + */ + +compilationUnit + : packageDeclaration? importDeclaration* typeDeclaration* EOF + ; + +packageDeclaration + : packageModifier* 'package' packageName ';' + ; + +packageModifier + : annotation + ; + +importDeclaration + : singleTypeImportDeclaration + | typeImportOnDemandDeclaration + | singleStaticImportDeclaration + | staticImportOnDemandDeclaration + ; + +singleTypeImportDeclaration + : 'import' typeName ';' + ; + +typeImportOnDemandDeclaration + : 'import' packageOrTypeName '.' '*' ';' + ; + +singleStaticImportDeclaration + : 'import' 'static' typeName '.' Identifier ';' + ; + +staticImportOnDemandDeclaration + : 'import' 'static' typeName '.' '*' ';' + ; + +typeDeclaration + : classDeclaration + | interfaceDeclaration + | ';' + ; + +/* + * Productions from §8 (Classes) + */ + +classDeclaration + : normalClassDeclaration + | enumDeclaration + ; + +normalClassDeclaration + : classModifier* 'class' Identifier typeParameters? superclass? superinterfaces? classBody + ; + +classModifier + : annotation + | 'public' + | 'protected' + | 'private' + | 'abstract' + | 'static' + | 'final' + | 'strictfp' + ; + +typeParameters + : '<' typeParameterList '>' + ; + +typeParameterList + : typeParameter (',' typeParameter)* + ; + +superclass + : 'extends' classType + ; + +superinterfaces + : 'implements' interfaceTypeList + ; + +interfaceTypeList + : interfaceType (',' interfaceType)* + ; + +classBody + : '{' classBodyDeclaration* '}' + ; + +classBodyDeclaration + : classMemberDeclaration + | instanceInitializer + | staticInitializer + | constructorDeclaration + ; + +classMemberDeclaration + : fieldDeclaration + | methodDeclaration + | classDeclaration + | interfaceDeclaration + | ';' + ; + +fieldDeclaration + : fieldModifier* unannType variableDeclaratorList ';' + ; + +fieldModifier + : annotation + | 'public' + | 'protected' + | 'private' + | 'static' + | 'final' + | 'transient' + | 'volatile' + ; + +variableDeclaratorList + : variableDeclarator (',' variableDeclarator)* + ; + +variableDeclarator + : variableDeclaratorId ('=' variableInitializer)? + ; + +variableDeclaratorId + : Identifier dims? + ; + +variableInitializer + : expression + | arrayInitializer + ; + +unannType + : unannPrimitiveType + | unannReferenceType + ; + +unannPrimitiveType + : numericType + | 'boolean' + ; + +unannReferenceType + : unannClassOrInterfaceType + | unannTypeVariable + | unannArrayType + ; + +unannClassOrInterfaceType + : ( unannClassType_lfno_unannClassOrInterfaceType + | unannInterfaceType_lfno_unannClassOrInterfaceType + ) + ( unannClassType_lf_unannClassOrInterfaceType + | unannInterfaceType_lf_unannClassOrInterfaceType + )* + ; + +unannClassType + : Identifier typeArguments? + | unannClassOrInterfaceType '.' annotation* Identifier typeArguments? + ; + +unannClassType_lf_unannClassOrInterfaceType + : '.' annotation* Identifier typeArguments? + ; + +unannClassType_lfno_unannClassOrInterfaceType + : Identifier typeArguments? + ; + +unannInterfaceType + : unannClassType + ; + +unannInterfaceType_lf_unannClassOrInterfaceType + : unannClassType_lf_unannClassOrInterfaceType + ; + +unannInterfaceType_lfno_unannClassOrInterfaceType + : unannClassType_lfno_unannClassOrInterfaceType + ; + +unannTypeVariable + : Identifier + ; + +unannArrayType + : unannPrimitiveType dims + | unannClassOrInterfaceType dims + | unannTypeVariable dims + ; + +methodDeclaration + : methodModifier* methodHeader methodBody + ; + +methodModifier + : annotation + | 'public' + | 'protected' + | 'private' + | 'abstract' + | 'static' + | 'final' + | 'synchronized' + | 'native' + | 'strictfp' + ; + +methodHeader + : result methodDeclarator throws_? + | typeParameters annotation* result methodDeclarator throws_? + ; + +result + : unannType + | 'void' + ; + +methodDeclarator + : Identifier '(' formalParameterList? ')' dims? + ; + +formalParameterList + : receiverParameter + | formalParameters ',' lastFormalParameter + | lastFormalParameter + ; + +formalParameters + : formalParameter (',' formalParameter)* + | receiverParameter (',' formalParameter)* + ; + +formalParameter + : variableModifier* unannType variableDeclaratorId + ; + +variableModifier + : annotation + | 'final' + ; + +lastFormalParameter + : variableModifier* unannType annotation* '...' variableDeclaratorId + | formalParameter + ; + +receiverParameter + : annotation* unannType (Identifier '.')? 'this' + ; + +throws_ + : 'throws' exceptionTypeList + ; + +exceptionTypeList + : exceptionType (',' exceptionType)* + ; + +exceptionType + : classType + | typeVariable + ; + +methodBody + : block + | ';' + ; + +instanceInitializer + : block + ; + +staticInitializer + : 'static' block + ; + +constructorDeclaration + : constructorModifier* constructorDeclarator throws_? constructorBody + ; + +constructorModifier + : annotation + | 'public' + | 'protected' + | 'private' + ; + +constructorDeclarator + : typeParameters? simpleTypeName '(' formalParameterList? ')' + ; + +simpleTypeName + : Identifier + ; + +constructorBody + : '{' explicitConstructorInvocation? blockStatements? '}' + ; + +explicitConstructorInvocation + : typeArguments? 'this' '(' argumentList? ')' ';' + | typeArguments? 'super' '(' argumentList? ')' ';' + | expressionName '.' typeArguments? 'super' '(' argumentList? ')' ';' + | primary '.' typeArguments? 'super' '(' argumentList? ')' ';' + ; + +enumDeclaration + : classModifier* 'enum' Identifier superinterfaces? enumBody + ; + +enumBody + : '{' enumConstantList? ','? enumBodyDeclarations? '}' + ; + +enumConstantList + : enumConstant (',' enumConstant)* + ; + +enumConstant + : enumConstantModifier* Identifier ('(' argumentList? ')')? classBody? + ; + +enumConstantModifier + : annotation + ; + +enumBodyDeclarations + : ';' classBodyDeclaration* + ; + +/* + * Productions from §9 (Interfaces) + */ + +interfaceDeclaration + : normalInterfaceDeclaration + | annotationTypeDeclaration + ; + +normalInterfaceDeclaration + : interfaceModifier* 'interface' Identifier typeParameters? extendsInterfaces? interfaceBody + ; + +interfaceModifier + : annotation + | 'public' + | 'protected' + | 'private' + | 'abstract' + | 'static' + | 'strictfp' + ; + +extendsInterfaces + : 'extends' interfaceTypeList + ; + +interfaceBody + : '{' interfaceMemberDeclaration* '}' + ; + +interfaceMemberDeclaration + : constantDeclaration + | interfaceMethodDeclaration + | classDeclaration + | interfaceDeclaration + | ';' + ; + +constantDeclaration + : constantModifier* unannType variableDeclaratorList ';' + ; + +constantModifier + : annotation + | 'public' + | 'static' + | 'final' + ; + +interfaceMethodDeclaration + : interfaceMethodModifier* methodHeader methodBody + ; + +interfaceMethodModifier + : annotation + | 'public' + | 'abstract' + | 'default' + | 'static' + | 'strictfp' + ; + +annotationTypeDeclaration + : interfaceModifier* '@' 'interface' Identifier annotationTypeBody + ; + +annotationTypeBody + : '{' annotationTypeMemberDeclaration* '}' + ; + +annotationTypeMemberDeclaration + : annotationTypeElementDeclaration + | constantDeclaration + | classDeclaration + | interfaceDeclaration + | ';' + ; + +annotationTypeElementDeclaration + : annotationTypeElementModifier* unannType Identifier '(' ')' dims? defaultValue? ';' + ; + +annotationTypeElementModifier + : annotation + | 'public' + | 'abstract' + ; + +defaultValue + : 'default' elementValue + ; + +annotation + : normalAnnotation + | markerAnnotation + | singleElementAnnotation + ; + +normalAnnotation + : '@' typeName '(' elementValuePairList? ')' + ; + +elementValuePairList + : elementValuePair (',' elementValuePair)* + ; + +elementValuePair + : Identifier '=' elementValue + ; + +elementValue + : conditionalExpression + | elementValueArrayInitializer + | annotation + ; + +elementValueArrayInitializer + : '{' elementValueList? ','? '}' + ; + +elementValueList + : elementValue (',' elementValue)* + ; + +markerAnnotation + : '@' typeName + ; + +singleElementAnnotation + : '@' typeName '(' elementValue ')' + ; + +/* + * Productions from §10 (Arrays) + */ + +arrayInitializer + : '{' variableInitializerList? ','? '}' + ; + +variableInitializerList + : variableInitializer (',' variableInitializer)* + ; + +/* + * Productions from §14 (Blocks and Statements) + */ + +block + : '{' blockStatements? '}' + ; + +blockStatements + : blockStatement+ + ; + +blockStatement + : localVariableDeclarationStatement + | classDeclaration + | statement + ; + +localVariableDeclarationStatement + : localVariableDeclaration ';' + ; + +localVariableDeclaration + : variableModifier* unannType variableDeclaratorList + ; + +statement + : statementWithoutTrailingSubstatement + | labeledStatement + | ifThenStatement + | ifThenElseStatement + | whileStatement + | forStatement + ; + +statementNoShortIf + : statementWithoutTrailingSubstatement + | labeledStatementNoShortIf + | ifThenElseStatementNoShortIf + | whileStatementNoShortIf + | forStatementNoShortIf + ; + +statementWithoutTrailingSubstatement + : block + | emptyStatement + | expressionStatement + | assertStatement + | switchStatement + | doStatement + | breakStatement + | continueStatement + | returnStatement + | synchronizedStatement + | throwStatement + | tryStatement + ; + +emptyStatement + : ';' + ; + +labeledStatement + : Identifier ':' statement + ; + +labeledStatementNoShortIf + : Identifier ':' statementNoShortIf + ; + +expressionStatement + : statementExpression ';' + ; + +statementExpression + : assignment + | preIncrementExpression + | preDecrementExpression + | postIncrementExpression + | postDecrementExpression + | methodInvocation + | classInstanceCreationExpression + ; + +ifThenStatement + : 'if' '(' expression ')' statement + ; + +ifThenElseStatement + : 'if' '(' expression ')' statementNoShortIf 'else' statement + ; + +ifThenElseStatementNoShortIf + : 'if' '(' expression ')' statementNoShortIf 'else' statementNoShortIf + ; + +assertStatement + : 'assert' expression ';' + | 'assert' expression ':' expression ';' + ; + +switchStatement + : 'switch' '(' expression ')' switchBlock + ; + +switchBlock + : '{' switchBlockStatementGroup* switchLabel* '}' + ; + +switchBlockStatementGroup + : switchLabels blockStatements + ; + +switchLabels + : switchLabel switchLabel* + ; + +switchLabel + : 'case' constantExpression ':' + | 'case' enumConstantName ':' + | 'default' ':' + ; + +enumConstantName + : Identifier + ; + +whileStatement + : 'while' '(' expression ')' statement + ; + +whileStatementNoShortIf + : 'while' '(' expression ')' statementNoShortIf + ; + +doStatement + : 'do' statement 'while' '(' expression ')' ';' + ; + +forStatement + : basicForStatement + | enhancedForStatement + ; + +forStatementNoShortIf + : basicForStatementNoShortIf + | enhancedForStatementNoShortIf + ; + +basicForStatement + : 'for' '(' forInit? ';' expression? ';' forUpdate? ')' statement + ; + +basicForStatementNoShortIf + : 'for' '(' forInit? ';' expression? ';' forUpdate? ')' statementNoShortIf + ; + +forInit + : statementExpressionList + | localVariableDeclaration + ; + +forUpdate + : statementExpressionList + ; + +statementExpressionList + : statementExpression (',' statementExpression)* + ; + +enhancedForStatement + : 'for' '(' variableModifier* unannType variableDeclaratorId ':' expression ')' statement + ; + +enhancedForStatementNoShortIf + : 'for' '(' variableModifier* unannType variableDeclaratorId ':' expression ')' statementNoShortIf + ; + +breakStatement + : 'break' Identifier? ';' + ; + +continueStatement + : 'continue' Identifier? ';' + ; + +returnStatement + : 'return' expression? ';' + ; + +throwStatement + : 'throw' expression ';' + ; + +synchronizedStatement + : 'synchronized' '(' expression ')' block + ; + +tryStatement + : 'try' block catches + | 'try' block catches? finally_ + | tryWithResourcesStatement + ; + +catches + : catchClause catchClause* + ; + +catchClause + : 'catch' '(' catchFormalParameter ')' block + ; + +catchFormalParameter + : variableModifier* catchType variableDeclaratorId + ; + +catchType + : unannClassType ('|' classType)* + ; + +finally_ + : 'finally' block + ; + +tryWithResourcesStatement + : 'try' resourceSpecification block catches? finally_? + ; + +resourceSpecification + : '(' resourceList ';'? ')' + ; + +resourceList + : resource (';' resource)* + ; + +resource + : variableModifier* unannType variableDeclaratorId '=' expression + ; + +/* + * Productions from §15 (Expressions) + */ + +primary + : ( primaryNoNewArray_lfno_primary + | arrayCreationExpression + ) + ( primaryNoNewArray_lf_primary + )* + ; + +primaryNoNewArray + : literal + | typeName ('[' ']')* '.' 'class' + | 'void' '.' 'class' + | 'this' + | typeName '.' 'this' + | '(' expression ')' + | classInstanceCreationExpression + | fieldAccess + | arrayAccess + | methodInvocation + | methodReference + ; + +primaryNoNewArray_lf_arrayAccess + : + ; + +primaryNoNewArray_lfno_arrayAccess + : literal + | typeName ('[' ']')* '.' 'class' + | 'void' '.' 'class' + | 'this' + | typeName '.' 'this' + | '(' expression ')' + | classInstanceCreationExpression + | fieldAccess + | methodInvocation + | methodReference + ; + +primaryNoNewArray_lf_primary + : classInstanceCreationExpression_lf_primary + | fieldAccess_lf_primary + | arrayAccess_lf_primary + | methodInvocation_lf_primary + | methodReference_lf_primary + ; + +primaryNoNewArray_lf_primary_lf_arrayAccess_lf_primary + : + ; + +primaryNoNewArray_lf_primary_lfno_arrayAccess_lf_primary + : classInstanceCreationExpression_lf_primary + | fieldAccess_lf_primary + | methodInvocation_lf_primary + | methodReference_lf_primary + ; + +primaryNoNewArray_lfno_primary + : literal + | typeName ('[' ']')* '.' 'class' + | unannPrimitiveType ('[' ']')* '.' 'class' + | 'void' '.' 'class' + | 'this' + | typeName '.' 'this' + | '(' expression ')' + | classInstanceCreationExpression_lfno_primary + | fieldAccess_lfno_primary + | arrayAccess_lfno_primary + | methodInvocation_lfno_primary + | methodReference_lfno_primary + ; + +primaryNoNewArray_lfno_primary_lf_arrayAccess_lfno_primary + : + ; + +primaryNoNewArray_lfno_primary_lfno_arrayAccess_lfno_primary + : literal + | typeName ('[' ']')* '.' 'class' + | unannPrimitiveType ('[' ']')* '.' 'class' + | 'void' '.' 'class' + | 'this' + | typeName '.' 'this' + | '(' expression ')' + | classInstanceCreationExpression_lfno_primary + | fieldAccess_lfno_primary + | methodInvocation_lfno_primary + | methodReference_lfno_primary + ; + +classInstanceCreationExpression + : 'new' typeArguments? annotation* Identifier ('.' annotation* Identifier)* typeArgumentsOrDiamond? '(' argumentList? ')' classBody? + | expressionName '.' 'new' typeArguments? annotation* Identifier typeArgumentsOrDiamond? '(' argumentList? ')' classBody? + | primary '.' 'new' typeArguments? annotation* Identifier typeArgumentsOrDiamond? '(' argumentList? ')' classBody? + ; + +classInstanceCreationExpression_lf_primary + : '.' 'new' typeArguments? annotation* Identifier typeArgumentsOrDiamond? '(' argumentList? ')' classBody? + ; + +classInstanceCreationExpression_lfno_primary + : 'new' typeArguments? annotation* Identifier ('.' annotation* Identifier)* typeArgumentsOrDiamond? '(' argumentList? ')' classBody? + | expressionName '.' 'new' typeArguments? annotation* Identifier typeArgumentsOrDiamond? '(' argumentList? ')' classBody? + ; + +typeArgumentsOrDiamond + : typeArguments + | '<' '>' + ; + +fieldAccess + : primary '.' Identifier + | 'super' '.' Identifier + | typeName '.' 'super' '.' Identifier + ; + +fieldAccess_lf_primary + : '.' Identifier + ; + +fieldAccess_lfno_primary + : 'super' '.' Identifier + | typeName '.' 'super' '.' Identifier + ; + +arrayAccess + : ( expressionName '[' expression ']' + | primaryNoNewArray_lfno_arrayAccess '[' expression ']' + ) + ( primaryNoNewArray_lf_arrayAccess '[' expression ']' + )* + ; + +arrayAccess_lf_primary + : ( primaryNoNewArray_lf_primary_lfno_arrayAccess_lf_primary '[' expression ']' + ) + ( primaryNoNewArray_lf_primary_lf_arrayAccess_lf_primary '[' expression ']' + )* + ; + +arrayAccess_lfno_primary + : ( expressionName '[' expression ']' + | primaryNoNewArray_lfno_primary_lfno_arrayAccess_lfno_primary '[' expression ']' + ) + ( primaryNoNewArray_lfno_primary_lf_arrayAccess_lfno_primary '[' expression ']' + )* + ; + +methodInvocation + : methodName '(' argumentList? ')' + | typeName '.' typeArguments? Identifier '(' argumentList? ')' + | expressionName '.' typeArguments? Identifier '(' argumentList? ')' + | primary '.' typeArguments? Identifier '(' argumentList? ')' + | 'super' '.' typeArguments? Identifier '(' argumentList? ')' + | typeName '.' 'super' '.' typeArguments? Identifier '(' argumentList? ')' + ; + +methodInvocation_lf_primary + : '.' typeArguments? Identifier '(' argumentList? ')' + ; + +methodInvocation_lfno_primary + : methodName '(' argumentList? ')' + | typeName '.' typeArguments? Identifier '(' argumentList? ')' + | expressionName '.' typeArguments? Identifier '(' argumentList? ')' + | 'super' '.' typeArguments? Identifier '(' argumentList? ')' + | typeName '.' 'super' '.' typeArguments? Identifier '(' argumentList? ')' + ; + +argumentList + : expression (',' expression)* + ; + +methodReference + : expressionName '::' typeArguments? Identifier + | referenceType '::' typeArguments? Identifier + | primary '::' typeArguments? Identifier + | 'super' '::' typeArguments? Identifier + | typeName '.' 'super' '::' typeArguments? Identifier + | classType '::' typeArguments? 'new' + | arrayType '::' 'new' + ; + +methodReference_lf_primary + : '::' typeArguments? Identifier + ; + +methodReference_lfno_primary + : expressionName '::' typeArguments? Identifier + | referenceType '::' typeArguments? Identifier + | 'super' '::' typeArguments? Identifier + | typeName '.' 'super' '::' typeArguments? Identifier + | classType '::' typeArguments? 'new' + | arrayType '::' 'new' + ; + +arrayCreationExpression + : 'new' primitiveType dimExprs dims? + | 'new' classOrInterfaceType dimExprs dims? + | 'new' primitiveType dims arrayInitializer + | 'new' classOrInterfaceType dims arrayInitializer + ; + +dimExprs + : dimExpr dimExpr* + ; + +dimExpr + : annotation* '[' expression ']' + ; + +constantExpression + : expression + ; + +expression + : lambdaExpression + | assignmentExpression + ; + +lambdaExpression + : lambdaParameters '->' lambdaBody + ; + +lambdaParameters + : Identifier + | '(' formalParameterList? ')' + | '(' inferredFormalParameterList ')' + ; + +inferredFormalParameterList + : Identifier (',' Identifier)* + ; + +lambdaBody + : expression + | block + ; + +assignmentExpression + : conditionalExpression + | assignment + ; + +assignment + : leftHandSide assignmentOperator expression + ; + +leftHandSide + : expressionName + | fieldAccess + | arrayAccess + ; + +assignmentOperator + : '=' + | '*=' + | '/=' + | '%=' + | '+=' + | '-=' + | '<<=' + | '>>=' + | '>>>=' + | '&=' + | '^=' + | '|=' + ; + +conditionalExpression + : conditionalOrExpression + | conditionalOrExpression '?' expression ':' conditionalExpression + ; + +conditionalOrExpression + : conditionalAndExpression + | conditionalOrExpression '||' conditionalAndExpression + ; + +conditionalAndExpression + : inclusiveOrExpression + | conditionalAndExpression '&&' inclusiveOrExpression + ; + +inclusiveOrExpression + : exclusiveOrExpression + | inclusiveOrExpression '|' exclusiveOrExpression + ; + +exclusiveOrExpression + : andExpression + | exclusiveOrExpression '^' andExpression + ; + +andExpression + : equalityExpression + | andExpression '&' equalityExpression + ; + +equalityExpression + : relationalExpression + | equalityExpression '==' relationalExpression + | equalityExpression '!=' relationalExpression + ; + +relationalExpression + : shiftExpression + | relationalExpression '<' shiftExpression + | relationalExpression '>' shiftExpression + | relationalExpression '<=' shiftExpression + | relationalExpression '>=' shiftExpression + | relationalExpression 'instanceof' referenceType + ; + +shiftExpression + : additiveExpression + | shiftExpression '<' '<' additiveExpression + | shiftExpression '>' '>' additiveExpression + | shiftExpression '>' '>' '>' additiveExpression + ; + +additiveExpression + : multiplicativeExpression + | additiveExpression '+' multiplicativeExpression + | additiveExpression '-' multiplicativeExpression + ; + +multiplicativeExpression + : unaryExpression + | multiplicativeExpression '*' unaryExpression + | multiplicativeExpression '/' unaryExpression + | multiplicativeExpression '%' unaryExpression + ; + +unaryExpression + : preIncrementExpression + | preDecrementExpression + | '+' unaryExpression + | '-' unaryExpression + | unaryExpressionNotPlusMinus + ; + +preIncrementExpression + : '++' unaryExpression + ; + +preDecrementExpression + : '--' unaryExpression + ; + +unaryExpressionNotPlusMinus + : postfixExpression + | '~' unaryExpression + | '!' unaryExpression + | castExpression + ; + +postfixExpression + : ( primary + | expressionName + ) + ( postIncrementExpression_lf_postfixExpression + | postDecrementExpression_lf_postfixExpression + )* + ; + +postIncrementExpression + : postfixExpression '++' + ; + +postIncrementExpression_lf_postfixExpression + : '++' + ; + +postDecrementExpression + : postfixExpression '--' + ; + +postDecrementExpression_lf_postfixExpression + : '--' + ; + +castExpression + : '(' primitiveType ')' unaryExpression + | '(' referenceType additionalBound* ')' unaryExpressionNotPlusMinus + | '(' referenceType additionalBound* ')' lambdaExpression + ; + +// LEXER + +// §3.9 Keywords + +ABSTRACT : 'abstract'; +ASSERT : 'assert'; +BOOLEAN : 'boolean'; +BREAK : 'break'; +BYTE : 'byte'; +CASE : 'case'; +CATCH : 'catch'; +CHAR : 'char'; +CLASS : 'class'; +CONST : 'const'; +CONTINUE : 'continue'; +DEFAULT : 'default'; +DO : 'do'; +DOUBLE : 'double'; +ELSE : 'else'; +ENUM : 'enum'; +EXTENDS : 'extends'; +FINAL : 'final'; +FINALLY : 'finally'; +FLOAT : 'float'; +FOR : 'for'; +IF : 'if'; +GOTO : 'goto'; +IMPLEMENTS : 'implements'; +IMPORT : 'import'; +INSTANCEOF : 'instanceof'; +INT : 'int'; +INTERFACE : 'interface'; +LONG : 'long'; +NATIVE : 'native'; +NEW : 'new'; +PACKAGE : 'package'; +PRIVATE : 'private'; +PROTECTED : 'protected'; +PUBLIC : 'public'; +RETURN : 'return'; +SHORT : 'short'; +STATIC : 'static'; +STRICTFP : 'strictfp'; +SUPER : 'super'; +SWITCH : 'switch'; +SYNCHRONIZED : 'synchronized'; +THIS : 'this'; +THROW : 'throw'; +THROWS : 'throws'; +TRANSIENT : 'transient'; +TRY : 'try'; +VOID : 'void'; +VOLATILE : 'volatile'; +WHILE : 'while'; + +// §3.10.1 Integer Literals + +IntegerLiteral + : DecimalIntegerLiteral + | HexIntegerLiteral + | OctalIntegerLiteral + | BinaryIntegerLiteral + ; + +fragment +DecimalIntegerLiteral + : DecimalNumeral IntegerTypeSuffix? + ; + +fragment +HexIntegerLiteral + : HexNumeral IntegerTypeSuffix? + ; + +fragment +OctalIntegerLiteral + : OctalNumeral IntegerTypeSuffix? + ; + +fragment +BinaryIntegerLiteral + : BinaryNumeral IntegerTypeSuffix? + ; + +fragment +IntegerTypeSuffix + : [lL] + ; + +fragment +DecimalNumeral + : '0' + | NonZeroDigit (Digits? | Underscores Digits) + ; + +fragment +Digits + : Digit (DigitsAndUnderscores? Digit)? + ; + +fragment +Digit + : '0' + | NonZeroDigit + ; + +fragment +NonZeroDigit + : [1-9] + ; + +fragment +DigitsAndUnderscores + : DigitOrUnderscore+ + ; + +fragment +DigitOrUnderscore + : Digit + | '_' + ; + +fragment +Underscores + : '_'+ + ; + +fragment +HexNumeral + : '0' [xX] HexDigits + ; + +fragment +HexDigits + : HexDigit (HexDigitsAndUnderscores? HexDigit)? + ; + +fragment +HexDigit + : [0-9a-fA-F] + ; + +fragment +HexDigitsAndUnderscores + : HexDigitOrUnderscore+ + ; + +fragment +HexDigitOrUnderscore + : HexDigit + | '_' + ; + +fragment +OctalNumeral + : '0' Underscores? OctalDigits + ; + +fragment +OctalDigits + : OctalDigit (OctalDigitsAndUnderscores? OctalDigit)? + ; + +fragment +OctalDigit + : [0-7] + ; + +fragment +OctalDigitsAndUnderscores + : OctalDigitOrUnderscore+ + ; + +fragment +OctalDigitOrUnderscore + : OctalDigit + | '_' + ; + +fragment +BinaryNumeral + : '0' [bB] BinaryDigits + ; + +fragment +BinaryDigits + : BinaryDigit (BinaryDigitsAndUnderscores? BinaryDigit)? + ; + +fragment +BinaryDigit + : [01] + ; + +fragment +BinaryDigitsAndUnderscores + : BinaryDigitOrUnderscore+ + ; + +fragment +BinaryDigitOrUnderscore + : BinaryDigit + | '_' + ; + +// §3.10.2 Floating-Point Literals + +FloatingPointLiteral + : DecimalFloatingPointLiteral + | HexadecimalFloatingPointLiteral + ; + +fragment +DecimalFloatingPointLiteral + : Digits '.' Digits? ExponentPart? FloatTypeSuffix? + | '.' Digits ExponentPart? FloatTypeSuffix? + | Digits ExponentPart FloatTypeSuffix? + | Digits FloatTypeSuffix + ; + +fragment +ExponentPart + : ExponentIndicator SignedInteger + ; + +fragment +ExponentIndicator + : [eE] + ; + +fragment +SignedInteger + : Sign? Digits + ; + +fragment +Sign + : [+-] + ; + +fragment +FloatTypeSuffix + : [fFdD] + ; + +fragment +HexadecimalFloatingPointLiteral + : HexSignificand BinaryExponent FloatTypeSuffix? + ; + +fragment +HexSignificand + : HexNumeral '.'? + | '0' [xX] HexDigits? '.' HexDigits + ; + +fragment +BinaryExponent + : BinaryExponentIndicator SignedInteger + ; + +fragment +BinaryExponentIndicator + : [pP] + ; + +// §3.10.3 Boolean Literals + +BooleanLiteral + : 'true' + | 'false' + ; + +// §3.10.4 Character Literals + +CharacterLiteral + : '\'' SingleCharacter '\'' + | '\'' EscapeSequence '\'' + ; + +fragment +SingleCharacter + : ~['\\\r\n] + ; + +// §3.10.5 String Literals + +StringLiteral + : '"' StringCharacters? '"' + ; + +fragment +StringCharacters + : StringCharacter+ + ; + +fragment +StringCharacter + : ~["\\\r\n] + | EscapeSequence + ; + +// §3.10.6 Escape Sequences for Character and String Literals + +fragment +EscapeSequence + : '\\' [btnfr"'\\] + | OctalEscape + | UnicodeEscape // This is not in the spec but prevents having to preprocess the input + ; + +fragment +OctalEscape + : '\\' OctalDigit + | '\\' OctalDigit OctalDigit + | '\\' ZeroToThree OctalDigit OctalDigit + ; + +fragment +ZeroToThree + : [0-3] + ; + +// This is not in the spec but prevents having to preprocess the input +fragment +UnicodeEscape + : '\\' 'u'+ HexDigit HexDigit HexDigit HexDigit + ; + +// §3.10.7 The Null Literal + +NullLiteral + : 'null' + ; + +// §3.11 Separators + +LPAREN : '('; +RPAREN : ')'; +LBRACE : '{'; +RBRACE : '}'; +LBRACK : '['; +RBRACK : ']'; +SEMI : ';'; +COMMA : ','; +DOT : '.'; + +// §3.12 Operators + +ASSIGN : '='; +GT : '>'; +LT : '<'; +BANG : '!'; +TILDE : '~'; +QUESTION : '?'; +COLON : ':'; +EQUAL : '=='; +LE : '<='; +GE : '>='; +NOTEQUAL : '!='; +AND : '&&'; +OR : '||'; +INC : '++'; +DEC : '--'; +ADD : '+'; +SUB : '-'; +MUL : '*'; +DIV : '/'; +BITAND : '&'; +BITOR : '|'; +CARET : '^'; +MOD : '%'; +ARROW : '->'; +COLONCOLON : '::'; + +ADD_ASSIGN : '+='; +SUB_ASSIGN : '-='; +MUL_ASSIGN : '*='; +DIV_ASSIGN : '/='; +AND_ASSIGN : '&='; +OR_ASSIGN : '|='; +XOR_ASSIGN : '^='; +MOD_ASSIGN : '%='; +LSHIFT_ASSIGN : '<<='; +RSHIFT_ASSIGN : '>>='; +URSHIFT_ASSIGN : '>>>='; + +// §3.8 Identifiers (must appear after all keywords in the grammar) + +Identifier + : JavaLetter JavaLetterOrDigit* + ; + +fragment +JavaLetter + : [a-zA-Z$_] // these are the "java letters" below 0x7F + | // covers all characters above 0x7F which are not a surrogate + ~[\u0000-\u007F\uD800-\uDBFF] + {Character.isJavaIdentifierStart(_input.LA(-1))}? + | // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF + [\uD800-\uDBFF] [\uDC00-\uDFFF] + {Character.isJavaIdentifierStart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? + ; + +fragment +JavaLetterOrDigit + : [a-zA-Z0-9$_] // these are the "java letters or digits" below 0x7F + | // covers all characters above 0x7F which are not a surrogate + ~[\u0000-\u007F\uD800-\uDBFF] + {Character.isJavaIdentifierPart(_input.LA(-1))}? + | // covers UTF-16 surrogate pairs encodings for U+10000 to U+10FFFF + [\uD800-\uDBFF] [\uDC00-\uDFFF] + {Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}? + ; + +// +// Additional symbols not defined in the lexical specification +// + +AT : '@'; +ELLIPSIS : '...'; + +// +// Whitespace and comments +// + +WS : [ \t\r\n\u000C]+ -> skip + ; + +COMMENT + : '/*' .*? '*/' -> skip + ; + +LINE_COMMENT + : '//' ~[\r\n]* -> skip + ; \ No newline at end of file diff --git a/antlr/src/main/antlr4/com/baeldung/antlr/Log.g4 b/antlr/src/main/antlr4/com/baeldung/antlr/Log.g4 new file mode 100644 index 0000000000..3ecb966f50 --- /dev/null +++ b/antlr/src/main/antlr4/com/baeldung/antlr/Log.g4 @@ -0,0 +1,16 @@ +grammar Log; + +log : entry+; +entry : timestamp ' ' level ' ' message CRLF; +timestamp : DATE ' ' TIME; +level : 'ERROR' | 'INFO' | 'DEBUG'; +message : (TEXT | ' ')+; + +fragment DIGIT : [0-9]; +fragment TWODIGIT : DIGIT DIGIT; +fragment LETTER : [A-Za-z]; + +DATE : TWODIGIT TWODIGIT '-' LETTER LETTER LETTER '-' TWODIGIT; +TIME : TWODIGIT ':' TWODIGIT ':' TWODIGIT; +TEXT : LETTER+; +CRLF : '\r'? '\n' | '\r'; \ No newline at end of file diff --git a/antlr/src/main/java/com/baeldung/antlr/java/UppercaseMethodListener.java b/antlr/src/main/java/com/baeldung/antlr/java/UppercaseMethodListener.java new file mode 100644 index 0000000000..5092359b72 --- /dev/null +++ b/antlr/src/main/java/com/baeldung/antlr/java/UppercaseMethodListener.java @@ -0,0 +1,28 @@ +package com.baeldung.antlr.java; + +import com.baeldung.antlr.Java8BaseListener; +import com.baeldung.antlr.Java8Parser; +import org.antlr.v4.runtime.tree.TerminalNode; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class UppercaseMethodListener extends Java8BaseListener { + + private List errors = new ArrayList(); + + @Override + public void enterMethodDeclarator(Java8Parser.MethodDeclaratorContext ctx) { + TerminalNode node = ctx.Identifier(); + String methodName = node.getText(); + + if (Character.isUpperCase(methodName.charAt(0))){ + errors.add(String.format("Method %s is uppercased!", methodName)); + } + } + + public List getErrors(){ + return Collections.unmodifiableList(errors); + } +} diff --git a/antlr/src/main/java/com/baeldung/antlr/log/LogListener.java b/antlr/src/main/java/com/baeldung/antlr/log/LogListener.java new file mode 100644 index 0000000000..1f6d91df95 --- /dev/null +++ b/antlr/src/main/java/com/baeldung/antlr/log/LogListener.java @@ -0,0 +1,51 @@ +package com.baeldung.antlr.log; + +import com.baeldung.antlr.LogBaseListener; +import com.baeldung.antlr.LogParser; +import com.baeldung.antlr.log.model.LogLevel; +import com.baeldung.antlr.log.model.LogEntry; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +public class LogListener extends LogBaseListener { + + private static final DateTimeFormatter DEFAULT_DATETIME_FORMATTER + = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss", Locale.ENGLISH); + + private List entries = new ArrayList<>(); + private LogEntry currentLogEntry; + + @Override + public void enterEntry(LogParser.EntryContext ctx) { + this.currentLogEntry = new LogEntry(); + } + + @Override + public void exitEntry(LogParser.EntryContext ctx) { + entries.add(currentLogEntry); + } + + @Override + public void enterTimestamp(LogParser.TimestampContext ctx) { + currentLogEntry.setTimestamp(LocalDateTime.parse(ctx.getText(), DEFAULT_DATETIME_FORMATTER)); + } + + @Override + public void enterMessage(LogParser.MessageContext ctx) { + currentLogEntry.setMessage(ctx.getText()); + } + + @Override + public void enterLevel(LogParser.LevelContext ctx) { + currentLogEntry.setLevel(LogLevel.valueOf(ctx.getText())); + } + + public List getEntries() { + return Collections.unmodifiableList(entries); + } +} diff --git a/antlr/src/main/java/com/baeldung/antlr/log/model/LogEntry.java b/antlr/src/main/java/com/baeldung/antlr/log/model/LogEntry.java new file mode 100644 index 0000000000..2b406c4ae9 --- /dev/null +++ b/antlr/src/main/java/com/baeldung/antlr/log/model/LogEntry.java @@ -0,0 +1,35 @@ +package com.baeldung.antlr.log.model; + + +import java.time.LocalDateTime; + +public class LogEntry { + + private LogLevel level; + private String message; + private LocalDateTime timestamp; + + public LogLevel getLevel() { + return level; + } + + public void setLevel(LogLevel level) { + this.level = level; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public LocalDateTime getTimestamp() { + return timestamp; + } + + public void setTimestamp(LocalDateTime timestamp) { + this.timestamp = timestamp; + } +} diff --git a/antlr/src/main/java/com/baeldung/antlr/log/model/LogLevel.java b/antlr/src/main/java/com/baeldung/antlr/log/model/LogLevel.java new file mode 100644 index 0000000000..004d9c6e8c --- /dev/null +++ b/antlr/src/main/java/com/baeldung/antlr/log/model/LogLevel.java @@ -0,0 +1,5 @@ +package com.baeldung.antlr.log.model; + +public enum LogLevel { + DEBUG, INFO, ERROR +} diff --git a/antlr/src/test/java/com/baeldung/antlr/JavaParserUnitTest.java b/antlr/src/test/java/com/baeldung/antlr/JavaParserUnitTest.java new file mode 100644 index 0000000000..0d43e0f284 --- /dev/null +++ b/antlr/src/test/java/com/baeldung/antlr/JavaParserUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.antlr; + +import com.baeldung.antlr.java.UppercaseMethodListener; +import org.antlr.v4.runtime.CharStreams; +import org.antlr.v4.runtime.CommonTokenStream; +import org.antlr.v4.runtime.tree.ParseTree; +import org.antlr.v4.runtime.tree.ParseTreeWalker; +import org.junit.Test; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +public class JavaParserUnitTest { + + @Test + public void whenOneMethodStartsWithUpperCase_thenOneErrorReturned() throws Exception{ + + String javaClassContent = "public class SampleClass { void DoSomething(){} }"; + Java8Lexer java8Lexer = new Java8Lexer(CharStreams.fromString(javaClassContent)); + CommonTokenStream tokens = new CommonTokenStream(java8Lexer); + Java8Parser java8Parser = new Java8Parser(tokens); + ParseTree tree = java8Parser.compilationUnit(); + ParseTreeWalker walker = new ParseTreeWalker(); + UppercaseMethodListener uppercaseMethodListener = new UppercaseMethodListener(); + walker.walk(uppercaseMethodListener, tree); + + assertThat(uppercaseMethodListener.getErrors().size(), is(1)); + assertThat(uppercaseMethodListener.getErrors().get(0), + is("Method DoSomething is uppercased!")); + } +} diff --git a/antlr/src/test/java/com/baeldung/antlr/LogParserUnitTest.java b/antlr/src/test/java/com/baeldung/antlr/LogParserUnitTest.java new file mode 100644 index 0000000000..d263c2bd19 --- /dev/null +++ b/antlr/src/test/java/com/baeldung/antlr/LogParserUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.antlr; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import com.baeldung.antlr.log.LogListener; +import com.baeldung.antlr.log.model.LogLevel; +import com.baeldung.antlr.log.model.LogEntry; +import org.antlr.v4.runtime.CharStreams; +import org.antlr.v4.runtime.CommonTokenStream; +import org.antlr.v4.runtime.tree.ParseTreeWalker; +import org.junit.Test; + +import java.time.LocalDateTime; + + +public class LogParserUnitTest { + + @Test + public void whenLogContainsOneErrorLogEntry_thenOneErrorIsReturned() throws Exception { + String logLines = "2018-May-05 14:20:21 DEBUG entering awesome method\r\n" + + "2018-May-05 14:20:24 ERROR Bad thing happened\r\n"; + LogLexer serverLogLexer = new LogLexer(CharStreams.fromString(logLines)); + CommonTokenStream tokens = new CommonTokenStream( serverLogLexer ); + LogParser logParser = new LogParser(tokens); + ParseTreeWalker walker = new ParseTreeWalker(); + LogListener logWalker = new LogListener(); + walker.walk(logWalker, logParser.log()); + + assertThat(logWalker.getEntries().size(), is(2)); + LogEntry error = logWalker.getEntries().get(1); + assertThat(error.getLevel(), is(LogLevel.ERROR)); + assertThat(error.getMessage(), is("Bad thing happened")); + assertThat(error.getTimestamp(), is(LocalDateTime.of(2018,5,5,14,20,24))); + } +} diff --git a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationIntegrationTest.java b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationLiveTest.java similarity index 99% rename from apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationIntegrationTest.java rename to apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationLiveTest.java index 546b8fe45c..b54b62ca02 100644 --- a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationIntegrationTest.java +++ b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneAdvancedOperationLiveTest.java @@ -19,7 +19,7 @@ import java.util.List; import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -public class CayenneAdvancedOperationIntegrationTest { +public class CayenneAdvancedOperationLiveTest { private static ObjectContext context = null; @BeforeClass diff --git a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationIntegrationTest.java b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationLiveTest.java similarity index 98% rename from apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationIntegrationTest.java rename to apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationLiveTest.java index 85f06d5538..e6ca4a3634 100644 --- a/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationIntegrationTest.java +++ b/apache-cayenne/src/test/java/com/baeldung/apachecayenne/CayenneOperationLiveTest.java @@ -16,7 +16,7 @@ import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertNull; -public class CayenneOperationIntegrationTest { +public class CayenneOperationLiveTest { private static ObjectContext context = null; @BeforeClass diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/BaseTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/BaseManualTest.java similarity index 94% rename from apache-curator/src/test/java/com/baeldung/apache/curator/BaseTest.java rename to apache-curator/src/test/java/com/baeldung/apache/curator/BaseManualTest.java index cfac3ee3f2..5722228b26 100644 --- a/apache-curator/src/test/java/com/baeldung/apache/curator/BaseTest.java +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/BaseManualTest.java @@ -6,7 +6,7 @@ import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.RetryNTimes; import org.junit.Before; -public abstract class BaseTest { +public abstract class BaseManualTest { @Before public void setup() { diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java index d02ef8131d..1a6fe6ccd0 100644 --- a/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java @@ -12,9 +12,9 @@ import org.apache.curator.framework.CuratorFramework; import org.apache.curator.x.async.AsyncCuratorFramework; import org.junit.Test; -import com.baeldung.apache.curator.BaseTest; +import com.baeldung.apache.curator.BaseManualTest; -public class ConfigurationManagementManualTest extends BaseTest { +public class ConfigurationManagementManualTest extends BaseManualTest { private static final String KEY_FORMAT = "/%s"; diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java index 4400c1d1aa..d7caa18ce9 100644 --- a/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java @@ -11,9 +11,9 @@ import org.apache.curator.x.async.modeled.ModeledFramework; import org.apache.curator.x.async.modeled.ZPath; import org.junit.Test; -import com.baeldung.apache.curator.BaseTest; +import com.baeldung.apache.curator.BaseManualTest; -public class ModelTypedExamplesManualTest extends BaseTest { +public class ModelTypedExamplesManualTest extends BaseManualTest { @Test public void givenPath_whenStoreAModel_thenNodesAreCreated() diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java index 04f4104e6b..0c5890ad59 100644 --- a/apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java +++ b/apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java @@ -10,9 +10,9 @@ import org.apache.curator.framework.recipes.shared.SharedCount; import org.apache.curator.framework.state.ConnectionState; import org.junit.Test; -import com.baeldung.apache.curator.BaseTest; +import com.baeldung.apache.curator.BaseManualTest; -public class RecipesManualTest extends BaseTest { +public class RecipesManualTest extends BaseManualTest { @Test public void givenRunningZookeeper_whenUsingLeaderElection_thenNoErrors() { diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/ChunkerTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/ChunkerUnitTest.java similarity index 97% rename from apache-opennlp/src/test/java/com/baeldung/apache/opennlp/ChunkerTest.java rename to apache-opennlp/src/test/java/com/baeldung/apache/opennlp/ChunkerUnitTest.java index cc3abb422b..91dde8a2d1 100644 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/ChunkerTest.java +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/ChunkerUnitTest.java @@ -10,7 +10,7 @@ import opennlp.tools.tokenize.SimpleTokenizer; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; -public class ChunkerTest { +public class ChunkerUnitTest { @Test public void givenChunkerModel_whenChunk_thenChunksAreDetected() throws Exception { diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LanguageDetectorAndTrainingDataTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LanguageDetectorAndTrainingDataUnitTest.java similarity index 97% rename from apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LanguageDetectorAndTrainingDataTest.java rename to apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LanguageDetectorAndTrainingDataUnitTest.java index 5eb649dae1..82732809a5 100644 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LanguageDetectorAndTrainingDataTest.java +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LanguageDetectorAndTrainingDataUnitTest.java @@ -19,7 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import org.junit.Test; -public class LanguageDetectorAndTrainingDataTest { +public class LanguageDetectorAndTrainingDataUnitTest { @Test public void givenLanguageDictionary_whenLanguageDetect_thenLanguageIsDetected() throws FileNotFoundException, IOException { diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LemmetizerTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LemmetizerUnitTest.java similarity index 97% rename from apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LemmetizerTest.java rename to apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LemmetizerUnitTest.java index bb681fb8d8..05bc6242b2 100644 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LemmetizerTest.java +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/LemmetizerUnitTest.java @@ -8,7 +8,7 @@ import opennlp.tools.tokenize.SimpleTokenizer; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; -public class LemmetizerTest { +public class LemmetizerUnitTest { @Test public void givenEnglishDictionary_whenLemmatize_thenLemmasAreDetected() throws Exception { diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/NamedEntityRecognitionTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/NamedEntityRecognitionUnitTest.java similarity index 97% rename from apache-opennlp/src/test/java/com/baeldung/apache/opennlp/NamedEntityRecognitionTest.java rename to apache-opennlp/src/test/java/com/baeldung/apache/opennlp/NamedEntityRecognitionUnitTest.java index 94224409d6..6965498e12 100644 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/NamedEntityRecognitionTest.java +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/NamedEntityRecognitionUnitTest.java @@ -11,7 +11,7 @@ import opennlp.tools.util.Span; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; -public class NamedEntityRecognitionTest { +public class NamedEntityRecognitionUnitTest { @Test public void givenEnglishPersonModel_whenNER_thenPersonsAreDetected() throws Exception { diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/POSTaggerTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/POSTaggerUnitTest.java similarity index 96% rename from apache-opennlp/src/test/java/com/baeldung/apache/opennlp/POSTaggerTest.java rename to apache-opennlp/src/test/java/com/baeldung/apache/opennlp/POSTaggerUnitTest.java index 1bfebe208c..c084dcc1f2 100644 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/POSTaggerTest.java +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/POSTaggerUnitTest.java @@ -7,7 +7,7 @@ import opennlp.tools.tokenize.SimpleTokenizer; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; -public class POSTaggerTest { +public class POSTaggerUnitTest { @Test public void givenPOSModel_whenPOSTagging_thenPOSAreDetected() throws Exception { diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/SentenceDetectionTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/SentenceDetectionUnitTest.java similarity index 96% rename from apache-opennlp/src/test/java/com/baeldung/apache/opennlp/SentenceDetectionTest.java rename to apache-opennlp/src/test/java/com/baeldung/apache/opennlp/SentenceDetectionUnitTest.java index 0250b12cbf..60ee51e7ca 100644 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/SentenceDetectionTest.java +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/SentenceDetectionUnitTest.java @@ -6,7 +6,7 @@ import opennlp.tools.sentdetect.SentenceModel; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; -public class SentenceDetectionTest { +public class SentenceDetectionUnitTest { @Test public void givenEnglishModel_whenDetect_thenSentencesAreDetected() throws Exception { diff --git a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/TokenizerTest.java b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/TokenizerUnitTest.java similarity index 97% rename from apache-opennlp/src/test/java/com/baeldung/apache/opennlp/TokenizerTest.java rename to apache-opennlp/src/test/java/com/baeldung/apache/opennlp/TokenizerUnitTest.java index a4dea57cc3..6aa18b3bee 100644 --- a/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/TokenizerTest.java +++ b/apache-opennlp/src/test/java/com/baeldung/apache/opennlp/TokenizerUnitTest.java @@ -8,7 +8,7 @@ import opennlp.tools.tokenize.WhitespaceTokenizer; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; -public class TokenizerTest { +public class TokenizerUnitTest { @Test public void givenEnglishModel_whenTokenize_thenTokensAreDetected() throws Exception { diff --git a/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java index 5319208e85..7253238e80 100644 --- a/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java +++ b/apache-poi/src/test/java/com/baeldung/poi/powerpoint/PowerPointIntegrationTest.java @@ -1,25 +1,30 @@ package com.baeldung.poi.powerpoint; +import java.io.File; +import java.util.List; + import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xslf.usermodel.XSLFShape; import org.apache.poi.xslf.usermodel.XSLFSlide; import org.junit.After; import org.junit.Assert; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; - -import java.io.File; -import java.util.List; +import org.junit.rules.TemporaryFolder; public class PowerPointIntegrationTest { private PowerPointHelper pph; private String fileLocation; private static final String FILE_NAME = "presentation.pptx"; + + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); @Before public void setUp() throws Exception { - File currDir = new File("."); + File currDir = tempFolder.newFolder(); String path = currDir.getAbsolutePath(); fileLocation = path.substring(0, path.length() - 1) + FILE_NAME; diff --git a/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/aws-lambda/pom.xml b/aws-lambda/pom.xml new file mode 100644 index 0000000000..878e4db109 --- /dev/null +++ b/aws-lambda/pom.xml @@ -0,0 +1,99 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + com.baeldung + aws-lambda + 0.1.0-SNAPSHOT + jar + aws-lambda + + + + + com.amazonaws + aws-java-sdk-dynamodb + 1.11.241 + + + com.amazonaws + aws-java-sdk-core + 1.11.241 + + + com.amazonaws + aws-lambda-java-core + ${aws-lambda-java-core.version} + + + commons-logging + commons-logging + + + + + com.amazonaws + aws-lambda-java-events + ${aws-lambda-java-events.version} + + + commons-logging + commons-logging + + + + + com.google.code.gson + gson + ${gson.version} + + + commons-io + commons-io + ${commons-io.version} + + + com.googlecode.json-simple + json-simple + ${json-simple.version} + + + + + + org.apache.maven.plugins + maven-shade-plugin + ${maven-shade-plugin.version} + + false + + + + package + + shade + + + + + + + + 1.1.1 + 20180130 + 2.5 + 1.3.0 + 1.2.0 + 2.8.2 + 1.11.241 + 3.0.0 + 2.10 + + \ No newline at end of file diff --git a/aws/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java b/aws-lambda/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java similarity index 100% rename from aws/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java rename to aws-lambda/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java diff --git a/aws/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java b/aws-lambda/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java similarity index 100% rename from aws/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java rename to aws-lambda/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java diff --git a/aws/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java b/aws-lambda/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java similarity index 100% rename from aws/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java rename to aws-lambda/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java diff --git a/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/APIDemoHandler.java b/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/APIDemoHandler.java new file mode 100644 index 0000000000..328915c028 --- /dev/null +++ b/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/APIDemoHandler.java @@ -0,0 +1,166 @@ +package com.baeldung.lambda.apigateway; + +import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; +import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; +import com.amazonaws.services.dynamodbv2.document.*; +import com.amazonaws.services.dynamodbv2.document.spec.PutItemSpec; +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestStreamHandler; +import com.baeldung.lambda.apigateway.model.Person; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.io.*; + +public class APIDemoHandler implements RequestStreamHandler { + + private JSONParser parser = new JSONParser(); + private static final String DYNAMODB_TABLE_NAME = System.getenv("TABLE_NAME"); + + @Override + public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException { + + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + JSONObject responseJson = new JSONObject(); + + AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient(); + DynamoDB dynamoDb = new DynamoDB(client); + + try { + JSONObject event = (JSONObject) parser.parse(reader); + + if (event.get("body") != null) { + + Person person = new Person((String) event.get("body")); + + dynamoDb.getTable(DYNAMODB_TABLE_NAME) + .putItem(new PutItemSpec().withItem(new Item().withNumber("id", person.getId()) + .withString("firstName", person.getFirstName()) + .withString("lastName", person.getLastName()).withNumber("age", person.getAge()) + .withString("address", person.getAddress()))); + } + + JSONObject responseBody = new JSONObject(); + responseBody.put("message", "New item created"); + + JSONObject headerJson = new JSONObject(); + headerJson.put("x-custom-header", "my custom header value"); + + responseJson.put("statusCode", 200); + responseJson.put("headers", headerJson); + responseJson.put("body", responseBody.toString()); + + } catch (ParseException pex) { + responseJson.put("statusCode", 400); + responseJson.put("exception", pex); + } + + OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); + writer.write(responseJson.toString()); + writer.close(); + } + + public void handleGetByPathParam(InputStream inputStream, OutputStream outputStream, Context context) + throws IOException { + + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + JSONObject responseJson = new JSONObject(); + + AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient(); + DynamoDB dynamoDb = new DynamoDB(client); + + Item result = null; + try { + JSONObject event = (JSONObject) parser.parse(reader); + JSONObject responseBody = new JSONObject(); + + if (event.get("pathParameters") != null) { + + JSONObject pps = (JSONObject) event.get("pathParameters"); + if (pps.get("id") != null) { + + int id = Integer.parseInt((String) pps.get("id")); + result = dynamoDb.getTable(DYNAMODB_TABLE_NAME).getItem("id", id); + } + + } + if (result != null) { + + Person person = new Person(result.toJSON()); + responseBody.put("Person", person); + responseJson.put("statusCode", 200); + } else { + + responseBody.put("message", "No item found"); + responseJson.put("statusCode", 404); + } + + JSONObject headerJson = new JSONObject(); + headerJson.put("x-custom-header", "my custom header value"); + + responseJson.put("headers", headerJson); + responseJson.put("body", responseBody.toString()); + + } catch (ParseException pex) { + responseJson.put("statusCode", 400); + responseJson.put("exception", pex); + } + + OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); + writer.write(responseJson.toString()); + writer.close(); + } + + public void handleGetByQueryParam(InputStream inputStream, OutputStream outputStream, Context context) + throws IOException { + + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + JSONObject responseJson = new JSONObject(); + + AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient(); + DynamoDB dynamoDb = new DynamoDB(client); + + Item result = null; + try { + JSONObject event = (JSONObject) parser.parse(reader); + JSONObject responseBody = new JSONObject(); + + if (event.get("queryStringParameters") != null) { + + JSONObject qps = (JSONObject) event.get("queryStringParameters"); + if (qps.get("id") != null) { + + int id = Integer.parseInt((String) qps.get("id")); + result = dynamoDb.getTable(DYNAMODB_TABLE_NAME).getItem("id", id); + } + } + + if (result != null) { + + Person person = new Person(result.toJSON()); + responseBody.put("Person", person); + responseJson.put("statusCode", 200); + } else { + + responseBody.put("message", "No item found"); + responseJson.put("statusCode", 404); + } + + JSONObject headerJson = new JSONObject(); + headerJson.put("x-custom-header", "my custom header value"); + + responseJson.put("headers", headerJson); + responseJson.put("body", responseBody.toString()); + + } catch (ParseException pex) { + responseJson.put("statusCode", 400); + responseJson.put("exception", pex); + } + + OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); + writer.write(responseJson.toString()); + writer.close(); + } + +} diff --git a/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/model/Person.java b/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/model/Person.java new file mode 100644 index 0000000000..3be7b261cd --- /dev/null +++ b/aws-lambda/src/main/java/com/baeldung/lambda/apigateway/model/Person.java @@ -0,0 +1,68 @@ +package com.baeldung.lambda.apigateway.model; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +public class Person { + + private int id; + private String firstName; + private String lastName; + private int age; + private String address; + + public Person(String json) { + Gson gson = new Gson(); + Person request = gson.fromJson(json, Person.class); + this.id = request.getId(); + this.firstName = request.getFirstName(); + this.lastName = request.getLastName(); + this.age = request.getAge(); + this.address = request.getAddress(); + } + + public String toString() { + final Gson gson = new GsonBuilder().setPrettyPrinting().create(); + return gson.toJson(this); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } +} diff --git a/aws/src/main/java/com/baeldung/lambda/dynamodb/SavePersonHandler.java b/aws-lambda/src/main/java/com/baeldung/lambda/dynamodb/SavePersonHandler.java similarity index 100% rename from aws/src/main/java/com/baeldung/lambda/dynamodb/SavePersonHandler.java rename to aws-lambda/src/main/java/com/baeldung/lambda/dynamodb/SavePersonHandler.java diff --git a/aws/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonRequest.java b/aws-lambda/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonRequest.java similarity index 100% rename from aws/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonRequest.java rename to aws-lambda/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonRequest.java diff --git a/aws/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonResponse.java b/aws-lambda/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonResponse.java similarity index 100% rename from aws/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonResponse.java rename to aws-lambda/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonResponse.java 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/AzureApplicationIntegrationTest.java b/azure/src/test/java/com/baeldung/springboot/azure/AzureApplicationIntegrationTest.java new file mode 100644 index 0000000000..7c3084446f --- /dev/null +++ b/azure/src/test/java/com/baeldung/springboot/azure/AzureApplicationIntegrationTest.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 AzureApplicationIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/bootique/src/test/java/com/baeldung/bootique/AppTest.java b/bootique/src/test/java/com/baeldung/bootique/AppUnitTest.java similarity index 96% rename from bootique/src/test/java/com/baeldung/bootique/AppTest.java rename to bootique/src/test/java/com/baeldung/bootique/AppUnitTest.java index 8856780ed4..2a113cd1ee 100644 --- a/bootique/src/test/java/com/baeldung/bootique/AppTest.java +++ b/bootique/src/test/java/com/baeldung/bootique/AppUnitTest.java @@ -9,7 +9,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; -public class AppTest { +public class AppUnitTest { @Rule public BQTestFactory bqTestFactory = new BQTestFactory(); diff --git a/camel-api/pom.xml b/camel-api/pom.xml index 86f6713cd6..4e50828b96 100644 --- a/camel-api/pom.xml +++ b/camel-api/pom.xml @@ -5,7 +5,6 @@ com.example spring-boot-camel 0.0.1-SNAPSHOT - Spring-Boot - Camel API com.baeldung diff --git a/cas/cas-secured-app/pom.xml b/cas/cas-secured-app/pom.xml index 1a9176ff3e..332ee912b6 100644 --- a/cas/cas-secured-app/pom.xml +++ b/cas/cas-secured-app/pom.xml @@ -12,7 +12,7 @@ org.springframework.boot spring-boot-starter-parent - 2.0.0.M7 + 1.5.13.RELEASE @@ -60,28 +60,6 @@ - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - UTF-8 UTF-8 diff --git a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java index 7faccbb125..2c88b74a83 100644 --- a/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java +++ b/cas/cas-secured-app/src/main/java/com/baeldung/cassecuredapp/controllers/AuthController.java @@ -1,7 +1,7 @@ package com.baeldung.cassecuredapp.controllers; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler; diff --git a/cas/cas-server/.factorypath b/cas/cas-server/.factorypath new file mode 100644 index 0000000000..006c761796 --- /dev/null +++ b/cas/cas-server/.factorypath @@ -0,0 +1,228 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cas/cas-server/README.md b/cas/cas-server/README.md index bae8b648e5..bacf45a2a1 100644 --- a/cas/cas-server/README.md +++ b/cas/cas-server/README.md @@ -6,10 +6,11 @@ Generic CAS WAR overlay to exercise the latest versions of CAS. This overlay cou # Versions ```xml -5.1.x +5.3.x ``` # Requirements + * JDK 1.8+ # Configuration @@ -64,20 +65,23 @@ Run the CAS web application as an executable WAR via Spring Boot. This is most u ### Warning! -Be careful with this method of deployment. `bootRun` is not designed to work with already executable WAR artifacts such that CAS server web application. YMMV. Today, uses of this mode ONLY work when there is **NO OTHER** dependency added to the build script and the `cas-server-webapp` is the only present module. See [this issue](https://github.com/apereo/cas/issues/2334) and [this issue](https://github.com/spring-projects/spring-boot/issues/8320) for more info. +Be careful with this method of deployment. `bootRun` is not designed to work with already executable WAR artifacts such that CAS server web application. YMMV. Today, uses of this mode ONLY work when there is **NO OTHER** dependency added to the build script and the `cas-server-webapp` is the only present module. See [this issue](https://github.com/spring-projects/spring-boot/issues/8320) for more info. ## Spring Boot App Server Selection -There is an app.server property in the pom.xml that can be used to select a spring boot application server. -It defaults to "-tomcat" but "-jetty" and "-undertow" are supported. -It can also be set to an empty value (nothing) if you want to deploy CAS to an external application server of your choice and you don't want the spring boot libraries included. + +There is an app.server property in the `pom.xml` that can be used to select a spring boot application server. +It defaults to `-tomcat` but `-jetty` and `-undertow` are supported. + +It can also be set to an empty value (nothing) if you want to deploy CAS to an external application server of your choice. ```xml -tomcat ``` ## Windows Build -If you are building on windows, try build.cmd instead of build.sh. Arguments are similar but for usage, run: + +If you are building on windows, try `build.cmd` instead of `build.sh`. Arguments are similar but for usage, run: ``` build.cmd help @@ -86,3 +90,12 @@ build.cmd help ## External Deploy resultant `target/cas.war` to a servlet container of choice. + + +## Command Line Shell + +Invokes the CAS Command Line Shell. For a list of commands either use no arguments or use `-h`. To enter the interactive shell use `-sh`. + +```bash +./build.sh cli +``` \ No newline at end of file diff --git a/cas/cas-server/build.cmd b/cas/cas-server/build.cmd index f907dcb388..2cf9262afe 100644 --- a/cas/cas-server/build.cmd +++ b/cas/cas-server/build.cmd @@ -23,8 +23,10 @@ @if "%1" == "bootrun" call:bootrun %2 %3 %4 @if "%1" == "debug" call:debug %2 %3 %4 @if "%1" == "run" call:run %2 %3 %4 +@if "%1" == "runalone" call:runalone %2 %3 %4 @if "%1" == "help" call:help @if "%1" == "gencert" call:gencert +@if "%1" == "cli" call:runcli %2 %3 %4 @rem function section starts here @goto:eof @@ -38,7 +40,7 @@ @goto:eof :help - @echo "Usage: build.bat [copy|clean|package|run|debug|bootrun|gencert] [optional extra args for maven]" + @echo "Usage: build.bat [copy|clean|package|run|debug|bootrun|gencert|cli] [optional extra args for maven or cli]" @echo "To get started on a clean system, run "build.bat copy" and "build.bat gencert", then "build.bat run" @echo "Note that using the copy or gencert arguments will create and/or overwrite the %CAS_DIR% which is outside this project" @goto:eof @@ -66,6 +68,10 @@ call:package %1 %2 %3 & java %JAVA_ARGS% -jar target/cas.war @goto:eof +:runalone + call:package %1 %2 %3 & target/cas.war +@goto:eof + :gencert where /q keytool if ERRORLEVEL 1 ( @@ -80,3 +86,17 @@ keytool -exportcert -alias cas -storepass changeit -keystore %CAS_DIR%\thekeystore -file %CAS_DIR%\cas.cer ) @goto:eof + +:runcli + for /f %%i in ('call %MAVEN_CMD% -q --non-recursive "-Dexec.executable=cmd" "-Dexec.args=/C echo ${cas.version}" "org.codehaus.mojo:exec-maven-plugin:1.3.1:exec"') do set CAS_VERSION=%%i + @set CAS_VERSION=%CAS_VERSION: =% + @set DOWNLOAD_DIR=target + @set COMMAND_FILE=cas-server-support-shell-%CAS_VERSION%.jar + @if not exist %DOWNLOAD_DIR% mkdir %DOWNLOAD_DIR% + @if not exist %DOWNLOAD_DIR%\%COMMAND_FILE% ( + @call mvn org.apache.maven.plugins:maven-dependency-plugin:3.0.2:get -DgroupId=org.apereo.cas -DartifactId=cas-server-support-shell -Dversion=%CAS_VERSION% -Dpackaging=jar -DartifactItem.outputDirectory=%DOWNLOAD_DIR% -DartifactItem.destFileName=%COMMAND_FILE% -DremoteRepositories=central::default::http://repo1.maven.apache.org/maven2,snapshots::::https://oss.sonatype.org/content/repositories/snapshots -Dtransitive=false + @call mvn org.apache.maven.plugins:maven-dependency-plugin:3.0.2:copy -Dmdep.useBaseVersion=true -Dartifact=org.apereo.cas:cas-server-support-shell:%CAS_VERSION%:jar -DoutputDirectory=%DOWNLOAD_DIR% + ) + @call java %JAVA_ARGS% -jar %DOWNLOAD_DIR%\%COMMAND_FILE% %1 %2 %3 + +@goto:eof \ No newline at end of file diff --git a/cas/cas-server/build.sh b/cas/cas-server/build.sh index e33f7de854..4d80aa2593 100644 --- a/cas/cas-server/build.sh +++ b/cas/cas-server/build.sh @@ -13,24 +13,31 @@ function help() { echo "Usage: build.sh [copy|clean|package|run|debug|bootrun|gencert]" echo " copy: Copy config from ./etc/cas/config to /etc/cas/config" echo " clean: Clean Maven build directory" - echo " package: Clean and build CAS war, also call copy" - echo " run: Build and run CAS.war via spring boot (java -jar target/cas.war)" + echo " package: Clean and build CAS war" + echo " run: Build and run cas.war via Java (i.e. java -jar target/cas.war)" + echo " runalone: Build and run cas.war on its own as a standalone executable (target/cas.war)" echo " debug: Run CAS.war and listen for Java debugger on port 5000" - echo " bootrun: Run with maven spring boot plugin, doesn't work with multiple dependencies" + echo " bootrun: Run with maven spring boot plugin" + echo " listviews: List all CAS views that ship with the web application and can be customized in the overlay" + echo " getview: Ask for a view name to be included in the overlay for customizations" echo " gencert: Create keystore with SSL certificate in location where CAS looks by default" + echo " cli: Run the CAS command line shell and pass commands" } function clean() { + shift ./mvnw clean "$@" } function package() { + shift ./mvnw clean package -T 5 "$@" - copy + # copy } function bootrun() { - ./mvnw clean package spring-boot:run -T 5 "$@" + shift + ./mvnw clean package spring-boot:run -P bootiful -T 5 "$@" } function debug() { @@ -41,14 +48,59 @@ function run() { package && java -jar target/cas.war } +function runalone() { + shift + ./mvnw clean package -P default,exec "$@" + chmod +x target/cas.war + target/cas.war +} + +function listviews() { + shift + explodeapp + find $PWD/target/cas -type f -name "*.html" | xargs -n 1 basename | sort | more +} + +function explodeapp() { + if [ ! -d $PWD/target/cas ];then + echo "Building the CAS web application and exploding the final war file..." + ./mvnw clean package war:exploded "$@" + fi + echo "Exploded the CAS web application file." +} + +function getview() { + shift + explodeapp + echo "Searching for view name $@..." + results=`find $PWD/target/cas -type f -name "*.html" | grep -i "$@"` + echo -e "Found view(s): \n$results" + count=`wc -w <<< "$results"` + if [ "$count" -eq 1 ];then + # echo "Found view $results to include in the overlay" + firststring="target/cas/WEB-INF/classes" + secondstring="src/main/resources" + overlayfile=`echo "${results/$firststring/$secondstring}"` + overlaypath=`dirname "${overlayfile}"` + # echo "Overlay file is $overlayfile to be created at $overlaypath" + mkdir -p $overlaypath + cp $results $overlaypath + echo "Created view at $overlayfile" + ls $overlayfile + else + echo "More than one view file is found. Narrow down the search query..." + fi +} + + function gencert() { - if [[ ! -d /etc/cas ]] ; then + if [[ ! -d /etc/cas ]] ; then copy fi which keytool if [[ $? -ne 0 ]] ; then - echo Error: Java JDK \'keytool\' is not installed or is not in the path - exit 1 + echo Error: Java JDK \'keytool\' is not installed or is not in the path + exit 1 fi # override DNAME and CERT_SUBJ_ALT_NAMES before calling or use dummy values DNAME="${DNAME:-CN=cas.example.org,OU=Example,OU=Org,C=US}" @@ -58,21 +110,49 @@ function gencert() { keytool -exportcert -alias cas -storepass changeit -keystore /etc/cas/thekeystore -file /etc/cas/cas.cer } +function cli() { + + CAS_VERSION=$(./mvnw -q -Dexec.executable="echo" -Dexec.args='${cas.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec 2>/dev/null) + # echo "CAS version: $CAS_VERSION" + JAR_FILE_NAME="cas-server-support-shell-${CAS_VERSION}.jar" + # echo "JAR name: $JAR_FILE_NAME" + JAR_PATH="org/apereo/cas/cas-server-support-shell/${CAS_VERSION}/${JAR_FILE_NAME}" + # echo "JAR path: $JAR_PATH" + + JAR_FILE_LOCAL="$HOME/.m2/repository/$JAR_PATH"; + # echo "Local JAR file path: $JAR_FILE_LOCAL"; + if [ -f "$JAR_FILE_LOCAL" ]; then + # echo "Using JAR file locally at $JAR_FILE_LOCAL" + java -jar $JAR_FILE_LOCAL "$@" + exit 0; + fi + + DOWNLOAD_DIR=./target + COMMAND_FILE="${DOWNLOAD_DIR}/${JAR_FILE_NAME}" + if [ ! -f "$COMMAND_FILE" ]; then + mkdir -p $DOWNLOAD_DIR + ./mvnw org.apache.maven.plugins:maven-dependency-plugin:3.0.2:get -DgroupId=org.apereo.cas -DartifactId=cas-server-support-shell -Dversion=$CAS_VERSION -Dpackaging=jar -DartifactItem.outputDirectory=$DOWNLOAD_DIR -DremoteRepositories=central::default::http://repo1.maven.apache.org/maven2,snapshots::::https://oss.sonatype.org/content/repositories/snapshots -Dtransitive=false + ./mvnw org.apache.maven.plugins:maven-dependency-plugin:3.0.2:copy -Dmdep.useBaseVersion=true -Dartifact=org.apereo.cas:cas-server-support-shell:$CAS_VERSION:jar -DoutputDirectory=$DOWNLOAD_DIR + fi + java -jar $COMMAND_FILE "$@" + exit 0; + +} + if [ $# -eq 0 ]; then echo -e "No commands provided. Defaulting to [run]\n" run exit 0 fi - case "$1" in "copy") - copy + copy ;; "clean") shift clean "$@" - ;; + ;; "package") shift package "$@" @@ -87,11 +167,23 @@ case "$1" in "run") run "$@" ;; +"runalone") + runalone "$@" + ;; +"listviews") + listviews "$@" + ;; "gencert") gencert "$@" ;; +"getview") + getview "$@" + ;; +"cli") + shift + cli "$@" + ;; *) help ;; esac - diff --git a/cas/cas-server/etc/cas/config/log4j2.xml b/cas/cas-server/etc/cas/config/log4j2.xml index 53b30b4228..e688cc0350 100644 --- a/cas/cas-server/etc/cas/config/log4j2.xml +++ b/cas/cas-server/etc/cas/config/log4j2.xml @@ -92,7 +92,7 @@ - + diff --git a/cas/cas-server/maven/maven-wrapper.jar b/cas/cas-server/maven/maven-wrapper.jar new file mode 100644 index 0000000000..18ba302c65 Binary files /dev/null and b/cas/cas-server/maven/maven-wrapper.jar differ diff --git a/cas/cas-server/maven/maven-wrapper.properties b/cas/cas-server/maven/maven-wrapper.properties index b368e4609a..97a946225a 100644 --- a/cas/cas-server/maven/maven-wrapper.properties +++ b/cas/cas-server/maven/maven-wrapper.properties @@ -1 +1,3 @@ -distributionUrl=https\://repository.apache.org/content/repositories/releases/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip +#Maven download properties +#Fri Dec 01 21:35:11 MST 2017 +distributionUrl=https\://repository.apache.org/content/repositories/releases/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip diff --git a/cas/cas-server/pom.xml b/cas/cas-server/pom.xml index 30e29b155f..52ddba1a68 100644 --- a/cas/cas-server/pom.xml +++ b/cas/cas-server/pom.xml @@ -7,37 +7,23 @@ cas-server war 1.0 - - - org.springframework.boot - spring-boot-starter-parent - ${org.springframework.boot.spring-boot-starter-parent.version} - - - + - org.apereo.cas - cas-server-webapp${app.server} - ${cas.version} - war - runtime - - - org.apereo.cas - cas-server-support-json-service-registry - ${cas.version} - - - org.apereo.cas - cas-server-support-jdbc - ${cas.version} - - - org.apereo.cas - cas-server-support-jdbc-drivers - ${cas.version} - + org.apereo.cas + cas-server-support-json-service-registry + ${cas.version} + + + org.apereo.cas + cas-server-support-jdbc + ${cas.version} + + + org.apereo.cas + cas-server-support-jdbc-drivers + ${cas.version} + @@ -45,7 +31,7 @@ com.rimerosolutions.maven.plugins wrapper-maven-plugin - ${wrapper-maven-plugin.version} + 0.0.4 true MD5 @@ -56,22 +42,30 @@ spring-boot-maven-plugin ${springboot.version} - org.springframework.boot.loader.WarLauncher + ${mainClassName} true + ${isExecutable} + WAR + + + + repackage + + + org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} + 2.6 cas false false false - ${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF - + ${manifestFileToUse} @@ -84,47 +78,26 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - + 3.3 cas - - - - false - - pgp - - - - com.github.s4u.plugins - pgpverify-maven-plugin - ${pgpverify-maven-plugin.version} - - - - check - - - - - hkp://pool.sks-keyservers.net - ${settings.localRepository}/pgpkeys-cache - test - true - false - - - - - - + + 5.3.0-SNAPSHOT + 1.5.13.RELEASE + + -tomcat + + org.springframework.boot.loader.WarLauncher + false + ${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF + + 1.8 + 1.8 + UTF-8 + @@ -151,25 +124,110 @@ shibboleth-releases https://build.shibboleth.net/nexus/content/repositories/releases - - spring-milestones - https://repo.spring.io/milestone - - - 5.1.4 - 1.5.3.RELEASE - - -tomcat - 1.8 - 1.8 - UTF-8 - 2.0.0.M7 - 0.0.4 - 2.6 - 3.7.0 - 1.1.0 - + + + + true + + default + + + org.apereo.cas + cas-server-webapp${app.server} + ${cas.version} + war + runtime + + + + - \ No newline at end of file + + + false + + exec + + org.apereo.cas.web.CasWebApplication + true + + + + + + com.soebes.maven.plugins + echo-maven-plugin + 0.3.0 + + + prepare-package + + echo + + + + + + Executable profile to make the generated CAS web application executable. + + + + + + + + + + false + + bootiful + + -tomcat + false + + + + org.apereo.cas + cas-server-webapp${app.server} + ${cas.version} + war + runtime + + + + + + + false + + pgp + + + + com.github.s4u.plugins + pgpverify-maven-plugin + 1.1.0 + + + + check + + + + + hkp://pool.sks-keyservers.net + ${settings.localRepository}/pgpkeys-cache + test + true + false + + + + + + + diff --git a/cas/cas-server/src/main/resources/application.properties b/cas/cas-server/src/main/resources/application.properties index 018fd351ff..7735fcabdc 100644 --- a/cas/cas-server/src/main/resources/application.properties +++ b/cas/cas-server/src/main/resources/application.properties @@ -43,7 +43,7 @@ spring.http.encoding.force=true ## #CAS CONFIG LOCATION # -cas.standalone.config=classpath:/etc/cas/config +standalone.config=classpath:/etc/cas/config ## @@ -109,7 +109,7 @@ cas.authn.jdbc.query[0].sql=SELECT * FROM users WHERE email = ? cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect cas.authn.jdbc.query[0].user=root -cas.authn.jdbc.query[0].password=root +cas.authn.jdbc.query[0].password=1234 cas.authn.jdbc.query[0].ddlAuto=none #cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver diff --git a/cas/cas-server/src/main/resources/cas.properties b/cas/cas-server/src/main/resources/cas.properties index f80f22fc11..e39d68f312 100644 --- a/cas/cas-server/src/main/resources/cas.properties +++ b/cas/cas-server/src/main/resources/cas.properties @@ -3,38 +3,7 @@ cas.server.prefix: https://localhost:643/cas cas.adminPagesSecurity.ip=127\.0\.0\.1 +logging.config: file:/etc/cas/config/log4j2.xml + cas.serviceRegistry.initFromJson=true -cas.serviceRegistry.config.location=classpath:/services - -cas.authn.accept.users= -cas.authn.accept.name= - - -#CAS Database Authentication Property - -# cas.authn.jdbc.query[0].healthQuery= -# cas.authn.jdbc.query[0].isolateInternalQueries=false -# cas.authn.jdbc.query[0].failFast=true -# cas.authn.jdbc.query[0].isolationLevelName=ISOLATION_READ_COMMITTED -# cas.authn.jdbc.query[0].leakThreshold=10 -# cas.authn.jdbc.query[0].propagationBehaviorName=PROPAGATION_REQUIRED -# cas.authn.jdbc.query[0].batchSize=1 -# cas.authn.jdbc.query[0].maxAgeDays=180 -# cas.authn.jdbc.query[0].autocommit=false -# cas.authn.jdbc.query[0].idleTimeout=5000 -# cas.authn.jdbc.query[0].credentialCriteria= -# cas.authn.jdbc.query[0].name= -# cas.authn.jdbc.query[0].order=0 -# cas.authn.jdbc.query[0].dataSourceName= -# cas.authn.jdbc.query[0].dataSourceProxy=false -# cas.authn.jdbc.query[0].fieldExpired= -# cas.authn.jdbc.query[0].fieldDisabled= -# cas.authn.jdbc.query[0].principalAttributeList=sn,cn:commonName,givenName -# cas.authn.jdbc.query[0].passwordEncoder.type=NONE|DEFAULT|STANDARD|BCRYPT|SCRYPT|PBKDF2|com.example.CustomPasswordEncoder -# cas.authn.jdbc.query[0].passwordEncoder.characterEncoding= -# cas.authn.jdbc.query[0].passwordEncoder.encodingAlgorithm= -# cas.authn.jdbc.query[0].passwordEncoder.secret= -# cas.authn.jdbc.query[0].passwordEncoder.strength=16 -# cas.authn.jdbc.query[0].principalTransformation.suffix= -# cas.authn.jdbc.query[0].principalTransformation.caseConversion=NONE|UPPERCASE|LOWERCASE -# cas.authn.jdbc.query[0].principalTransformation.prefix= \ No newline at end of file +cas.serviceRegistry.config.location=classpath:/services \ No newline at end of file diff --git a/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml b/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml index 53b30b4228..e688cc0350 100644 --- a/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml +++ b/cas/cas-server/src/main/resources/etc/cas/config/log4j2.xml @@ -92,7 +92,7 @@ - + diff --git a/cas/cas-server/src/main/resources/etc/cas/thekeystore b/cas/cas-server/src/main/resources/etc/cas/thekeystore index 86170dff16..77bf895249 100644 Binary files a/cas/cas-server/src/main/resources/etc/cas/thekeystore and b/cas/cas-server/src/main/resources/etc/cas/thekeystore differ diff --git a/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt b/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt index 5bd9d5baba..12ef688a08 100644 Binary files a/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt and b/cas/cas-server/src/main/resources/etc/cas/thekeystore.crt differ diff --git a/cas/cas-server/src/main/resources/log4j2.xml b/cas/cas-server/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..e688cc0350 --- /dev/null +++ b/cas/cas-server/src/main/resources/log4j2.xml @@ -0,0 +1,117 @@ + + + + + + . + + warn + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cas/cas-server/src/main/resources/services/casSecuredApp.json b/cas/cas-server/src/main/resources/services/casSecuredApp-19991.json similarity index 100% rename from cas/cas-server/src/main/resources/services/casSecuredApp.json rename to cas/cas-server/src/main/resources/services/casSecuredApp-19991.json diff --git a/cdi/pom.xml b/cdi/pom.xml index 00cc96a7ed..1d14e3c267 100644 --- a/cdi/pom.xml +++ b/cdi/pom.xml @@ -8,12 +8,30 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 + + org.hamcrest + hamcrest-core + 1.3 + test + + + org.assertj + assertj-core + 3.10.0 + test + + + junit + junit + 4.12 + test + org.springframework spring-context @@ -38,9 +56,8 @@ - 4.3.4.RELEASE 1.8.9 2.4.1.Final - \ No newline at end of file + diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/application/FileApplication.java b/cdi/src/main/java/com/baeldung/dependencyinjection/application/FileApplication.java new file mode 100644 index 0000000000..2ae8ac9621 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/application/FileApplication.java @@ -0,0 +1,18 @@ +package com.baeldung.dependencyinjection.application; + +import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor; +import org.jboss.weld.environment.se.Weld; +import org.jboss.weld.environment.se.WeldContainer; + +public class FileApplication { + + public static void main(String[] args) { + Weld weld = new Weld(); + WeldContainer container = weld.initialize(); + ImageFileProcessor imageFileProcessor = container.select(ImageFileProcessor.class).get(); + System.out.println(imageFileProcessor.openFile("file1.png")); + System.out.println(imageFileProcessor.writeFile("file1.png")); + System.out.println(imageFileProcessor.saveFile("file1.png")); + container.shutdown(); + } +} \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/factories/TimeLoggerFactory.java b/cdi/src/main/java/com/baeldung/dependencyinjection/factories/TimeLoggerFactory.java new file mode 100644 index 0000000000..86916fa8c4 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/factories/TimeLoggerFactory.java @@ -0,0 +1,14 @@ +package com.baeldung.dependencyinjection.factories; + +import com.baeldung.dependencyinjection.loggers.TimeLogger; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import javax.enterprise.inject.Produces; + +public class TimeLoggerFactory { + + @Produces + public TimeLogger getTimeLogger() { + return new TimeLogger(new SimpleDateFormat("HH:mm"), Calendar.getInstance()); + } +} \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/GifFileEditor.java b/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/GifFileEditor.java new file mode 100644 index 0000000000..6b51d64a33 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/GifFileEditor.java @@ -0,0 +1,27 @@ +package com.baeldung.dependencyinjection.imagefileeditors; + +import com.baeldung.dependencyinjection.qualifiers.GifFileEditorQualifier; + +@GifFileEditorQualifier +public class GifFileEditor implements ImageFileEditor { + + @Override + public String openFile(String fileName) { + return "Opening GIF file " + fileName; + } + + @Override + public String editFile(String fileName) { + return "Editing GIF file " + fileName; + } + + @Override + public String writeFile(String fileName) { + return "Writing GIF file " + fileName; + } + + @Override + public String saveFile(String fileName) { + return "Saving GIF file " + fileName; + } +} \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/ImageFileEditor.java b/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/ImageFileEditor.java new file mode 100644 index 0000000000..d524a5160a --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/ImageFileEditor.java @@ -0,0 +1,12 @@ +package com.baeldung.dependencyinjection.imagefileeditors; + +public interface ImageFileEditor { + + String openFile(String fileName); + + String editFile(String fileName); + + String writeFile(String fileName); + + String saveFile(String fileName); +} \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/JpgFileEditor.java b/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/JpgFileEditor.java new file mode 100644 index 0000000000..97adebc1af --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/JpgFileEditor.java @@ -0,0 +1,27 @@ +package com.baeldung.dependencyinjection.imagefileeditors; + +import com.baeldung.dependencyinjection.qualifiers.JpgFileEditorQualifier; + +@JpgFileEditorQualifier +public class JpgFileEditor implements ImageFileEditor { + + @Override + public String openFile(String fileName) { + return "Opening JPG file " + fileName; + } + + @Override + public String editFile(String fileName) { + return "Editing JPG file " + fileName; + } + + @Override + public String writeFile(String fileName) { + return "Writing JPG file " + fileName; + } + + @Override + public String saveFile(String fileName) { + return "Saving JPG file " + fileName; + } +} \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/PngFileEditor.java b/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/PngFileEditor.java new file mode 100644 index 0000000000..5db608539c --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/imagefileeditors/PngFileEditor.java @@ -0,0 +1,27 @@ +package com.baeldung.dependencyinjection.imagefileeditors; + +import com.baeldung.dependencyinjection.qualifiers.PngFileEditorQualifier; + +@PngFileEditorQualifier +public class PngFileEditor implements ImageFileEditor { + + @Override + public String openFile(String fileName) { + return "Opening PNG file " + fileName; + } + + @Override + public String editFile(String fileName) { + return "Editing PNG file " + fileName; + } + + @Override + public String writeFile(String fileName) { + return "Writing PNG file " + fileName; + } + + @Override + public String saveFile(String fileName) { + return "Saving PNG file " + fileName; + } +} \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/imageprocessors/ImageFileProcessor.java b/cdi/src/main/java/com/baeldung/dependencyinjection/imageprocessors/ImageFileProcessor.java new file mode 100644 index 0000000000..1527108568 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/imageprocessors/ImageFileProcessor.java @@ -0,0 +1,42 @@ +package com.baeldung.dependencyinjection.imageprocessors; + +import com.baeldung.dependencyinjection.loggers.TimeLogger; +import com.baeldung.dependencyinjection.qualifiers.PngFileEditorQualifier; +import javax.inject.Inject; +import com.baeldung.dependencyinjection.imagefileeditors.ImageFileEditor; + +public class ImageFileProcessor { + + private final ImageFileEditor imageFileEditor; + private final TimeLogger timeLogger; + + @Inject + public ImageFileProcessor(@PngFileEditorQualifier ImageFileEditor imageFileEditor, TimeLogger timeLogger) { + this.imageFileEditor = imageFileEditor; + this.timeLogger = timeLogger; + } + + public ImageFileEditor getImageFileditor() { + return imageFileEditor; + } + + public TimeLogger getTimeLogger() { + return timeLogger; + } + + public String openFile(String fileName) { + return imageFileEditor.openFile(fileName) + " at: " + timeLogger.getTime(); + } + + public String editFile(String fileName) { + return imageFileEditor.editFile(fileName) + " at: " + timeLogger.getTime(); + } + + public String writeFile(String fileName) { + return imageFileEditor.writeFile(fileName) + " at: " + timeLogger.getTime(); + } + + public String saveFile(String fileName) { + return imageFileEditor.saveFile(fileName)+ " at: " + timeLogger.getTime(); + } +} \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/loggers/TimeLogger.java b/cdi/src/main/java/com/baeldung/dependencyinjection/loggers/TimeLogger.java new file mode 100644 index 0000000000..44223d7e5d --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/loggers/TimeLogger.java @@ -0,0 +1,19 @@ +package com.baeldung.dependencyinjection.loggers; + +import java.text.SimpleDateFormat; +import java.util.Calendar; + +public class TimeLogger { + + private final SimpleDateFormat dateFormat; + private final Calendar calendar; + + public TimeLogger(SimpleDateFormat dateFormat, Calendar calendar) { + this.dateFormat = dateFormat; + this.calendar = calendar; + } + + public String getTime() { + return dateFormat.format(calendar.getTime()); + } +} \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/qualifiers/GifFileEditorQualifier.java b/cdi/src/main/java/com/baeldung/dependencyinjection/qualifiers/GifFileEditorQualifier.java new file mode 100644 index 0000000000..3660aad15e --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/qualifiers/GifFileEditorQualifier.java @@ -0,0 +1,12 @@ +package com.baeldung.dependencyinjection.qualifiers; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import javax.inject.Qualifier; + +@Qualifier +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER}) +public @interface GifFileEditorQualifier {} \ No newline at end of file diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/qualifiers/JpgFileEditorQualifier.java b/cdi/src/main/java/com/baeldung/dependencyinjection/qualifiers/JpgFileEditorQualifier.java new file mode 100644 index 0000000000..c8a007bcab --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/qualifiers/JpgFileEditorQualifier.java @@ -0,0 +1,12 @@ +package com.baeldung.dependencyinjection.qualifiers; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import javax.inject.Qualifier; + +@Qualifier +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER}) +public @interface JpgFileEditorQualifier {} diff --git a/cdi/src/main/java/com/baeldung/dependencyinjection/qualifiers/PngFileEditorQualifier.java b/cdi/src/main/java/com/baeldung/dependencyinjection/qualifiers/PngFileEditorQualifier.java new file mode 100644 index 0000000000..51d2fba315 --- /dev/null +++ b/cdi/src/main/java/com/baeldung/dependencyinjection/qualifiers/PngFileEditorQualifier.java @@ -0,0 +1,12 @@ +package com.baeldung.dependencyinjection.qualifiers; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import javax.inject.Qualifier; + +@Qualifier +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER}) +public @interface PngFileEditorQualifier {} diff --git a/cdi/src/test/java/com/baeldung/test/dependencyinjection/GifFileEditorUnitTest.java b/cdi/src/test/java/com/baeldung/test/dependencyinjection/GifFileEditorUnitTest.java new file mode 100644 index 0000000000..3b148049b5 --- /dev/null +++ b/cdi/src/test/java/com/baeldung/test/dependencyinjection/GifFileEditorUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.test.dependencyinjection; + +import com.baeldung.dependencyinjection.imagefileeditors.GifFileEditor; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +public class GifFileEditorUnitTest { + + private static GifFileEditor gifFileEditor; + + + @BeforeClass + public static void setGifFileEditorInstance() { + gifFileEditor = new GifFileEditor(); + } + + @Test + public void givenGifFileEditorlInstance_whenCalledopenFile_thenOneAssertion() { + assertThat(gifFileEditor.openFile("file1.gif")).isEqualTo("Opening GIF file file1.gif"); + } + + @Test + public void givenGifFileEditorlInstance_whenCallededitFile_thenOneAssertion() { + assertThat(gifFileEditor.editFile("file1.gif")).isEqualTo("Editing GIF file file1.gif"); + } + + @Test + public void givenGifFileEditorInstance_whenCalledwriteFile_thenOneAssertion() { + assertThat(gifFileEditor.writeFile("file1.gif")).isEqualTo("Writing GIF file file1.gif"); + } + + @Test + public void givenGifFileEditorInstance_whenCalledsaveFile_thenOneAssertion() { + assertThat(gifFileEditor.saveFile("file1.gif")).isEqualTo("Saving GIF file file1.gif"); + } +} \ No newline at end of file diff --git a/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java b/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java new file mode 100644 index 0000000000..8b5fa409c9 --- /dev/null +++ b/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.test.dependencyinjection; + +import com.baeldung.dependencyinjection.imagefileeditors.GifFileEditor; +import com.baeldung.dependencyinjection.imagefileeditors.JpgFileEditor; +import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor; +import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor; +import com.baeldung.dependencyinjection.loggers.TimeLogger; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import static org.assertj.core.api.Assertions.assertThat; +import org.jboss.weld.environment.se.Weld; +import org.jboss.weld.environment.se.WeldContainer; +import org.junit.BeforeClass; +import org.junit.Test; + +public class ImageProcessorUnitTest { + + private static ImageFileProcessor imageFileProcessor; + private static SimpleDateFormat dateFormat; + private static Calendar calendar; + + + @BeforeClass + public static void setImageProcessorInstance() { + Weld weld = new Weld(); + WeldContainer container = weld.initialize(); + imageFileProcessor = container.select(ImageFileProcessor.class).get(); + container.shutdown(); + } + + @BeforeClass + public static void setSimpleDateFormatInstance() { + dateFormat = new SimpleDateFormat("HH:mm"); + } + + @BeforeClass + public static void setCalendarInstance() { + calendar = Calendar.getInstance(); + } + + @Test + public void givenImageProcessorInstance_whenInjectedPngFileEditorandTimeLoggerInstances_thenTwoAssertions() { + assertThat(imageFileProcessor.getImageFileditor()).isInstanceOf(PngFileEditor.class); + assertThat(imageFileProcessor.getTimeLogger()).isInstanceOf(TimeLogger.class); + } + + @Test + public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() { + String currentTime = dateFormat.format(calendar.getTime()); + assertThat(imageFileProcessor.openFile("file1.png")).isEqualTo("Opening PNG file file1.png at: " + currentTime); + } + + @Test + public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() { + String currentTime = dateFormat.format(calendar.getTime()); + assertThat(imageFileProcessor.editFile("file1.png")).isEqualTo("Editing PNG file file1.png at: " + currentTime); + } + + @Test + public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() { + String currentTime = dateFormat.format(calendar.getTime()); + assertThat(imageFileProcessor.writeFile("file1.png")).isEqualTo("Writing PNG file file1.png at: " + currentTime); + } + + @Test + public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() { + String currentTime = dateFormat.format(calendar.getTime()); + assertThat(imageFileProcessor.saveFile("file1.png")).isEqualTo("Saving PNG file file1.png at: " + currentTime); + } +} \ No newline at end of file diff --git a/cdi/src/test/java/com/baeldung/test/dependencyinjection/JpgFileEditorUnitTest.java b/cdi/src/test/java/com/baeldung/test/dependencyinjection/JpgFileEditorUnitTest.java new file mode 100644 index 0000000000..4f3954c0bc --- /dev/null +++ b/cdi/src/test/java/com/baeldung/test/dependencyinjection/JpgFileEditorUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.test.dependencyinjection; + +import com.baeldung.dependencyinjection.imagefileeditors.JpgFileEditor; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +public class JpgFileEditorUnitTest { + + private static JpgFileEditor jpgFileUtil; + + + @BeforeClass + public static void setJpgFileEditorInstance() { + jpgFileUtil = new JpgFileEditor(); + } + + @Test + public void givenJpgFileEditorInstance_whenCalledopenFile_thenOneAssertion() { + assertThat(jpgFileUtil.openFile("file1.jpg")).isEqualTo("Opening JPG file file1.jpg"); + } + + @Test + public void givenJpgFileEditorlInstance_whenCallededitFile_thenOneAssertion() { + assertThat(jpgFileUtil.editFile("file1.gif")).isEqualTo("Editing JPG file file1.gif"); + } + + @Test + public void givenJpgFileEditorInstance_whenCalledwriteFile_thenOneAssertion() { + assertThat(jpgFileUtil.writeFile("file1.jpg")).isEqualTo("Writing JPG file file1.jpg"); + } + + @Test + public void givenJpgFileEditorInstance_whenCalledsaveFile_thenOneAssertion() { + assertThat(jpgFileUtil.saveFile("file1.jpg")).isEqualTo("Saving JPG file file1.jpg"); + } +} \ No newline at end of file diff --git a/cdi/src/test/java/com/baeldung/test/dependencyinjection/PngFileEditorUnitTest.java b/cdi/src/test/java/com/baeldung/test/dependencyinjection/PngFileEditorUnitTest.java new file mode 100644 index 0000000000..d16f6d576e --- /dev/null +++ b/cdi/src/test/java/com/baeldung/test/dependencyinjection/PngFileEditorUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.test.dependencyinjection; + +import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor; +import com.baeldung.dependencyinjection.qualifiers.PngFileEditorQualifier; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +@PngFileEditorQualifier +public class PngFileEditorUnitTest { + + private static PngFileEditor pngFileEditor; + + + @BeforeClass + public static void setPngFileEditorInstance() { + pngFileEditor = new PngFileEditor(); + } + + @Test + public void givenPngFileEditorInstance_whenCalledopenFile_thenOneAssertion() { + assertThat(pngFileEditor.openFile("file1.png")).isEqualTo("Opening PNG file file1.png"); + } + + @Test + public void givenPngFileEditorInstance_whenCallededitFile_thenOneAssertion() { + assertThat(pngFileEditor.editFile("file1.png")).isEqualTo("Editing PNG file file1.png"); + } + + @Test + public void givenPngFileEditorInstance_whenCalledwriteFile_thenOneAssertion() { + assertThat(pngFileEditor.writeFile("file1.png")).isEqualTo("Writing PNG file file1.png"); + } + + @Test + public void givenPngFileEditorInstance_whenCalledsaveFile_thenOneAssertion() { + assertThat(pngFileEditor.saveFile("file1.png")).isEqualTo("Saving PNG file file1.png"); + } +} diff --git a/cdi/src/test/java/com/baeldung/test/dependencyinjection/TimeLoggerFactoryUnitTest.java b/cdi/src/test/java/com/baeldung/test/dependencyinjection/TimeLoggerFactoryUnitTest.java new file mode 100644 index 0000000000..caf2ed32b5 --- /dev/null +++ b/cdi/src/test/java/com/baeldung/test/dependencyinjection/TimeLoggerFactoryUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.test.dependencyinjection; + +import com.baeldung.dependencyinjection.factories.TimeLoggerFactory; +import com.baeldung.dependencyinjection.loggers.TimeLogger; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class TimeLoggerFactoryUnitTest { + + @Test + public void givenTimeLoggerFactory_whenCalledgetTimeLogger_thenOneAssertion() { + TimeLoggerFactory timeLoggerFactory = new TimeLoggerFactory(); + assertThat(timeLoggerFactory.getTimeLogger()).isInstanceOf(TimeLogger.class); + } +} diff --git a/cdi/src/test/java/com/baeldung/test/dependencyinjection/TimeLoggerUnitTest.java b/cdi/src/test/java/com/baeldung/test/dependencyinjection/TimeLoggerUnitTest.java new file mode 100644 index 0000000000..222de251fe --- /dev/null +++ b/cdi/src/test/java/com/baeldung/test/dependencyinjection/TimeLoggerUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.test.dependencyinjection; + +import com.baeldung.dependencyinjection.loggers.TimeLogger; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.Test; + +public class TimeLoggerUnitTest { + + + @Test + public void givenTimeLoggerInstance_whenCalledgetLogTime_thenOneAssertion() { + SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm"); + Calendar calendar = Calendar.getInstance(); + TimeLogger timeLogger = new TimeLogger(dateFormat, calendar); + String currentTime = dateFormat.format(calendar.getTime()); + assertThat(timeLogger.getTime()).isEqualTo(currentTime); + } +} \ No newline at end of file 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..aa6110b7b1 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -50,4 +50,7 @@ - [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) +- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection) +- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic) diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index aab349781a..20db1e1146 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -195,6 +195,16 @@ + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + -parameters + + org.springframework.boot spring-boot-maven-plugin diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java index 0d727cf0b5..b380c04fc2 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java +++ b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java @@ -3,6 +3,7 @@ package com.baeldung.datetime; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.LocalTime; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalAdjusters; @@ -43,4 +44,30 @@ class UseLocalDate { LocalDateTime startofDay = localDate.atStartOfDay(); return startofDay; } + + LocalDateTime getStartOfDayOfLocalDate(LocalDate localDate) { + LocalDateTime startofDay = LocalDateTime.of(localDate, LocalTime.MIDNIGHT); + return startofDay; + } + + LocalDateTime getStartOfDayAtMinTime(LocalDate localDate) { + LocalDateTime startofDay = localDate.atTime(LocalTime.MIN); + return startofDay; + } + + LocalDateTime getStartOfDayAtMidnightTime(LocalDate localDate) { + LocalDateTime startofDay = localDate.atTime(LocalTime.MIDNIGHT); + return startofDay; + } + + LocalDateTime getEndOfDay(LocalDate localDate) { + LocalDateTime endOfDay = localDate.atTime(LocalTime.MAX); + return endOfDay; + } + + LocalDateTime getEndOfDayFromLocalTime(LocalDate localDate) { + LocalDateTime endOfDate = LocalTime.MAX.atDate(localDate); + return endOfDate; + } + } diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java index 7f39ac2f91..b2ff11ba16 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java +++ b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java @@ -1,6 +1,8 @@ package com.baeldung.datetime; import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.temporal.ChronoField; public class UseLocalDateTime { @@ -8,4 +10,15 @@ public class UseLocalDateTime { return LocalDateTime.parse(representation); } + LocalDateTime getEndOfDayFromLocalDateTimeDirectly(LocalDateTime localDateTime) { + LocalDateTime endOfDate = localDateTime.with(ChronoField.NANO_OF_DAY, LocalTime.MAX.toNanoOfDay()); + return endOfDate; + } + + LocalDateTime getEndOfDayFromLocalDateTime(LocalDateTime localDateTime) { + LocalDateTime endOfDate = localDateTime.toLocalDate() + .atTime(LocalTime.MAX); + return endOfDate; + } + } diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java b/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java index f5e1af0a06..505bfa741f 100644 --- a/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java +++ b/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java @@ -1,12 +1,42 @@ package com.baeldung.datetime; +import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; +import java.time.temporal.ChronoField; class UseZonedDateTime { ZonedDateTime getZonedDateTime(LocalDateTime localDateTime, ZoneId zoneId) { return ZonedDateTime.of(localDateTime, zoneId); } + + ZonedDateTime getStartOfDay(LocalDate localDate, ZoneId zone) { + ZonedDateTime startofDay = localDate.atStartOfDay() + .atZone(zone); + return startofDay; + } + + ZonedDateTime getStartOfDayShorthand(LocalDate localDate, ZoneId zone) { + ZonedDateTime startofDay = localDate.atStartOfDay(zone); + return startofDay; + } + + ZonedDateTime getStartOfDayFromZonedDateTime(ZonedDateTime zonedDateTime) { + ZonedDateTime startofDay = zonedDateTime.toLocalDateTime() + .toLocalDate() + .atStartOfDay(zonedDateTime.getZone()); + return startofDay; + } + + ZonedDateTime getStartOfDayAtMinTime(ZonedDateTime zonedDateTime) { + ZonedDateTime startofDay = zonedDateTime.with(ChronoField.HOUR_OF_DAY, 0); + return startofDay; + } + + ZonedDateTime getStartOfDayAtMidnightTime(ZonedDateTime zonedDateTime) { + ZonedDateTime startofDay = zonedDateTime.with(ChronoField.NANO_OF_DAY, 0); + return startofDay; + } } diff --git a/core-java-8/src/main/java/com/baeldung/hashtable/Word.java b/core-java-8/src/main/java/com/baeldung/hashtable/Word.java new file mode 100644 index 0000000000..eb7c5b7dca --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/hashtable/Word.java @@ -0,0 +1,28 @@ +package com.baeldung.hashtable; + +public class Word { + private String name; + + public Word(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public boolean equals(Object o) { + if (o == this) + return true; + if (!(o instanceof Word)) + return false; + + Word word = (Word) o; + return word.getName().equals(this.name) ? true : false; + + } + + public int hashCode() { + return name.hashCode(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/optional/OrElseAndOrElseGet.java b/core-java-8/src/main/java/com/baeldung/optional/OrElseAndOrElseGet.java new file mode 100644 index 0000000000..d4d07291d5 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/optional/OrElseAndOrElseGet.java @@ -0,0 +1,34 @@ +package com.baeldung.optional; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.Random; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class OrElseAndOrElseGet { + + public static List names = Arrays.asList("John", "Jones", "Kelly", "Cristina", "Raven"); + + private static final Logger LOG = LoggerFactory.getLogger(OrElseAndOrElseGet.class); + + public String getRandomName() { + LOG.info("getRandomName() method - start"); + Random random = new Random(); + int index = random.nextInt(5); + LOG.info("getRandomName() method - end"); + return names.get(index); + } + + public String getNameUsingOrElse(String name) { + return Optional.ofNullable(name) + .orElse(getRandomName()); + } + + public String getNameUsingOrElseGet(String name) { + return Optional.ofNullable(name) + .orElseGet(() -> getRandomName()); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/optional/OrElseAndOrElseGetBenchmarkRunner.java b/core-java-8/src/main/java/com/baeldung/optional/OrElseAndOrElseGetBenchmarkRunner.java new file mode 100644 index 0000000000..8bf0b0b25d --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/optional/OrElseAndOrElseGetBenchmarkRunner.java @@ -0,0 +1,37 @@ +package com.baeldung.optional; + +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.runner.RunnerException; + +@Fork(1) +@State(Scope.Benchmark) +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +public class OrElseAndOrElseGetBenchmarkRunner { + + private OrElseAndOrElseGet orElsevsOrElseGet = new OrElseAndOrElseGet(); + + public static void main(String[] args) throws RunnerException, IOException { + org.openjdk.jmh.Main.main(args); + } + + @Benchmark + public String orElseBenchmark() { + return orElsevsOrElseGet.getNameUsingOrElse("baeldung"); + } + + @Benchmark + public String orElseGetBenchmark() { + return orElsevsOrElseGet.getNameUsingOrElseGet("baeldung"); + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/reflect/Person.java b/core-java-8/src/main/java/com/baeldung/reflect/Person.java new file mode 100644 index 0000000000..fba25aca8b --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/reflect/Person.java @@ -0,0 +1,18 @@ +package com.baeldung.reflect; + +public class Person { + + private String fullName; + + public Person(String fullName) { + this.fullName = fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getFullName() { + return fullName; + } +} diff --git a/core-java-8/src/test/java/com/baeldung/counter/CounterTest.java b/core-java-8/src/test/java/com/baeldung/counter/CounterUnitTest.java similarity index 94% rename from core-java-8/src/test/java/com/baeldung/counter/CounterTest.java rename to core-java-8/src/test/java/com/baeldung/counter/CounterUnitTest.java index 657b510452..ef57fc2c6e 100644 --- a/core-java-8/src/test/java/com/baeldung/counter/CounterTest.java +++ b/core-java-8/src/test/java/com/baeldung/counter/CounterUnitTest.java @@ -9,7 +9,7 @@ import org.junit.Test; import com.baeldung.counter.CounterUtil.MutableInteger; -public class CounterTest { +public class CounterUnitTest { @Test public void whenMapWithWrapperAsCounter_runsSuccessfully() { diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java index 6fb6d21b19..5709fc7209 100644 --- a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java @@ -1,13 +1,15 @@ package com.baeldung.datetime; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; + import java.time.LocalDate; +import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Month; import org.junit.Test; -import static org.junit.Assert.assertEquals; - public class UseLocalDateTimeUnitTest { UseLocalDateTime useLocalDateTime = new UseLocalDateTime(); @@ -19,4 +21,16 @@ public class UseLocalDateTimeUnitTest { assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30") .toLocalTime()); } + + @Test + public void givenLocalDateTime_whenSettingEndOfDay_thenReturnLastMomentOfDay() { + LocalDateTime givenTimed = LocalDateTime.parse("2018-06-23T05:55:55"); + + LocalDateTime endOfDayFromGivenDirectly = useLocalDateTime.getEndOfDayFromLocalDateTimeDirectly(givenTimed); + LocalDateTime endOfDayFromGiven = useLocalDateTime.getEndOfDayFromLocalDateTime(givenTimed); + + assertThat(endOfDayFromGivenDirectly).isEqualTo(endOfDayFromGiven); + assertThat(endOfDayFromGivenDirectly.toLocalTime()).isEqualTo(LocalTime.MAX); + assertThat(endOfDayFromGivenDirectly.toString()).isEqualTo("2018-06-23T23:59:59.999999999"); + } } diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java index 834179febd..bb9b60956d 100644 --- a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java @@ -1,13 +1,15 @@ package com.baeldung.datetime; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; + import java.time.DayOfWeek; import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.LocalTime; import org.junit.Test; -import static org.junit.Assert.assertEquals; - public class UseLocalDateUnitTest { UseLocalDate useLocalDate = new UseLocalDate(); @@ -57,4 +59,33 @@ public class UseLocalDateUnitTest { assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22"))); } + @Test + public void givenLocalDate_whenSettingStartOfDay_thenReturnMidnightInAllCases() { + LocalDate given = LocalDate.parse("2018-06-23"); + + LocalDateTime startOfDayWithMethod = useLocalDate.getStartOfDay(given); + LocalDateTime startOfDayOfLocalDate = useLocalDate.getStartOfDayOfLocalDate(given); + LocalDateTime startOfDayWithMin = useLocalDate.getStartOfDayAtMinTime(given); + LocalDateTime startOfDayWithMidnight = useLocalDate.getStartOfDayAtMidnightTime(given); + + assertThat(startOfDayWithMethod).isEqualTo(startOfDayWithMin) + .isEqualTo(startOfDayWithMidnight) + .isEqualTo(startOfDayOfLocalDate) + .isEqualTo(LocalDateTime.parse("2018-06-23T00:00:00")); + assertThat(startOfDayWithMin.toLocalTime()).isEqualTo(LocalTime.MIDNIGHT); + assertThat(startOfDayWithMin.toString()).isEqualTo("2018-06-23T00:00"); + } + + @Test + public void givenLocalDate_whenSettingEndOfDay_thenReturnLastMomentOfDay() { + LocalDate given = LocalDate.parse("2018-06-23"); + + LocalDateTime endOfDayWithMax = useLocalDate.getEndOfDay(given); + LocalDateTime endOfDayFromLocalTime = useLocalDate.getEndOfDayFromLocalTime(given); + + assertThat(endOfDayWithMax).isEqualTo(endOfDayFromLocalTime); + assertThat(endOfDayWithMax.toLocalTime()).isEqualTo(LocalTime.MAX); + assertThat(endOfDayWithMax.toString()).isEqualTo("2018-06-23T23:59:59.999999999"); + } + } diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java index 5fb079b94c..f9b4008888 100644 --- a/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java @@ -1,6 +1,10 @@ package com.baeldung.datetime; +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.LocalTime; import java.time.ZoneId; import java.time.ZonedDateTime; @@ -17,4 +21,25 @@ public class UseZonedDateTimeUnitTest { ZonedDateTime zonedDatetime = zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId); Assert.assertEquals(zoneId, ZoneId.from(zonedDatetime)); } + + @Test + public void givenLocalDateOrZoned_whenSettingStartOfDay_thenReturnMidnightInAllCases() { + LocalDate given = LocalDate.parse("2018-06-23"); + ZoneId zone = ZoneId.of("Europe/Paris"); + ZonedDateTime zonedGiven = ZonedDateTime.of(given, LocalTime.NOON, zone); + + ZonedDateTime startOfOfDayWithMethod = zonedDateTime.getStartOfDay(given, zone); + ZonedDateTime startOfOfDayWithShorthandMethod = zonedDateTime.getStartOfDayShorthand(given, zone); + ZonedDateTime startOfOfDayFromZonedDateTime = zonedDateTime.getStartOfDayFromZonedDateTime(zonedGiven); + ZonedDateTime startOfOfDayAtMinTime = zonedDateTime.getStartOfDayAtMinTime(zonedGiven); + ZonedDateTime startOfOfDayAtMidnightTime = zonedDateTime.getStartOfDayAtMidnightTime(zonedGiven); + + assertThat(startOfOfDayWithMethod).isEqualTo(startOfOfDayWithShorthandMethod) + .isEqualTo(startOfOfDayFromZonedDateTime) + .isEqualTo(startOfOfDayAtMinTime) + .isEqualTo(startOfOfDayAtMidnightTime); + assertThat(startOfOfDayWithMethod.toLocalTime()).isEqualTo(LocalTime.MIDNIGHT); + assertThat(startOfOfDayWithMethod.toLocalTime() + .toString()).isEqualTo("00:00"); + } } 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 new file mode 100644 index 0000000000..8d30596ab4 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java @@ -0,0 +1,274 @@ +package com.baeldung.hashtable; + +import java.util.ConcurrentModificationException; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.Map; + +import static org.junit.Assert.*; +import static org.hamcrest.Matchers.*; +import org.junit.Test; + +public class HashtableUnitTest { + + @Test + public void whenPutAndGet_thenReturnsValue() { + Hashtable table = new Hashtable(); + + Word word = new Word("cat"); + table.put(word, "an animal"); + + String definition = table.get(word); + + assertEquals("an animal", definition); + + definition = table.remove(word); + + assertEquals("an animal", definition); + } + + @Test + public void whenThesameInstanceOfKey_thenReturnsValue() { + Hashtable table = new Hashtable(); + Word word = new Word("cat"); + table.put(word, "an animal"); + String extracted = table.get(word); + assertEquals("an animal", extracted); + } + + @Test + public void whenEqualsOverridden_thenReturnsValue() { + Hashtable table = new Hashtable(); + Word word = new Word("cat"); + table.put(word, "an animal"); + String extracted = table.get(new Word("cat")); + assertEquals("an animal", extracted); + } + + @Test(expected = NullPointerException.class) + public void whenNullKey_thenException() { + Hashtable table = new Hashtable(); + table.put(null, "an animal"); + } + + @Test(expected = ConcurrentModificationException.class) + public void whenIterate_thenFailFast() { + + Hashtable table = new Hashtable(); + table.put(new Word("cat"), "an animal"); + table.put(new Word("dog"), "another animal"); + + Iterator it = table.keySet().iterator(); + System.out.println("iterator created"); + + table.remove(new Word("dog")); + System.out.println("element removed"); + + while (it.hasNext()) { + Word key = it.next(); + System.out.println(table.get(key)); + } + } + + @Test + public void whenEnumerate_thenNotFailFast() { + + Hashtable table = new Hashtable(); + table.put(new Word("1"), "one"); + table.put(new Word("2"), "two"); + table.put(new Word("3"), "three"); + table.put(new Word("4"), "four"); + table.put(new Word("5"), "five"); + table.put(new Word("6"), "six"); + table.put(new Word("7"), "seven"); + table.put(new Word("8"), "eight"); + + Enumeration enumKey = table.keys(); + System.out.println("Enumeration created"); + table.remove(new Word("1")); + System.out.println("element removed"); + while (enumKey.hasMoreElements()) { + Word key = enumKey.nextElement(); + System.out.println(table.get(key)); + } + } + + @Test + public void whenAddElements_thenIterationOrderUnpredicable() { + + Hashtable table = new Hashtable(); + table.put(new Word("1"), "one"); + table.put(new Word("2"), "two"); + table.put(new Word("3"), "three"); + table.put(new Word("4"), "four"); + table.put(new Word("5"), "five"); + table.put(new Word("6"), "six"); + table.put(new Word("7"), "seven"); + table.put(new Word("8"), "eight"); + + Iterator> it = table.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry entry = it.next(); + System.out.println(entry.getValue()); + } + } + + @Test + public void whenGetOrDefault_thenDefaultGot() { + + Hashtable table = new Hashtable(); + table.put(new Word("cat"), "a small domesticated carnivorous mammal"); + Word key = new Word("dog"); + String definition; + + // old way + /* if (table.containsKey(key)) { + definition = table.get(key); + } else { + definition = "not found"; + }*/ + + // new way + definition = table.getOrDefault(key, "not found"); + + assertThat(definition, is("not found")); + } + + @Test + public void whenPutifAbsent_thenNotRewritten() { + + Hashtable table = new Hashtable(); + table.put(new Word("cat"), "a small domesticated carnivorous mammal"); + + String definition = "an animal"; + // old way + /* if (!table.containsKey(new Word("cat"))) { + table.put(new Word("cat"), definition); + }*/ + // new way + table.putIfAbsent(new Word("cat"), definition); + + assertThat(table.get(new Word("cat")), is("a small domesticated carnivorous mammal")); + } + + @Test + public void whenRemovePair_thenCheckKeyAndValue() { + + Hashtable table = new Hashtable(); + table.put(new Word("cat"), "a small domesticated carnivorous mammal"); + + // old way + /* if (table.get(new Word("cat")).equals("an animal")) { + table.remove(new Word("cat")); + }*/ + + // new way + boolean result = table.remove(new Word("cat"), "an animal"); + + assertThat(result, is(false)); + } + + @Test + public void whenReplacePair_thenValueChecked() { + + Hashtable table = new Hashtable(); + table.put(new Word("cat"), "a small domesticated carnivorous mammal"); + + String definition = "an animal"; + + // old way + /* if (table.containsKey(new Word("cat")) && table.get(new Word("cat")).equals("a small domesticated carnivorous mammal")) { + table.put(new Word("cat"), definition); + }*/ + // new way + table.replace(new Word("cat"), "a small domesticated carnivorous mammal", definition); + + assertThat(table.get(new Word("cat")), is("an animal")); + + } + + @Test + public void whenKeyIsAbsent_thenNotRewritten() { + + Hashtable table = new Hashtable(); + table.put(new Word("cat"), "a small domesticated carnivorous mammal"); + + // old way + /* if (!table.containsKey(cat)) { + String definition = "an animal";// calculate + table.put(new Word("cat"), definition); + } + */ + // new way + + table.computeIfAbsent(new Word("cat"), key -> "an animal"); + assertThat(table.get(new Word("cat")), is("a small domesticated carnivorous mammal")); + + } + + @Test + public void whenKeyIsPresent_thenComputeIfPresent() { + + Hashtable table = new Hashtable(); + table.put(new Word("cat"), "a small domesticated carnivorous mammal"); + + Word cat = new Word("cat"); + // old way + /* if (table.containsKey(cat)) { + String concatination = cat.getName() + " - " + table.get(cat); + table.put(cat, concatination); + }*/ + + // new way + table.computeIfPresent(cat, (key, value) -> key.getName() + " - " + value); + + assertThat(table.get(cat), is("cat - a small domesticated carnivorous mammal")); + + } + + @Test + public void whenCompute_thenForAllKeys() { + + Hashtable table = new Hashtable(); + String[] animals = { "cat", "dog", "dog", "cat", "bird", "mouse", "mouse" }; + for (String animal : animals) { + table.compute(animal, (key, value) -> (value == null ? 1 : value + 1)); + } + assertThat(table.values(), hasItems(2, 2, 2, 1)); + + } + + @Test + public void whenInsteadOfCompute_thenMerge() { + + Hashtable table = new Hashtable(); + String[] animals = { "cat", "dog", "dog", "cat", "bird", "mouse", "mouse" }; + for (String animal : animals) { + table.merge(animal, 1, (oldValue, value) -> (oldValue + value)); + } + assertThat(table.values(), hasItems(2, 2, 2, 1)); + } + + @Test + public void whenForeach_thenIterate() { + + Hashtable table = new Hashtable(); + table.put(new Word("cat"), "a small domesticated carnivorous mammal"); + table.put(new Word("dog"), "another animal"); + table.forEach((k, v) -> System.out.println(k.getName() + " - " + v) + + ); + } + + @Test + public void whenReplaceall_thenNoIterationNeeded() { + + Hashtable table = new Hashtable(); + table.put(new Word("cat"), "a small domesticated carnivorous mammal"); + table.put(new Word("dog"), "another animal"); + table.replaceAll((k, v) -> k.getName() + " - " + v); + + 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/UnsignedArithmeticUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java new file mode 100644 index 0000000000..4f1e54ec2c --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.java8; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.junit.Assert.assertEquals; + +public class UnsignedArithmeticUnitTest { + @Test + public void whenDoublingALargeByteNumber_thenOverflow() { + byte b1 = 100; + byte b2 = (byte) (b1 << 1); + + assertEquals(-56, b2); + } + + @Test + public void whenComparingNumbers_thenNegativeIsInterpretedAsUnsigned() { + int positive = Integer.MAX_VALUE; + int negative = Integer.MIN_VALUE; + + int signedComparison = Integer.compare(positive, negative); + assertEquals(1, signedComparison); + + int unsignedComparison = Integer.compareUnsigned(positive, negative); + assertEquals(-1, unsignedComparison); + + assertEquals(negative, positive + 1); + } + + @Test + public void whenDividingNumbers_thenNegativeIsInterpretedAsUnsigned() { + int positive = Integer.MAX_VALUE; + int negative = Integer.MIN_VALUE; + + assertEquals(-1, negative / positive); + assertEquals(1, Integer.divideUnsigned(negative, positive)); + + assertEquals(-1, negative % positive); + assertEquals(1, Integer.remainderUnsigned(negative, positive)); + } + + @Test + public void whenParsingNumbers_thenNegativeIsInterpretedAsUnsigned() { + Throwable thrown = catchThrowable(() -> Integer.parseInt("2147483648")); + assertThat(thrown).isInstanceOf(NumberFormatException.class); + + assertEquals(Integer.MAX_VALUE + 1, Integer.parseUnsignedInt("2147483648")); + } + + @Test + public void whenFormattingNumbers_thenNegativeIsInterpretedAsUnsigned() { + String signedString = Integer.toString(Integer.MIN_VALUE); + assertEquals("-2147483648", signedString); + + String unsignedString = Integer.toUnsignedString(Integer.MIN_VALUE); + assertEquals("2147483648", unsignedString); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetUnitTest.java new file mode 100644 index 0000000000..c8a631d9f0 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.java8.optional; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.junit.Assert.*; + +import com.baeldung.optional.OrElseAndOrElseGet; + +public class OrElseAndOrElseGetUnitTest { + + private OrElseAndOrElseGet orElsevsOrElseGet = new OrElseAndOrElseGet(); + + private static final Logger LOG = LoggerFactory.getLogger(OrElseAndOrElseGetUnitTest.class); + + @Test + public void givenNonEmptyOptional_whenOrElseUsed_thenGivenStringReturned() { + LOG.info("In givenNonEmptyOptional_whenOrElseUsed_thenGivenStringReturned()"); + String name = orElsevsOrElseGet.getNameUsingOrElse("baeldung"); + assertEquals(name, "baeldung"); + } + + @Test + public void givenEmptyOptional_whenOrElseUsed_thenRandomStringReturned() { + LOG.info("In givenEmptyOptional_whenOrElseUsed_thenRandomStringReturned()"); + String name = orElsevsOrElseGet.getNameUsingOrElse(null); + assertTrue(orElsevsOrElseGet.names.contains(name)); + } + + @Test + public void givenNonEmptyOptional_whenOrElseGetUsed_thenGivenStringReturned() { + LOG.info("In givenNonEmptyOptional_whenOrElseGetUsed_thenGivenStringReturned()"); + String name = orElsevsOrElseGet.getNameUsingOrElseGet("baeldung"); + assertEquals(name, "baeldung"); + } + + @Test + public void givenEmptyOptional_whenOrElseGetUsed_thenRandomStringReturned() { + LOG.info("In givenEmptyOptional_whenOrElseGetUsed_thenRandomStringReturned()"); + String name = orElsevsOrElseGet.getNameUsingOrElseGet(null); + assertTrue(orElsevsOrElseGet.names.contains(name)); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java b/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorUnitTest.java similarity index 93% rename from core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java rename to core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorUnitTest.java index e53e1c183e..0e7396c9dd 100644 --- a/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorTest.java +++ b/core-java-8/src/test/java/com/baeldung/prime/PrimeGeneratorUnitTest.java @@ -7,7 +7,7 @@ import java.util.List; import org.junit.Test; import static org.junit.Assert.*; -public class PrimeGeneratorTest { +public class PrimeGeneratorUnitTest { @Test public void whenBruteForced_returnsSuccessfully() { final List primeNumbers = primeNumbersBruteForce(20); diff --git a/core-java-8/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java b/core-java-8/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java new file mode 100644 index 0000000000..b191c94826 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.reflect; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.lang.reflect.Parameter; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import org.junit.Test; + +public class MethodParamNameUnitTest { + + @Test + public void whenGetConstructorParams_thenOk() + throws NoSuchMethodException, SecurityException { + List parameters + = Arrays.asList(Person.class.getConstructor(String.class).getParameters()); + Optional parameter + = parameters.stream().filter(Parameter::isNamePresent).findFirst(); + assertThat(parameter.get().getName()).isEqualTo("fullName"); + } + + @Test + public void whenGetMethodParams_thenOk() + throws NoSuchMethodException, SecurityException { + List parameters + = Arrays.asList( + Person.class.getMethod("setFullName", String.class).getParameters()); + Optional parameter + = parameters.stream().filter(Parameter::isNamePresent).findFirst(); + assertThat(parameter.get().getName()).isEqualTo("fullName"); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorTest.java b/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorUnitTest.java similarity index 95% rename from core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorTest.java rename to core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorUnitTest.java index 64dd65cf5e..81fad12eb0 100644 --- a/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorTest.java +++ b/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorUnitTest.java @@ -9,7 +9,7 @@ import static org.assertj.core.api.Assertions.*; import org.junit.Before; import org.junit.Test; -public class ExecutorTest { +public class ExecutorUnitTest { Article article; Stream stream; Spliterator spliterator; diff --git a/core-java-8/src/test/java/com/baeldung/stream/StreamApiTest.java b/core-java-8/src/test/java/com/baeldung/stream/StreamApiUnitTest.java similarity index 97% rename from core-java-8/src/test/java/com/baeldung/stream/StreamApiTest.java rename to core-java-8/src/test/java/com/baeldung/stream/StreamApiUnitTest.java index f4d0ac6b08..71569a1c82 100644 --- a/core-java-8/src/test/java/com/baeldung/stream/StreamApiTest.java +++ b/core-java-8/src/test/java/com/baeldung/stream/StreamApiUnitTest.java @@ -7,7 +7,7 @@ import java.util.List; import static org.junit.Assert.assertEquals; -public class StreamApiTest { +public class StreamApiUnitTest { @Test public void givenList_whenGetLastElementUsingReduce_thenReturnLastElement() { diff --git a/core-java-8/src/test/java/com/baeldung/stream/StreamIndicesTest.java b/core-java-8/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java similarity index 98% rename from core-java-8/src/test/java/com/baeldung/stream/StreamIndicesTest.java rename to core-java-8/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java index a02ef4031e..36a609f536 100644 --- a/core-java-8/src/test/java/com/baeldung/stream/StreamIndicesTest.java +++ b/core-java-8/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java @@ -8,7 +8,7 @@ import java.util.List; import static org.junit.Assert.assertEquals; -public class StreamIndicesTest { +public class StreamIndicesUnitTest { @Test public void whenCalled_thenReturnListOfEvenIndexedStrings() { diff --git a/core-java-8/src/test/java/com/baeldung/stream/StreamToImmutableTest.java b/core-java-8/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java similarity index 98% rename from core-java-8/src/test/java/com/baeldung/stream/StreamToImmutableTest.java rename to core-java-8/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java index 69b0b6d3ef..bd540201d2 100644 --- a/core-java-8/src/test/java/com/baeldung/stream/StreamToImmutableTest.java +++ b/core-java-8/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java @@ -16,7 +16,7 @@ import org.junit.Test; import com.baeldung.stream.mycollectors.MyImmutableListCollector; import com.google.common.collect.ImmutableList; -public class StreamToImmutableTest { +public class StreamToImmutableUnitTest { @Test public void whenUsingCollectingToImmutableSet_thenSuccess() { diff --git a/core-java-8/src/test/java/com/baeldung/stream/SupplierStreamTest.java b/core-java-8/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java similarity index 93% rename from core-java-8/src/test/java/com/baeldung/stream/SupplierStreamTest.java rename to core-java-8/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java index d78c9fca35..a496e18b2d 100644 --- a/core-java-8/src/test/java/com/baeldung/stream/SupplierStreamTest.java +++ b/core-java-8/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java @@ -8,7 +8,7 @@ import java.util.stream.Stream; import org.junit.Test; -public class SupplierStreamTest { +public class SupplierStreamUnitTest { @Test(expected = IllegalStateException.class) public void givenStream_whenStreamUsedTwice_thenThrowException() { diff --git a/core-java-8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java b/core-java-8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java similarity index 96% rename from core-java-8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java rename to core-java-8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java index 513f163da8..5ea0e840a2 100644 --- a/core-java-8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterTest.java +++ b/core-java-8/src/test/java/com/baeldung/temporaladjusters/CustomTemporalAdjusterUnitTest.java @@ -9,7 +9,7 @@ import java.time.temporal.TemporalAdjuster; import static org.junit.Assert.assertEquals; -public class CustomTemporalAdjusterTest { +public class CustomTemporalAdjusterUnitTest { private static final TemporalAdjuster NEXT_WORKING_DAY = new CustomTemporalAdjuster(); diff --git a/core-java-8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersTest.java b/core-java-8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java similarity index 92% rename from core-java-8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersTest.java rename to core-java-8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java index d06da5a782..175964dd21 100644 --- a/core-java-8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersTest.java +++ b/core-java-8/src/test/java/com/baeldung/temporaladjusters/TemporalAdjustersUnitTest.java @@ -7,7 +7,7 @@ import java.time.temporal.TemporalAdjusters; import org.junit.Assert; import org.junit.Test; -public class TemporalAdjustersTest { +public class TemporalAdjustersUnitTest { @Test public void whenAdjust_thenNextSunday() { diff --git a/core-java-8/src/test/java/com/baeldung/typeinference/TypeInferenceUnitTest.java b/core-java-8/src/test/java/com/baeldung/typeinference/TypeInferenceUnitTest.java new file mode 100644 index 0000000000..b9600a18cb --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/typeinference/TypeInferenceUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.typeinference; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; + +public class TypeInferenceUnitTest { + + @Test + public void givenNoTypeInference_whenInvokingGenericMethodsWithTypeParameters_ObjectsAreCreated() { + // Without type inference. code is verbose. + Map> mapOfMaps = new HashMap>(); + List strList = Collections. emptyList(); + List intList = Collections. emptyList(); + + assertTrue(mapOfMaps.isEmpty()); + assertTrue(strList.isEmpty()); + assertTrue(intList.isEmpty()); + } + + @Test + public void givenTypeInference_whenInvokingGenericMethodsWithoutTypeParameters_ObjectsAreCreated() { + // With type inference. code is concise. + List strListInferred = Collections.emptyList(); + List intListInferred = Collections.emptyList(); + + assertTrue(strListInferred.isEmpty()); + assertTrue(intListInferred.isEmpty()); + } + + @Test + public void givenJava7_whenInvokingCostructorWithoutTypeParameters_ObjectsAreCreated() { + // Type Inference for constructor using diamond operator. + Map> mapOfMapsInferred = new HashMap<>(); + + assertTrue(mapOfMapsInferred.isEmpty()); + assertEquals("public class java.util.HashMap", mapOfMapsInferred.getClass() + .toGenericString()); + } + + static List add(List list, T a, T b) { + list.add(a); + list.add(b); + return list; + } + + @Test + public void givenGenericMethod_WhenInvokedWithoutExplicitTypes_TypesAreInferred() { + // Generalized target-type inference + List strListGeneralized = add(new ArrayList<>(), "abc", "def"); + List intListGeneralized = add(new ArrayList<>(), 1, 2); + List numListGeneralized = add(new ArrayList<>(), 1, 2.0); + + assertEquals("public class java.util.ArrayList", strListGeneralized.getClass() + .toGenericString()); + assertFalse(intListGeneralized.isEmpty()); + assertEquals(2, numListGeneralized.size()); + } + + @Test + public void givenLambdaExpressions_whenParameterTypesNotSpecified_ParameterTypesAreInferred() { + // Type Inference and Lambda Expressions. + List intList = Arrays.asList(5, 3, 4, 2, 1); + Collections.sort(intList, (a, b) -> { + assertEquals("java.lang.Integer", a.getClass().getName()); + return a.compareTo(b); + }); + assertEquals("[1, 2, 3, 4, 5]", Arrays.toString(intList.toArray())); + + List strList = Arrays.asList("Red", "Blue", "Green"); + Collections.sort(strList, (a, b) -> { + assertEquals("java.lang.String", a.getClass().getName()); + return a.compareTo(b); + }); + assertEquals("[Blue, Green, Red]", Arrays.toString(strList.toArray())); + } + +} diff --git a/core-java-9/README.md b/core-java-9/README.md index 59b0929871..a76dcefc69 100644 --- a/core-java-9/README.md +++ b/core-java-9/README.md @@ -24,3 +24,5 @@ - [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) +- [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api) diff --git a/core-java-9/pom.xml b/core-java-9/pom.xml index 1f92ee71f8..0662e1e9a2 100644 --- a/core-java-9/pom.xml +++ b/core-java-9/pom.xml @@ -47,6 +47,11 @@ ${awaitility.version} test + + com.google.guava + guava + ${guava.version} + @@ -89,6 +94,7 @@ 1.7.0 1.9 1.9 + 25.1-jre diff --git a/core-java-9/src/main/java/com/baeldung/optionals/Optionals.java b/core-java-9/src/main/java/com/baeldung/optionals/Optionals.java new file mode 100644 index 0000000000..5efa607f94 --- /dev/null +++ b/core-java-9/src/main/java/com/baeldung/optionals/Optionals.java @@ -0,0 +1,26 @@ +package com.baeldung.optionals; + +import java.util.Optional; + +public class Optionals { + + public static Optional or(Optional optional, Optional fallback) { + return optional.isPresent() ? optional : fallback; + } + + public static Optional getName(Optional name) { + return name.or(() -> getCustomMessage()); + } + + public static com.google.common.base.Optional getOptionalGuavaName(com.google.common.base.Optional name) { + return name.or(getCustomMessageGuava()); + } + + private static Optional getCustomMessage() { + return Optional.of("Name not provided"); + } + + private static com.google.common.base.Optional getCustomMessageGuava() { + return com.google.common.base.Optional.of("Name not provided"); + } +} \ No newline at end of file diff --git a/core-java-9/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java new file mode 100644 index 0000000000..aa2fb34753 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/modules/ModuleAPIUnitTest.java @@ -0,0 +1,199 @@ +package com.baeldung.java9.modules; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.collection.IsEmptyCollection.empty; +import static org.junit.Assert.*; + +import java.lang.module.ModuleDescriptor; +import java.lang.module.ModuleDescriptor.*; +import java.sql.Date; +import java.sql.Driver; +import java.util.HashMap; +import java.util.Set; +import java.util.stream.Collectors; + +import org.junit.Before; +import org.junit.Test; + +public class ModuleAPIUnitTest { + + public static final String JAVA_BASE_MODULE_NAME = "java.base"; + + private Module javaBaseModule; + private Module javaSqlModule; + private Module module; + + @Before + public void setUp() { + Class hashMapClass = HashMap.class; + javaBaseModule = hashMapClass.getModule(); + + Class dateClass = Date.class; + javaSqlModule = dateClass.getModule(); + + Class personClass = Person.class; + module = personClass.getModule(); + } + + @Test + public void whenCheckingIfNamed_thenModuleIsNamed() { + assertThat(javaBaseModule.isNamed(), is(true)); + assertThat(javaBaseModule.getName(), is(JAVA_BASE_MODULE_NAME)); + } + + @Test + public void whenCheckingIfNamed_thenModuleIsUnnamed() { + assertThat(module.isNamed(), is(false)); + assertThat(module.getName(), is(nullValue())); + } + + @Test + public void whenExtractingPackagesContainedInAModule_thenModuleContainsOnlyFewOfThem() { + assertTrue(javaBaseModule.getPackages().contains("java.lang.annotation")); + assertFalse(javaBaseModule.getPackages().contains("java.sql")); + } + + @Test + public void whenRetrievingClassLoader_thenClassLoaderIsReturned() { + assertThat( + module.getClassLoader().getClass().getName(), + is("jdk.internal.loader.ClassLoaders$AppClassLoader") + ); + } + + @Test + public void whenGettingAnnotationsPresentOnAModule_thenNoAnnotationsArePresent() { + assertThat(javaBaseModule.getAnnotations().length, is(0)); + } + + @Test + public void whenGettingLayerOfAModule_thenModuleLayerInformationAreAvailable() { + ModuleLayer javaBaseModuleLayer = javaBaseModule.getLayer(); + + assertTrue(javaBaseModuleLayer.configuration().findModule(JAVA_BASE_MODULE_NAME).isPresent()); + assertThat(javaBaseModuleLayer.configuration().modules().size(), is(78)); + assertTrue(javaBaseModuleLayer.parents().get(0).configuration().parents().isEmpty()); + } + + @Test + public void whenRetrievingModuleDescriptor_thenTypeOfModuleIsInferred() { + ModuleDescriptor javaBaseModuleDescriptor = javaBaseModule.getDescriptor(); + ModuleDescriptor javaSqlModuleDescriptor = javaSqlModule.getDescriptor(); + + assertFalse(javaBaseModuleDescriptor.isAutomatic()); + assertFalse(javaBaseModuleDescriptor.isOpen()); + assertFalse(javaSqlModuleDescriptor.isAutomatic()); + assertFalse(javaSqlModuleDescriptor.isOpen()); + } + + @Test + public void givenModuleName_whenBuildingModuleDescriptor_thenBuilt() { + Builder moduleBuilder = ModuleDescriptor.newModule("baeldung.base"); + + ModuleDescriptor moduleDescriptor = moduleBuilder.build(); + + assertThat(moduleDescriptor.name(), is("baeldung.base")); + } + + @Test + public void givenModules_whenAccessingModuleDescriptorRequires_thenRequiresAreReturned() { + Set javaBaseRequires = javaBaseModule.getDescriptor().requires(); + Set javaSqlRequires = javaSqlModule.getDescriptor().requires(); + + Set javaSqlRequiresNames = javaSqlRequires.stream() + .map(Requires::name) + .collect(Collectors.toSet()); + + assertThat(javaBaseRequires, empty()); + assertThat(javaSqlRequires.size(), is(3)); + assertThat(javaSqlRequiresNames, containsInAnyOrder("java.base", "java.xml", "java.logging")); + } + + @Test + public void givenModules_whenAccessingModuleDescriptorProvides_thenProvidesAreReturned() { + Set javaBaseProvides = javaBaseModule.getDescriptor().provides(); + Set javaSqlProvides = javaSqlModule.getDescriptor().provides(); + + Set javaBaseProvidesService = javaBaseProvides.stream() + .map(Provides::service) + .collect(Collectors.toSet()); + + assertThat(javaBaseProvidesService, contains("java.nio.file.spi.FileSystemProvider")); + assertThat(javaSqlProvides, empty()); + } + + @Test + public void givenModules_whenAccessingModuleDescriptorExports_thenExportsAreReturned() { + Set javaBaseExports = javaBaseModule.getDescriptor().exports(); + Set javaSqlExports = javaSqlModule.getDescriptor().exports(); + + Set javaSqlExportsSource = javaSqlExports.stream() + .map(Exports::source) + .collect(Collectors.toSet()); + + assertThat(javaBaseExports.size(), is(108)); + assertThat(javaSqlExports.size(), is(3)); + assertThat(javaSqlExportsSource, containsInAnyOrder("java.sql", "javax.transaction.xa", "javax.sql")); + } + + @Test + public void givenModules_whenAccessingModuleDescriptorUses_thenUsesAreReturned() { + Set javaBaseUses = javaBaseModule.getDescriptor().uses(); + Set javaSqlUses = javaSqlModule.getDescriptor().uses(); + + assertThat(javaBaseUses.size(), is(34)); + assertThat(javaSqlUses, contains("java.sql.Driver")); + } + + @Test + public void givenModules_whenAccessingModuleDescriptorOpen_thenOpenAreReturned() { + Set javaBaseUses = javaBaseModule.getDescriptor().opens(); + Set javaSqlUses = javaSqlModule.getDescriptor().opens(); + + assertThat(javaBaseUses, empty()); + assertThat(javaSqlUses, empty()); + } + + @Test + public void whenAddingReadsToAModule_thenModuleCanReadNewModule() { + Module updatedModule = module.addReads(javaSqlModule); + + assertTrue(updatedModule.canRead(javaSqlModule)); + } + + @Test + public void whenExportingPackage_thenPackageIsExported() { + Module updatedModule = module.addExports("com.baeldung.java9.modules", javaSqlModule); + + assertTrue(updatedModule.isExported("com.baeldung.java9.modules")); + } + + @Test + public void whenOpeningAModulePackage_thenPackagedIsOpened() { + Module updatedModule = module.addOpens("com.baeldung.java9.modules", javaSqlModule); + + assertTrue(updatedModule.isOpen("com.baeldung.java9.modules", javaSqlModule)); + } + + @Test + public void whenAddingUsesToModule_thenUsesIsAdded() { + Module updatedModule = module.addUses(Driver.class); + + assertTrue(updatedModule.canUse(Driver.class)); + } + + private class Person { + private String name; + + public Person(String name) { + this.name = name; + } + + public String getName() { + return name; + } + } +} diff --git a/core-java-9/src/test/java/com/baeldung/optionals/OptionalsTest.java b/core-java-9/src/test/java/com/baeldung/optionals/OptionalsTest.java new file mode 100644 index 0000000000..4e5f94c0db --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/optionals/OptionalsTest.java @@ -0,0 +1,51 @@ +package com.baeldung.optionals; + +import static org.junit.Assert.assertEquals; + +import java.util.Optional; + +import org.junit.Test; + +public class OptionalsTest { + + @Test + public void givenOptional_whenEmptyValue_thenCustomMessage() { + assertEquals(Optional.of("Name not provided"), Optionals.getName(Optional.ofNullable(null))); + } + + @Test + public void givenOptional_whenValue_thenOptional() { + String name = "Filan Fisteku"; + Optional optionalString = Optional.ofNullable(name); + assertEquals(optionalString, Optionals.getName(optionalString)); + } + + @Test + public void givenOptional_whenValue_thenOptionalGeneralMethod() { + String name = "Filan Fisteku"; + String missingOptional = "Name not provided"; + Optional optionalString = Optional.ofNullable(name); + Optional fallbackOptionalString = Optional.ofNullable(missingOptional); + assertEquals(optionalString, Optionals.or(optionalString, fallbackOptionalString)); + } + + @Test + public void givenEmptyOptional_whenValue_thenOptionalGeneralMethod() { + String missingOptional = "Name not provided"; + Optional optionalString = Optional.empty(); + Optional fallbackOptionalString = Optional.ofNullable(missingOptional); + assertEquals(fallbackOptionalString, Optionals.or(optionalString, fallbackOptionalString)); + } + + @Test + public void givenGuavaOptional_whenInvoke_thenOptional() { + String name = "Filan Fisteku"; + com.google.common.base.Optional stringOptional = com.google.common.base.Optional.of(name); + assertEquals(stringOptional, Optionals.getOptionalGuavaName(stringOptional)); + } + + @Test + public void givenGuavaOptional_whenNull_thenDefaultText() { + assertEquals(com.google.common.base.Optional.of("Name not provided"), Optionals.getOptionalGuavaName(com.google.common.base.Optional.fromNullable(null))); + } +} \ No newline at end of file diff --git a/core-java-collections/README.md b/core-java-collections/README.md index 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..a98b489d9d 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} + @@ -214,6 +220,7 @@ **/*LiveTest.java **/*IntegrationTest.java + **/*IntTest.java **/*LongRunningUnitTest.java **/*ManualTest.java @@ -283,6 +290,7 @@ **/*IntegrationTest.java + **/*IntTest.java @@ -365,6 +373,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..f5c5c3dd3a 100644 --- a/core-java-io/src/test/java/com/baeldung/file/FilesTest.java +++ b/core-java-io/src/test/java/com/baeldung/file/FilesManualTest.java @@ -24,7 +24,7 @@ import org.junit.Test; import com.baeldung.util.StreamUtils; -public class FilesTest { +public class FilesManualTest { public static final String fileName = "src/main/resources/countries.properties"; @@ -77,6 +77,6 @@ public class FilesTest { bw.newLine(); bw.close(); - assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n"); + assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n"); } } \ No newline at end of file diff --git a/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java index b56841117e..a96232d66c 100644 --- a/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java +++ b/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java @@ -1,6 +1,7 @@ package org.baeldung.java.io; import org.junit.Test; +import org.junit.Ignore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -105,8 +106,9 @@ public class JavaReadFromFileUnitTest { } @Test + @Ignore // TODO public void whenReadUTFEncodedFile_thenCorrect() throws IOException { - final String expected_value = "é�’空"; + final String expected_value = "青空"; final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8")); final String currentLine = reader.readLine(); reader.close(); diff --git a/core-java-sun/pom.xml b/core-java-sun/pom.xml index 3fd8e80296..8662884095 100644 --- a/core-java-sun/pom.xml +++ b/core-java-sun/pom.xml @@ -353,6 +353,7 @@ **/*IntegrationTest.java + **/*IntTest.java diff --git a/core-java/README.md b/core-java/README.md index b40298abe4..fa2d7e4cf0 100644 --- a/core-java/README.md +++ b/core-java/README.md @@ -74,17 +74,14 @@ - [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string) - [Period and Duration in Java](http://www.baeldung.com/java-period-duration) - [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator) -- [Singletons in Java](http://www.baeldung.com/java-singleton) - [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws) - [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded) - [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer) - [Number of Digits in an Integer in Java](http://www.baeldung.com/java-number-of-digits-in-int) -- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns) - [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin) - [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static) - [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array) - [Guide to Java String Pool](http://www.baeldung.com/java-string-pool) -- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns) - [Quick Example - Comparator vs Comparable in Java](http://www.baeldung.com/java-comparator-comparable) - [Quick Guide to Java Stack](http://www.baeldung.com/java-stack) - [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break) @@ -116,8 +113,6 @@ - [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings) - [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance) - [Guide to Externalizable Interface in Java](http://www.baeldung.com/java-externalizable) -- [The Observer Pattern in Java](http://www.baeldung.com/java-observer-pattern) -- [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight) - [Object Type Casting in Java](http://www.baeldung.com/java-type-casting) - [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat) - [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os) @@ -136,7 +131,6 @@ - [Class Loaders in Java](http://www.baeldung.com/java-classloaders) - [Find Sum and Average in a Java Array](http://www.baeldung.com/java-array-sum-average) - [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception) -- [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern) - [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure) - [BigDecimal and BigInteger in Java](http://www.baeldung.com/java-bigdecimal-biginteger) - [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones) @@ -147,3 +141,22 @@ - [Java KeyStore API](http://www.baeldung.com/java-keystore) - [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking) - [Guide to Java Clock Class](http://www.baeldung.com/java-clock) +- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java) +- [Using Java Assertions](http://www.baeldung.com/java-assert) +- [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference) +- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number) +- [Variable and Method Hiding in Java](http://www.baeldung.com/java-variable-method-hiding) +- [Access Modifiers in Java](http://www.baeldung.com/java-access-modifiers) +- [NaN in Java](http://www.baeldung.com/java-not-a-number) +- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java) +- [Why Use char[] Array Over a String for Storing Passwords in Java?](http://www.baeldung.com/java-storing-passwords) +- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns) +- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns) +- [Singletons in Java](http://www.baeldung.com/java-singleton) +- [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight) +- [The Observer Pattern in Java](http://www.baeldung.com/java-observer-pattern) +- [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern) +- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join) +- [Guide to the super Java Keyword](http://www.baeldung.com/java-super) +- [Guide to the this Java Keyword](http://www.baeldung.com/java-this) +- [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays) diff --git a/core-java/pom.xml b/core-java/pom.xml index 88fae5edea..a823d836e8 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -198,6 +198,11 @@ mail ${javax.mail.version} + + javax.mail + mail + 1.5.0-b01 + @@ -217,6 +222,7 @@ **/*LiveTest.java **/*IntegrationTest.java + **/*IntTest.java **/*LongRunningUnitTest.java **/*ManualTest.java @@ -382,6 +388,7 @@ **/*IntegrationTest.java + **/*IntTest.java diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/Public.java b/core-java/src/main/java/com/baeldung/accessmodifiers/Public.java new file mode 100644 index 0000000000..9a64c1d4c4 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/accessmodifiers/Public.java @@ -0,0 +1,9 @@ +package com.baeldung.accessmodifiers; + +public class Public { + public Public() { + SuperPublic.publicMethod(); // Available everywhere. + SuperPublic.protectedMethod(); // Available in the same package or subclass. + SuperPublic.defaultMethod(); // Available in the same package. + } +} diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/SubClass.java b/core-java/src/main/java/com/baeldung/accessmodifiers/SubClass.java new file mode 100644 index 0000000000..545f48c9ca --- /dev/null +++ b/core-java/src/main/java/com/baeldung/accessmodifiers/SubClass.java @@ -0,0 +1,9 @@ +package com.baeldung.accessmodifiers; + +public class SubClass extends SuperPublic { + public SubClass() { + SuperPublic.publicMethod(); // Available everywhere. + SuperPublic.protectedMethod(); // Available in the same package or subclass. + SuperPublic.defaultMethod(); // Available in the same package. + } +} diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java b/core-java/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java new file mode 100644 index 0000000000..7c9554f2c7 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/accessmodifiers/SuperPublic.java @@ -0,0 +1,39 @@ +package com.baeldung.accessmodifiers; + +//Only public or default access modifiers are permitted +public class SuperPublic { + // Always available from anywhere + static public void publicMethod() { + System.out.println(SuperPublic.class.getName() + " publicMethod()"); + } + + // Available within the same package + static void defaultMethod() { + System.out.println(SuperPublic.class.getName() + " defaultMethod()"); + } + + // Available within the same package and subclasses + static protected void protectedMethod() { + System.out.println(SuperPublic.class.getName() + " protectedMethod()"); + } + + // Available within the same class only + static private void privateMethod() { + System.out.println(SuperPublic.class.getName() + " privateMethod()"); + } + + // Method in the same class = has access to all members within the same class + private void anotherPrivateMethod() { + privateMethod(); + defaultMethod(); + protectedMethod(); + publicMethod(); // Available in the same class only. + } +} + +// Only public or default access modifiers are permitted +class SuperDefault { + public void publicMethod() { + System.out.println(this.getClass().getName() + " publicMethod()"); + } +} diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java new file mode 100644 index 0000000000..32eea36854 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherPublic.java @@ -0,0 +1,9 @@ +package com.baeldung.accessmodifiers.another; + +import com.baeldung.accessmodifiers.SuperPublic; + +public class AnotherPublic { + public AnotherPublic() { + SuperPublic.publicMethod(); // Available everywhere. + } +} diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java new file mode 100644 index 0000000000..3d9dc3f119 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSubClass.java @@ -0,0 +1,10 @@ +package com.baeldung.accessmodifiers.another; + +import com.baeldung.accessmodifiers.SuperPublic; + +public class AnotherSubClass extends SuperPublic { + public AnotherSubClass() { + SuperPublic.publicMethod(); // Available everywhere. + SuperPublic.protectedMethod(); // Available in subclass. Let's note different package. + } +} diff --git a/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java new file mode 100644 index 0000000000..3932e6f990 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/accessmodifiers/another/AnotherSuperPublic.java @@ -0,0 +1,9 @@ +package com.baeldung.accessmodifiers.another; + +import com.baeldung.accessmodifiers.SuperPublic; + +public class AnotherSuperPublic { + public AnotherSuperPublic() { + SuperPublic.publicMethod(); // Available everywhere. Let's note different package. + } +} diff --git a/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java b/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java index 977587a06a..f35064b783 100644 --- a/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java +++ b/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java @@ -9,7 +9,7 @@ public class ArrayBenchmarkRunner { public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() - .include(SearchArrayTest.class.getSimpleName()).threads(1) + .include(SearchArrayUnitTest.class.getSimpleName()).threads(1) .forks(1).shouldFailOnError(true).shouldDoGC(true) .jvmArgs("-server").build(); diff --git a/core-java/src/main/java/com/baeldung/array/JaggedArray.java b/core-java/src/main/java/com/baeldung/array/JaggedArray.java new file mode 100644 index 0000000000..36cfc88b95 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/array/JaggedArray.java @@ -0,0 +1,49 @@ +package com.baeldung.array; + +import java.util.Arrays; +import java.util.Scanner; + +public class JaggedArray { + + int[][] shortHandFormInitialization() { + int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + return jaggedArr; + } + + int[][] declarationAndThenInitialization() { + int[][] jaggedArr = new int[3][]; + jaggedArr[0] = new int[] { 1, 2 }; + jaggedArr[1] = new int[] { 3, 4, 5 }; + jaggedArr[2] = new int[] { 6, 7, 8, 9 }; + return jaggedArr; + } + + int[][] declarationAndThenInitializationUsingUserInputs() { + int[][] jaggedArr = new int[3][]; + jaggedArr[0] = new int[2]; + jaggedArr[1] = new int[3]; + jaggedArr[2] = new int[4]; + initializeElements(jaggedArr); + return jaggedArr; + } + + void initializeElements(int[][] jaggedArr) { + Scanner sc = new Scanner(System.in); + for (int outer = 0; outer < jaggedArr.length; outer++) { + for (int inner = 0; inner < jaggedArr[outer].length; inner++) { + jaggedArr[outer][inner] = sc.nextInt(); + } + } + } + + void printElements(int[][] jaggedArr) { + for (int index = 0; index < jaggedArr.length; index++) { + System.out.println(Arrays.toString(jaggedArr[index])); + } + } + + int[] getElementAtGivenIndex(int[][] jaggedArr, int index) { + return jaggedArr[index]; + } + +} diff --git a/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java b/core-java/src/main/java/com/baeldung/array/SearchArrayUnitTest.java similarity index 98% rename from core-java/src/main/java/com/baeldung/array/SearchArrayTest.java rename to core-java/src/main/java/com/baeldung/array/SearchArrayUnitTest.java index 199ebdf036..bed58356cb 100644 --- a/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java +++ b/core-java/src/main/java/com/baeldung/array/SearchArrayUnitTest.java @@ -8,7 +8,7 @@ import java.util.concurrent.TimeUnit; @BenchmarkMode(Mode.AverageTime) @Warmup(iterations = 5) @OutputTimeUnit(TimeUnit.MICROSECONDS) -public class SearchArrayTest { +public class SearchArrayUnitTest { @State(Scope.Benchmark) public static class SearchData { diff --git a/core-java/src/main/java/com/baeldung/extension/Extension.java b/core-java/src/main/java/com/baeldung/extension/Extension.java new file mode 100644 index 0000000000..e30084f1cb --- /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; + +import java.util.Optional; + +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 Optional getExtensionByStringHandling(String filename) { + return Optional.ofNullable(filename) + .filter(f -> f.contains(".")) + .map(f -> f.substring(filename.lastIndexOf(".") + 1)); + } + + public String getExtensionByGuava(String filename) { + return Files.getFileExtension(filename); + } +} diff --git a/core-java/src/main/java/com/baeldung/immutableobjects/Currency.java b/core-java/src/main/java/com/baeldung/immutableobjects/Currency.java new file mode 100644 index 0000000000..412d105581 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/immutableobjects/Currency.java @@ -0,0 +1,18 @@ +package com.baeldung.immutableobjects; + +public final class Currency { + + private final String value; + + private Currency(String currencyValue) { + value = currencyValue; + } + + public String getValue() { + return value; + } + + public static Currency of(String value) { + return new Currency(value); + } +} diff --git a/core-java/src/main/java/com/baeldung/immutableobjects/Money.java b/core-java/src/main/java/com/baeldung/immutableobjects/Money.java new file mode 100644 index 0000000000..b509d2e797 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/immutableobjects/Money.java @@ -0,0 +1,20 @@ +package com.baeldung.immutableobjects; + +// 4. Immutability in Java +public final class Money { + private final double amount; + private final Currency currency; + + public Money(double amount, Currency currency) { + this.amount = amount; + this.currency = currency; + } + + public Currency getCurrency() { + return currency; + } + + public double getAmount() { + return amount; + } +} 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/loops/InfiniteLoops.java b/core-java/src/main/java/com/baeldung/loops/InfiniteLoops.java new file mode 100644 index 0000000000..0706c85db8 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/loops/InfiniteLoops.java @@ -0,0 +1,23 @@ +package com.baeldung.loops; + +public class InfiniteLoops { + + public void infiniteLoopUsingWhile() { + while (true) { + System.out.println("Infinite loop using while"); + } + } + + public void infiniteLoopUsingFor() { + for (;;) { + System.out.println("Infinite loop using for"); + } + } + + public void infiniteLoopUsingDoWhile() { + do { + System.out.println("Infinite loop using do-while"); + } while (true); + } + +} diff --git a/core-java/src/main/java/com/baeldung/manifest/AppExample.java b/core-java/src/main/java/com/baeldung/manifest/AppExample.java new file mode 100644 index 0000000000..cb15323b22 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/manifest/AppExample.java @@ -0,0 +1,8 @@ +package com.baeldung.manifest; + +public class AppExample { + + public static void main(String[] args){ + System.out.println("AppExample executed!"); + } +} diff --git a/core-java/src/main/java/com/baeldung/manifest/ExecuteJarFile.java b/core-java/src/main/java/com/baeldung/manifest/ExecuteJarFile.java new file mode 100644 index 0000000000..21e14b96e0 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/manifest/ExecuteJarFile.java @@ -0,0 +1,83 @@ +package com.baeldung.manifest; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; + +public class ExecuteJarFile { + + private static final String DELIMITER = " "; + private static final String WORK_PATH = "src/main/java/com/baeldung/manifest"; + private static final String MANIFEST_MF_PATH = WORK_PATH + "/MANIFEST.MF"; + private static final String MAIN_MANIFEST_ATTRIBUTE = "Main-Class: com.baeldung.manifest.AppExample"; + + private static final String COMPILE_COMMAND = "javac -d . AppExample.java"; + private static final String CREATE_JAR_WITHOUT_MF_ATT_COMMAND = "jar cvf example.jar com/baeldung/manifest/AppExample.class"; + private static final String CREATE_JAR_WITH_MF_ATT_COMMAND = "jar cvmf MANIFEST.MF example.jar com/baeldung/manifest/AppExample.class"; + private static final String EXECUTE_JAR_COMMAND = "java -jar example.jar"; + + public static void main(String[] args) { + System.out.println(executeJarWithoutManifestAttribute()); + System.out.println(executeJarWithManifestAttribute()); + } + + public static String executeJarWithoutManifestAttribute() { + return executeJar(CREATE_JAR_WITHOUT_MF_ATT_COMMAND); + } + + public static String executeJarWithManifestAttribute() { + createManifestFile(); + return executeJar(CREATE_JAR_WITH_MF_ATT_COMMAND); + } + + private static void createManifestFile() { + BufferedWriter writer; + try { + writer = new BufferedWriter(new FileWriter(MANIFEST_MF_PATH)); + writer.write(MAIN_MANIFEST_ATTRIBUTE); + writer.newLine(); + writer.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static String executeJar(String createJarCommand) { + executeCommand(COMPILE_COMMAND); + executeCommand(createJarCommand); + return executeCommand(EXECUTE_JAR_COMMAND); + } + + private static String executeCommand(String command) { + String output = null; + try { + output = collectOutput(runProcess(command)); + } catch (Exception ex) { + System.out.println(ex); + } + return output; + } + + private static String collectOutput(Process process) throws IOException { + StringBuffer output = new StringBuffer(); + BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream())); + String line = ""; + while ((line = outputReader.readLine()) != null) { + output.append(line + "\n"); + } + return output.toString(); + } + + private static Process runProcess(String command) throws IOException, InterruptedException { + ProcessBuilder builder = new ProcessBuilder(command.split(DELIMITER)); + builder.directory(new File(WORK_PATH).getAbsoluteFile()); + builder.redirectErrorStream(true); + Process process = builder.start(); + process.waitFor(); + return process; + } + +} diff --git a/core-java/src/main/java/com/baeldung/nan/NaNExample.java b/core-java/src/main/java/com/baeldung/nan/NaNExample.java new file mode 100644 index 0000000000..d54a749d3f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/nan/NaNExample.java @@ -0,0 +1,81 @@ +package com.baeldung.nan; + +/** + * Sample usage of NaN. + * + */ +public class NaNExample { + + public static void main(String[] args) { + NaNExample naNExample = new NaNExample(); + naNExample.demo(); + } + + void demo() { + undefined_operations_produce_NaN(); + operations_with_no_real_results_produce_NaN(); + operations_with_NaN_produce_NaN(); + comparison_with_NaN(); + check_if_a_value_is_NaN(); + assign_NaN_to_missing_values(); + } + + void undefined_operations_produce_NaN() { + System.out.println("Undefined Operations Produce NaN"); + final double ZERO = 0; + System.out.println("ZERO / ZERO = " + (ZERO / ZERO)); + System.out.println("INFINITY - INFINITY = " + (Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY)); + System.out.println("INFINITY * ZERO = " + (Double.POSITIVE_INFINITY * ZERO)); + System.out.println(); + } + + void operations_with_no_real_results_produce_NaN() { + System.out.println("Operations with no real results produce NaN"); + System.out.println("SQUARE ROOT OF -1 = " + Math.sqrt(-1)); + System.out.println("LOG OF -1 = " + Math.log(-1)); + System.out.println(); + } + + void operations_with_NaN_produce_NaN() { + System.out.println("Operations with NaN produce NaN"); + System.out.println("2 + NaN = " + (2 + Double.NaN)); + System.out.println("2 - NaN = " + (2 - Double.NaN)); + System.out.println("2 * NaN = " + (2 * Double.NaN)); + System.out.println("2 / NaN = " + (2 / Double.NaN)); + System.out.println(); + } + + void assign_NaN_to_missing_values() { + System.out.println("Assign NaN to Missing values"); + double salaryRequired = Double.NaN; + System.out.println(salaryRequired); + System.out.println(); + } + + void comparison_with_NaN() { + System.out.println("Comparison with NaN"); + final double NAN = Double.NaN; + System.out.println("NaN == 1 = " + (NAN == 1)); + System.out.println("NaN > 1 = " + (NAN > 1)); + System.out.println("NaN < 1 = " + (NAN < 1)); + System.out.println("NaN != 1 = " + (NAN != 1)); + System.out.println("NaN == NaN = " + (NAN == NAN)); + System.out.println("NaN > NaN = " + (NAN > NAN)); + System.out.println("NaN < NaN = " + (NAN < NAN)); + System.out.println("NaN != NaN = " + (NAN != NAN)); + System.out.println(); + } + + void check_if_a_value_is_NaN() { + System.out.println("Check if a value is NaN"); + double x = 1; + System.out.println(x + " is NaN = " + (x != x)); + System.out.println(x + " is NaN = " + (Double.isNaN(x))); + + x = Double.NaN; + System.out.println(x + " is NaN = " + (x != x)); + System.out.println(x + " is NaN = " + (Double.isNaN(x))); + System.out.println(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/scope/method/BaseMethodClass.java b/core-java/src/main/java/com/baeldung/scope/method/BaseMethodClass.java new file mode 100644 index 0000000000..46ed5fd99f --- /dev/null +++ b/core-java/src/main/java/com/baeldung/scope/method/BaseMethodClass.java @@ -0,0 +1,9 @@ +package com.baeldung.scope.method; + + +public class BaseMethodClass { + + public static void printMessage() { + System.out.println("base static method"); + } +} diff --git a/core-java/src/main/java/com/baeldung/scope/method/ChildMethodClass.java b/core-java/src/main/java/com/baeldung/scope/method/ChildMethodClass.java new file mode 100644 index 0000000000..1d0cff2d6b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/scope/method/ChildMethodClass.java @@ -0,0 +1,9 @@ +package com.baeldung.scope.method; + + +public class ChildMethodClass extends BaseMethodClass { + + public static void printMessage() { + System.out.println("child static method"); + } +} diff --git a/core-java/src/main/java/com/baeldung/scope/method/MethodHidingDemo.java b/core-java/src/main/java/com/baeldung/scope/method/MethodHidingDemo.java new file mode 100644 index 0000000000..7e0b3ed146 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/scope/method/MethodHidingDemo.java @@ -0,0 +1,8 @@ +package com.baeldung.scope.method; + +public class MethodHidingDemo { + + public static void main(String[] args) { + ChildMethodClass.printMessage(); + } +} diff --git a/core-java/src/main/java/com/baeldung/scope/variable/ChildVariable.java b/core-java/src/main/java/com/baeldung/scope/variable/ChildVariable.java new file mode 100644 index 0000000000..5730e5e282 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/scope/variable/ChildVariable.java @@ -0,0 +1,13 @@ +package com.baeldung.scope.variable; + +/** + * Created by Gebruiker on 5/7/2018. + */ +public class ChildVariable extends ParentVariable { + + String instanceVariable = "child variable"; + + public void printInstanceVariable() { + System.out.println(instanceVariable); + } +} diff --git a/core-java/src/main/java/com/baeldung/scope/variable/HideVariable.java b/core-java/src/main/java/com/baeldung/scope/variable/HideVariable.java new file mode 100644 index 0000000000..8243fdb249 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/scope/variable/HideVariable.java @@ -0,0 +1,23 @@ +package com.baeldung.scope.variable; + +/** + * Created by Gebruiker on 5/6/2018. + */ +public class HideVariable { + + private String message = "this is instance variable"; + + HideVariable() { + String message = "constructor local variable"; + System.out.println(message); + } + + public void printLocalVariable() { + String message = "method local variable"; + System.out.println(message); + } + + public void printInstanceVariable() { + System.out.println(this.message); + } +} diff --git a/core-java/src/main/java/com/baeldung/scope/variable/ParentVariable.java b/core-java/src/main/java/com/baeldung/scope/variable/ParentVariable.java new file mode 100644 index 0000000000..7f116b955e --- /dev/null +++ b/core-java/src/main/java/com/baeldung/scope/variable/ParentVariable.java @@ -0,0 +1,13 @@ +package com.baeldung.scope.variable; + +/** + * Created by Gebruiker on 5/7/2018. + */ +public class ParentVariable { + + String instanceVariable = "parent variable"; + + public void printInstanceVariable() { + System.out.println(instanceVariable); + } +} diff --git a/core-java/src/main/java/com/baeldung/scope/variable/VariableHidingDemo.java b/core-java/src/main/java/com/baeldung/scope/variable/VariableHidingDemo.java new file mode 100644 index 0000000000..1ad71bd966 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/scope/variable/VariableHidingDemo.java @@ -0,0 +1,18 @@ +package com.baeldung.scope.variable; + +/** + * Created by Gebruiker on 5/6/2018. + */ +public class VariableHidingDemo { + public static void main(String[] args) { + HideVariable variable = new HideVariable(); + variable.printLocalVariable(); + variable.printInstanceVariable(); + + ParentVariable parentVariable = new ParentVariable(); + ParentVariable childVariable = new ChildVariable(); + + parentVariable.printInstanceVariable(); + childVariable.printInstanceVariable(); + } +} diff --git a/core-java/src/test/java/com/baeldung/array/ArrayInitializerTest.java b/core-java/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/array/ArrayInitializerTest.java rename to core-java/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java index 7265fa20e5..5e764da174 100644 --- a/core-java/src/test/java/com/baeldung/array/ArrayInitializerTest.java +++ b/core-java/src/test/java/com/baeldung/array/ArrayInitializerUnitTest.java @@ -15,7 +15,7 @@ import static org.junit.Assert.assertArrayEquals; import org.junit.Test; -public class ArrayInitializerTest { +public class ArrayInitializerUnitTest { @Test public void whenInitializeArrayInLoop_thenCorrect() { diff --git a/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java b/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayUnitTest.java similarity index 90% rename from core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java rename to core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayUnitTest.java index ec916af092..4493f3fbf5 100644 --- a/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java +++ b/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.array; import org.junit.Assert; import org.junit.Test; -public class Find2ndLargestInArrayTest { +public class Find2ndLargestInArrayUnitTest { @Test public void givenAnIntArray_thenFind2ndLargestElement() { int[] array = { 1, 3, 24, 16, 87, 20 }; diff --git a/core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java b/core-java/src/test/java/com/baeldung/array/FindElementInArrayUnitTest.java similarity index 96% rename from core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java rename to core-java/src/test/java/com/baeldung/array/FindElementInArrayUnitTest.java index ba9188fa7b..887f50ebcc 100644 --- a/core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java +++ b/core-java/src/test/java/com/baeldung/array/FindElementInArrayUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.array; import org.junit.Assert; import org.junit.Test; -public class FindElementInArrayTest { +public class FindElementInArrayUnitTest { @Test public void givenAnIntArray_whenNotUsingStream_thenFindAnElement() { int[] array = { 1, 3, 4, 8, 19, 20 }; diff --git a/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java b/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java new file mode 100644 index 0000000000..a4dd7e25c3 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/array/JaggedArrayUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.array; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.PrintStream; + +import org.junit.Test; + +public class JaggedArrayUnitTest { + + private JaggedArray obj = new JaggedArray(); + + @Test + public void whenInitializedUsingShortHandForm_thenCorrect() { + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.shortHandFormInitialization()); + } + + @Test + public void whenInitializedWithDeclarationAndThenInitalization_thenCorrect() { + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitialization()); + } + + @Test + public void whenInitializedWithDeclarationAndThenInitalizationUsingUserInputs_thenCorrect() { + InputStream is = new ByteArrayInputStream("1 2 3 4 5 6 7 8 9".getBytes()); + System.setIn(is); + assertArrayEquals(new int[][] { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }, obj.declarationAndThenInitializationUsingUserInputs()); + System.setIn(System.in); + } + + @Test + public void givenJaggedArrayAndAnIndex_thenReturnArrayAtGivenIndex() { + int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + assertArrayEquals(new int[] { 1, 2 }, obj.getElementAtGivenIndex(jaggedArr, 0)); + assertArrayEquals(new int[] { 3, 4, 5 }, obj.getElementAtGivenIndex(jaggedArr, 1)); + assertArrayEquals(new int[] { 6, 7, 8, 9 }, obj.getElementAtGivenIndex(jaggedArr, 2)); + } + + @Test + public void givenJaggedArray_whenUsingArraysAPI_thenVerifyPrintedElements() { + int[][] jaggedArr = { { 1, 2 }, { 3, 4, 5 }, { 6, 7, 8, 9 } }; + ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outContent)); + obj.printElements(jaggedArr); + assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", "")); + System.setOut(System.out); + } + +} diff --git a/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java b/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java rename to core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java index 208075cb57..0f38316ce3 100644 --- a/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java +++ b/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.array; import org.junit.Assert; import org.junit.Test; -public class SumAndAverageInArrayTest { +public class SumAndAverageInArrayUnitTest { @Test public void givenAnIntArray_whenNotUsingStream_thenFindSum() { int[] array = { 1, 3, 4, 8, 19, 20 }; diff --git a/core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java b/core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java new file mode 100644 index 0000000000..9e6d3d6131 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/arrays/ArraysUnitTest.java @@ -0,0 +1,153 @@ +package com.baeldung.arrays; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Stream; + +public class ArraysUnitTest { + private String[] intro; + + @Rule + public final ExpectedException exception = ExpectedException.none(); + + @Before + public void setup() { + intro = new String[] { "once", "upon", "a", "time" }; + } + + @Test + public void whenCopyOfRange_thenAbridgedArray() { + String[] abridgement = Arrays.copyOfRange(intro, 0, 3); + + assertArrayEquals(new String[] { "once", "upon", "a" }, abridgement); + assertFalse(Arrays.equals(intro, abridgement)); + } + + @Test + public void whenCopyOf_thenNullElement() { + String[] revised = Arrays.copyOf(intro, 3); + String[] expanded = Arrays.copyOf(intro, 5); + + assertArrayEquals(Arrays.copyOfRange(intro, 0, 3), revised); + assertNull(expanded[4]); + } + + @Test + public void whenFill_thenAllMatch() { + String[] stutter = new String[3]; + Arrays.fill(stutter, "once"); + + assertTrue(Stream.of(stutter).allMatch(el -> "once".equals(el))); + } + + @Test + public void whenEqualsContent_thenMatch() { + assertTrue(Arrays.equals(new String[] { "once", "upon", "a", "time" }, intro)); + assertFalse(Arrays.equals(new String[] { "once", "upon", "a", null }, intro)); + } + + @Test + public void whenNestedArrays_thenDeepEqualsPass() { + String[] end = { "the", "end" }; + Object[] story = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end }; + Object[] copy = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end }; + + assertTrue(Arrays.deepEquals(story, copy)); + assertFalse(Arrays.equals(story, copy)); + } + + @Test + public void whenSort_thenArraySorted() { + String[] sorted = Arrays.copyOf(intro, 4); + Arrays.sort(sorted); + + assertArrayEquals(new String[] { "a", "once", "time", "upon" }, sorted); + } + + @Test + public void whenBinarySearch_thenFindElements() { + String[] sorted = Arrays.copyOf(intro, 4); + Arrays.sort(sorted); + int exact = Arrays.binarySearch(sorted, "time"); + int caseInsensitive = Arrays.binarySearch(sorted, "TiMe", String::compareToIgnoreCase); + + assertEquals("time", sorted[exact]); + assertEquals(2, exact); + assertEquals(exact, caseInsensitive); + } + + @Test + public void whenNullElement_thenArraysHashCodeNotEqual() { + int beforeChange = Arrays.hashCode(intro); + int before = intro.hashCode(); + intro[3] = null; + int after = intro.hashCode(); + int afterChange = Arrays.hashCode(intro); + + assertNotEquals(beforeChange, afterChange); + assertEquals(before, after); + } + + @Test + public void whenNestedArrayNullElement_thenEqualsFailDeepHashPass() { + Object[] looping = new Object[] { intro, intro }; + int deepHashBefore = Arrays.deepHashCode(looping); + int hashBefore = Arrays.hashCode(looping); + + intro[3] = null; + + int hashAfter = Arrays.hashCode(looping); + int deepHashAfter = Arrays.deepHashCode(looping); + + assertEquals(hashAfter, hashBefore); + assertNotEquals(deepHashAfter, deepHashBefore); + } + + @Test + public void whenStreamBadIndex_thenException() { + assertEquals(Arrays.stream(intro).count(), 4); + + exception.expect(ArrayIndexOutOfBoundsException.class); + Arrays.stream(intro, 2, 1).count(); + } + + @Test + public void whenSetAllToUpper_thenAppliedToAllElements() { + String[] longAgo = new String[4]; + Arrays.setAll(longAgo, i -> intro[i].toUpperCase()); + + assertArrayEquals(longAgo, new String[] { "ONCE", "UPON", "A", "TIME" }); + } + + @Test + public void whenToString_thenFormattedArrayString() { + assertEquals("[once, upon, a, time]", Arrays.toString(intro)); + } + + @Test + public void whenNestedArrayDeepString_thenFormattedArraysString() { + String[] end = { "the", "end" }; + Object[] story = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end }; + + assertEquals("[[once, upon, a, time], [chapter one, chapter two], [the, end]]", Arrays.deepToString(story)); + } + + @Test + public void whenAsList_thenImmutableArray() { + List rets = Arrays.asList(intro); + + assertTrue(rets.contains("upon")); + assertTrue(rets.contains("time")); + assertEquals(rets.size(), 4); + + exception.expect(UnsupportedOperationException.class); + rets.add("the"); + } +} diff --git a/core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java b/core-java/src/test/java/com/baeldung/asciiart/AsciiArtIntegrationTest.java similarity index 92% rename from core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java rename to core-java/src/test/java/com/baeldung/asciiart/AsciiArtIntegrationTest.java index 103681894e..8ab1695395 100644 --- a/core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java +++ b/core-java/src/test/java/com/baeldung/asciiart/AsciiArtIntegrationTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import com.baeldung.asciiart.AsciiArt.Settings; -public class AsciiArtTest { +public class AsciiArtIntegrationTest { @Test public void givenTextWithAsciiCharacterAndSettings_shouldPrintAsciiArt() { diff --git a/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueTest.java b/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueUnitTest.java similarity index 96% rename from core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueTest.java rename to core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueUnitTest.java index 1980497cd3..2a2f3be2a9 100644 --- a/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueTest.java +++ b/core-java/src/test/java/com/baeldung/breakcontinue/BreakContinueUnitTest.java @@ -9,7 +9,7 @@ import static org.junit.Assert.assertEquals; import org.junit.Test; -public class BreakContinueTest { +public class BreakContinueUnitTest { @Test public void whenUnlabeledBreak_ThenEqual() { diff --git a/core-java/src/test/java/com/baeldung/casting/CastingTest.java b/core-java/src/test/java/com/baeldung/casting/CastingUnitTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/casting/CastingTest.java rename to core-java/src/test/java/com/baeldung/casting/CastingUnitTest.java index dd95e0dd80..41eaa5dc1b 100644 --- a/core-java/src/test/java/com/baeldung/casting/CastingTest.java +++ b/core-java/src/test/java/com/baeldung/casting/CastingUnitTest.java @@ -5,7 +5,7 @@ import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; -public class CastingTest { +public class CastingUnitTest { @Test public void whenPrimitiveConverted_thenValueChanged() { diff --git a/core-java/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java b/core-java/src/test/java/com/baeldung/chararraypassword/PasswordStoreExamplesUnitTest.java 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..680eea0cae --- /dev/null +++ b/core-java/src/test/java/com/baeldung/extension/ExtensionUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.extension; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.Optional; + +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"; + Optional actualExtension = extension.getExtensionByStringHandling("Demo.java"); + Assert.assertEquals(expectedExtension, actualExtension.get()); + } + + @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/immutableobjects/ImmutableObjectsUnitTest.java b/core-java/src/test/java/com/baeldung/immutableobjects/ImmutableObjectsUnitTest.java new file mode 100644 index 0000000000..01dfeac050 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/immutableobjects/ImmutableObjectsUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.immutableobjects; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +public class ImmutableObjectsUnitTest { + + @Test + public void whenCallingStringReplace_thenStringDoesNotMutate() { + // 2. What's an Immutable Object? + final String name = "baeldung"; + final String newName = name.replace("dung", "----"); + + assertEquals("baeldung", name); + assertEquals("bael----", newName); + } + + public void whenReassignFinalValue_thenCompilerError() { + // 3. The final Keyword in Java (1) + final String name = "baeldung"; + // name = "bael..."; + } + + @Test + public void whenAddingElementToList_thenSizeChange() { + // 3. The final Keyword in Java (2) + final List strings = new ArrayList<>(); + assertEquals(0, strings.size()); + strings.add("baeldung"); + assertEquals(1, strings.size()); + } +} 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/manifest/ExecuteJarFileUnitTest.java b/core-java/src/test/java/com/baeldung/manifest/ExecuteJarFileUnitTest.java new file mode 100644 index 0000000000..a5a499c98c --- /dev/null +++ b/core-java/src/test/java/com/baeldung/manifest/ExecuteJarFileUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.manifest; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class ExecuteJarFileUnitTest { + + private static final String ERROR_MESSAGE = "no main manifest attribute, in example.jar\n"; + private static final String SUCCESS_MESSAGE = "AppExample executed!\n"; + + @Test + public final void givenDefaultManifest_whenManifestAttributeIsNotPresent_thenGetErrorMessage() { + String output = ExecuteJarFile.executeJarWithoutManifestAttribute(); + assertEquals(ERROR_MESSAGE, output); + } + + @Test + public final void givenCustomManifest_whenManifestAttributeIsPresent_thenGetSuccessMessage() { + String output = ExecuteJarFile.executeJarWithManifestAttribute(); + assertEquals(SUCCESS_MESSAGE, output); + } + +} diff --git a/core-java/src/test/java/com/baeldung/maths/BigDecimalImplTest.java b/core-java/src/test/java/com/baeldung/maths/BigDecimalImplUnitTest.java similarity index 91% rename from core-java/src/test/java/com/baeldung/maths/BigDecimalImplTest.java rename to core-java/src/test/java/com/baeldung/maths/BigDecimalImplUnitTest.java index 788fbd7047..786e5af312 100644 --- a/core-java/src/test/java/com/baeldung/maths/BigDecimalImplTest.java +++ b/core-java/src/test/java/com/baeldung/maths/BigDecimalImplUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import java.math.BigDecimal; import java.math.RoundingMode; -public class BigDecimalImplTest { +public class BigDecimalImplUnitTest { @Test public void givenBigDecimalNumbers_whenAddedTogether_thenGetExpectedResult() { diff --git a/core-java/src/test/java/com/baeldung/maths/BigIntegerImplTest.java b/core-java/src/test/java/com/baeldung/maths/BigIntegerImplUnitTest.java similarity index 91% rename from core-java/src/test/java/com/baeldung/maths/BigIntegerImplTest.java rename to core-java/src/test/java/com/baeldung/maths/BigIntegerImplUnitTest.java index aa8eaa9909..4c45f69090 100644 --- a/core-java/src/test/java/com/baeldung/maths/BigIntegerImplTest.java +++ b/core-java/src/test/java/com/baeldung/maths/BigIntegerImplUnitTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import java.math.BigInteger; -public class BigIntegerImplTest { +public class BigIntegerImplUnitTest { @Test public void givenBigIntegerNumbers_whenAddedTogether_thenGetExpectedResult() { diff --git a/core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticTest.java b/core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticUnitTest.java similarity index 93% rename from core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticTest.java rename to core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticUnitTest.java index 2066f13c6d..6812a8f588 100644 --- a/core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticTest.java +++ b/core-java/src/test/java/com/baeldung/maths/FloatingPointArithmeticUnitTest.java @@ -5,7 +5,7 @@ import java.math.BigDecimal; import org.junit.Assert; import org.junit.Test; -public class FloatingPointArithmeticTest { +public class FloatingPointArithmeticUnitTest { @Test public void givenDecimalNumbers_whenAddedTogether_thenGetExpectedResult() { diff --git a/core-java/src/test/java/com/baeldung/maths/RoundTest.java b/core-java/src/test/java/com/baeldung/maths/RoundUnitTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/maths/RoundTest.java rename to core-java/src/test/java/com/baeldung/maths/RoundUnitTest.java index 5ce9523e21..f3c8e6e97a 100644 --- a/core-java/src/test/java/com/baeldung/maths/RoundTest.java +++ b/core-java/src/test/java/com/baeldung/maths/RoundUnitTest.java @@ -8,7 +8,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; -public class RoundTest { +public class RoundUnitTest { private double value = 2.03456d; private int places = 2; private double delta = 0.0d; diff --git a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java index fe2747bcee..04d2886a82 100644 --- a/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java +++ b/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java @@ -179,7 +179,7 @@ public class JavaMoneyUnitManualTest { MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder .of(Locale.US) .set(CurrencyStyle.NAME) - .set("pattern", "00000.00 �") + .set("pattern", "00000.00 US Dollar") .build()); String customFormatted = customFormat.format(oneDollar); diff --git a/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorTest.java b/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorUnitTest.java similarity index 85% rename from core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorTest.java rename to core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorUnitTest.java index aa11aaa788..ccc8c1f69c 100644 --- a/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorTest.java +++ b/core-java/src/test/java/com/baeldung/noclassdeffounderror/NoClassDefFoundErrorUnitTest.java @@ -2,7 +2,7 @@ package com.baeldung.noclassdeffounderror; import org.junit.Test; -public class NoClassDefFoundErrorTest { +public class NoClassDefFoundErrorUnitTest { @Test(expected = NoClassDefFoundError.class) public void givenInitErrorInClass_whenloadClass_thenNoClassDefFoundError() { diff --git a/core-java/src/test/java/com/baeldung/recursion/RecursionExampleTest.java b/core-java/src/test/java/com/baeldung/recursion/RecursionExampleUnitTest.java similarity index 94% rename from core-java/src/test/java/com/baeldung/recursion/RecursionExampleTest.java rename to core-java/src/test/java/com/baeldung/recursion/RecursionExampleUnitTest.java index c65be24240..6c560c9c37 100644 --- a/core-java/src/test/java/com/baeldung/recursion/RecursionExampleTest.java +++ b/core-java/src/test/java/com/baeldung/recursion/RecursionExampleUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.recursion; import org.junit.Assert; import org.junit.Test; -public class RecursionExampleTest { +public class RecursionExampleUnitTest { RecursionExample recursion = new RecursionExample(); diff --git a/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsTest.java b/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsUnitTest.java similarity index 93% rename from core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsTest.java rename to core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsUnitTest.java index bba867f50f..77cdd0279d 100644 --- a/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsTest.java +++ b/core-java/src/test/java/com/baeldung/reflection/BaeldungReflectionUtilsUnitTest.java @@ -7,7 +7,7 @@ import java.util.List; import static org.junit.Assert.assertTrue; -public class BaeldungReflectionUtilsTest { +public class BaeldungReflectionUtilsUnitTest { @Test public void givenCustomer_whenAFieldIsNull_thenFieldNameInResult() throws Exception { diff --git a/core-java/src/test/java/com/baeldung/regexp/EscapingCharsTest.java b/core-java/src/test/java/com/baeldung/regexp/EscapingCharsUnitTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/regexp/EscapingCharsTest.java rename to core-java/src/test/java/com/baeldung/regexp/EscapingCharsUnitTest.java index 47c9cfc621..d903a02589 100644 --- a/core-java/src/test/java/com/baeldung/regexp/EscapingCharsTest.java +++ b/core-java/src/test/java/com/baeldung/regexp/EscapingCharsUnitTest.java @@ -10,7 +10,7 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; -public class EscapingCharsTest { +public class EscapingCharsUnitTest { @Test public void givenRegexWithDot_whenMatchingStr_thenMatches() { String strInput = "foof"; diff --git a/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java b/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java index 7f165cec86..9abe8a927c 100644 --- a/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java +++ b/core-java/src/test/java/com/baeldung/scripting/NashornUnitTest.java @@ -104,7 +104,7 @@ public class NashornUnitTest { public void loadExamples() throws ScriptException { Object loadResult = engine.eval("load('classpath:js/script.js');" + "increment(5)"); - Assert.assertEquals(6.0, loadResult); + Assert.assertEquals(6, ((Double) loadResult).intValue()); Object math = engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.increment(5);"); diff --git a/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableTest.java b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableUnitTest.java similarity index 90% rename from core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableTest.java rename to core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableUnitTest.java index cd31f545b9..8d8e4f14fe 100644 --- a/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableTest.java +++ b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyRunnableUnitTest.java @@ -4,7 +4,7 @@ import org.junit.Test; import static junit.framework.TestCase.assertEquals; -public class SneakyRunnableTest { +public class SneakyRunnableUnitTest { @Test public void whenCallSneakyRunnableMethod_thenThrowException() { diff --git a/core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsTest.java b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsUnitTest.java similarity index 91% rename from core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsTest.java rename to core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsUnitTest.java index e033ca062d..da1b2e617b 100644 --- a/core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsTest.java +++ b/core-java/src/test/java/com/baeldung/sneakythrows/SneakyThrowsUnitTest.java @@ -4,7 +4,7 @@ import org.junit.Test; import static junit.framework.TestCase.assertEquals; -public class SneakyThrowsTest { +public class SneakyThrowsUnitTest { @Test public void whenCallSneakyMethod_thenThrowSneakyException() { diff --git a/core-java/src/test/java/com/baeldung/string/PalindromeTest.java b/core-java/src/test/java/com/baeldung/string/PalindromeUnitTest.java similarity index 98% rename from core-java/src/test/java/com/baeldung/string/PalindromeTest.java rename to core-java/src/test/java/com/baeldung/string/PalindromeUnitTest.java index bc6fee2cd9..49f2542f39 100644 --- a/core-java/src/test/java/com/baeldung/string/PalindromeTest.java +++ b/core-java/src/test/java/com/baeldung/string/PalindromeUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.string; import static org.junit.Assert.*; import org.junit.Test; -public class PalindromeTest { +public class PalindromeUnitTest { private String[] words = { "Anna", diff --git a/core-java/src/test/java/com/baeldung/string/StringComparisonTest.java b/core-java/src/test/java/com/baeldung/string/StringComparisonUnitTest.java similarity index 99% rename from core-java/src/test/java/com/baeldung/string/StringComparisonTest.java rename to core-java/src/test/java/com/baeldung/string/StringComparisonUnitTest.java index 5869676004..539f66d9b4 100644 --- a/core-java/src/test/java/com/baeldung/string/StringComparisonTest.java +++ b/core-java/src/test/java/com/baeldung/string/StringComparisonUnitTest.java @@ -7,7 +7,7 @@ import java.util.Objects; import static org.assertj.core.api.Assertions.assertThat; -public class StringComparisonTest { +public class StringComparisonUnitTest { @Test public void whenUsingComparisonOperator_ThenComparingStrings(){ diff --git a/core-java/src/test/java/com/baeldung/string/StringTest.java b/core-java/src/test/java/com/baeldung/string/StringUnitTest.java similarity index 99% rename from core-java/src/test/java/com/baeldung/string/StringTest.java rename to core-java/src/test/java/com/baeldung/string/StringUnitTest.java index e88b2d7c2c..0d4fd6eff9 100644 --- a/core-java/src/test/java/com/baeldung/string/StringTest.java +++ b/core-java/src/test/java/com/baeldung/string/StringUnitTest.java @@ -12,7 +12,7 @@ import java.util.regex.PatternSyntaxException; import org.junit.Test; -public class StringTest { +public class StringUnitTest { @Test public void whenCallCodePointAt_thenDecimalUnicodeReturned() { diff --git a/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java b/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java similarity index 99% rename from core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java rename to core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java index ad4f5dce7e..648fdaf65a 100644 --- a/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleTests.java +++ b/core-java/src/test/java/com/baeldung/string/formatter/StringFormatterExampleUnitTest.java @@ -8,7 +8,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; -public class StringFormatterExampleTests { +public class StringFormatterExampleUnitTest { @Test public void givenString_whenFormatSpecifierForCalendar_thenGotExpected() { diff --git a/core-java/src/test/java/com/baeldung/system/DateTimeServiceTest.java b/core-java/src/test/java/com/baeldung/system/DateTimeServiceUnitTest.java similarity index 90% rename from core-java/src/test/java/com/baeldung/system/DateTimeServiceTest.java rename to core-java/src/test/java/com/baeldung/system/DateTimeServiceUnitTest.java index 587cd4ef20..ef083dd25e 100644 --- a/core-java/src/test/java/com/baeldung/system/DateTimeServiceTest.java +++ b/core-java/src/test/java/com/baeldung/system/DateTimeServiceUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.system; import org.junit.Assert; import org.junit.Test; -public class DateTimeServiceTest { +public class DateTimeServiceUnitTest { @Test public void givenClass_whenCalledMethods_thenNotNullInResult() { diff --git a/core-java/src/test/java/com/baeldung/system/EnvironmentVariablesTest.java b/core-java/src/test/java/com/baeldung/system/EnvironmentVariablesUnitTest.java similarity index 87% rename from core-java/src/test/java/com/baeldung/system/EnvironmentVariablesTest.java rename to core-java/src/test/java/com/baeldung/system/EnvironmentVariablesUnitTest.java index 3722fea88f..5e4db747be 100644 --- a/core-java/src/test/java/com/baeldung/system/EnvironmentVariablesTest.java +++ b/core-java/src/test/java/com/baeldung/system/EnvironmentVariablesUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.system; import org.junit.Assert; import org.junit.Test; -public class EnvironmentVariablesTest { +public class EnvironmentVariablesUnitTest { @Test public void givenEnvVars_whenReadPath_thenGetValueinResult() { diff --git a/core-java/src/test/java/com/baeldung/system/SystemArrayCopyTest.java b/core-java/src/test/java/com/baeldung/system/SystemArrayCopyUnitTest.java similarity index 95% rename from core-java/src/test/java/com/baeldung/system/SystemArrayCopyTest.java rename to core-java/src/test/java/com/baeldung/system/SystemArrayCopyUnitTest.java index f54e3702c8..bf715f3ac3 100644 --- a/core-java/src/test/java/com/baeldung/system/SystemArrayCopyTest.java +++ b/core-java/src/test/java/com/baeldung/system/SystemArrayCopyUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.system; import org.junit.Assert; import org.junit.Test; -public class SystemArrayCopyTest { +public class SystemArrayCopyUnitTest { @Test public void givenTwoArraysAB_whenUseArrayCopy_thenArrayCopiedFromAToBInResult() { diff --git a/core-java/src/test/java/com/baeldung/system/SystemNanoTest.java b/core-java/src/test/java/com/baeldung/system/SystemNanoUnitTest.java similarity index 91% rename from core-java/src/test/java/com/baeldung/system/SystemNanoTest.java rename to core-java/src/test/java/com/baeldung/system/SystemNanoUnitTest.java index bf6590da0a..cd9543212e 100644 --- a/core-java/src/test/java/com/baeldung/system/SystemNanoTest.java +++ b/core-java/src/test/java/com/baeldung/system/SystemNanoUnitTest.java @@ -3,7 +3,7 @@ package com.baeldung.system; import org.junit.Assert; import org.junit.Test; -public class SystemNanoTest { +public class SystemNanoUnitTest { @Test public void givenSystem_whenCalledNanoTime_thenGivesTimeinResult() { diff --git a/core-java/src/test/java/com/baeldung/system/SystemPropertiesTest.java b/core-java/src/test/java/com/baeldung/system/SystemPropertiesUnitTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/system/SystemPropertiesTest.java rename to core-java/src/test/java/com/baeldung/system/SystemPropertiesUnitTest.java index 4fca27f96c..4940e39238 100644 --- a/core-java/src/test/java/com/baeldung/system/SystemPropertiesTest.java +++ b/core-java/src/test/java/com/baeldung/system/SystemPropertiesUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import java.util.Properties; -public class SystemPropertiesTest { +public class SystemPropertiesUnitTest { @Test public void givenSystem_whenCalledGetProperty_thenReturnPropertyinResult() { diff --git a/core-java/src/test/java/com/baeldung/system/WhenDetectingOSTest.java b/core-java/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java similarity index 93% rename from core-java/src/test/java/com/baeldung/system/WhenDetectingOSTest.java rename to core-java/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java index 77901f6524..27a6dd43c6 100644 --- a/core-java/src/test/java/com/baeldung/system/WhenDetectingOSTest.java +++ b/core-java/src/test/java/com/baeldung/system/WhenDetectingOSUnitTest.java @@ -5,7 +5,7 @@ import org.junit.Ignore; import org.junit.Test; @Ignore -public class WhenDetectingOSTest { +public class WhenDetectingOSUnitTest { private DetectOS os = new DetectOS(); diff --git a/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java b/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomIntegrationTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java rename to core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomIntegrationTest.java index c75813baba..56c77f923f 100644 --- a/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomTest.java +++ b/core-java/src/test/java/com/baeldung/threadlocalrandom/ThreadLocalRandomIntegrationTest.java @@ -5,7 +5,7 @@ import java.util.concurrent.ThreadLocalRandom; import static org.junit.Assert.assertTrue; import org.junit.Test; -public class ThreadLocalRandomTest { +public class ThreadLocalRandomIntegrationTest { @Test public void givenUsingThreadLocalRandom_whenGeneratingRandomIntBounded_thenCorrect() { diff --git a/core-java/src/test/java/com/baeldung/util/PropertiesLoaderTest.java b/core-java/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java similarity index 96% rename from core-java/src/test/java/com/baeldung/util/PropertiesLoaderTest.java rename to core-java/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java index fa3c425156..eea3068253 100644 --- a/core-java/src/test/java/com/baeldung/util/PropertiesLoaderTest.java +++ b/core-java/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java @@ -7,7 +7,7 @@ import java.util.Properties; import static org.junit.Assert.assertEquals; -public class PropertiesLoaderTest { +public class PropertiesLoaderUnitTest { @Test public void loadProperties_whenPropertyReaded_thenSuccess() throws IOException { diff --git a/core-java/src/test/java/com/baeldung/varargs/FormatterTest.java b/core-java/src/test/java/com/baeldung/varargs/FormatterUnitTest.java similarity index 97% rename from core-java/src/test/java/com/baeldung/varargs/FormatterTest.java rename to core-java/src/test/java/com/baeldung/varargs/FormatterUnitTest.java index 509c8764d2..e9018afd62 100644 --- a/core-java/src/test/java/com/baeldung/varargs/FormatterTest.java +++ b/core-java/src/test/java/com/baeldung/varargs/FormatterUnitTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -public class FormatterTest { +public class FormatterUnitTest { private final static String FORMAT = "%s %s %s"; diff --git a/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesTest.java b/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesUnitTest.java similarity index 91% rename from core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesTest.java rename to core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesUnitTest.java index 2b36786abf..161c053cea 100644 --- a/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesTest.java +++ b/core-java/src/test/java/org/baeldung/java/rawtypes/RawTypesUnitTest.java @@ -5,7 +5,7 @@ import java.util.List; import org.junit.Test; -public class RawTypesTest { +public class RawTypesUnitTest { @Test public void shouldCreateListUsingRawTypes() { @SuppressWarnings("rawtypes") diff --git a/core-kotlin/README.md b/core-kotlin/README.md index 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/enums/CardType.kt b/core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt new file mode 100644 index 0000000000..69cfce5601 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/enums/CardType.kt @@ -0,0 +1,23 @@ +package com.baeldung.enums + +enum class CardType(val color: String) : ICardLimit { + SILVER("gray") { + override fun getCreditLimit() = 100000 + override fun calculateCashbackPercent() = 0.25f + }, + GOLD("yellow") { + override fun getCreditLimit() = 200000 + override fun calculateCashbackPercent(): Float = 0.5f + }, + PLATINUM("black") { + override fun getCreditLimit() = 300000 + override fun calculateCashbackPercent() = 0.75f + }; + + companion object { + fun getCardTypeByColor(color: String) = values().firstOrNull { it.color == color } + fun getCardTypeByName(name: String) = valueOf(name.toUpperCase()) + } + + abstract fun calculateCashbackPercent(): Float +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/enums/ICardLimit.kt b/core-kotlin/src/main/kotlin/com/baeldung/enums/ICardLimit.kt new file mode 100644 index 0000000000..7994822a52 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/enums/ICardLimit.kt @@ -0,0 +1,5 @@ +package com.baeldung.enums + +interface ICardLimit { + fun getCreditLimit(): Int +} \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt b/core-kotlin/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt new file mode 100644 index 0000000000..cc46c65f96 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/klaxon/CustomProduct.kt @@ -0,0 +1,9 @@ +package com.baeldung.klaxon + +import com.beust.klaxon.Json + +class CustomProduct( + @Json(name = "productName") + val name: String, + @Json(ignored = true) + val id: Int) \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/klaxon/Product.kt b/core-kotlin/src/main/kotlin/com/baeldung/klaxon/Product.kt new file mode 100644 index 0000000000..09bcbc8722 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/klaxon/Product.kt @@ -0,0 +1,3 @@ +package com.baeldung.klaxon + +class Product(val name: String) \ No newline at end of file diff --git a/core-kotlin/src/main/kotlin/com/baeldung/klaxon/ProductData.kt b/core-kotlin/src/main/kotlin/com/baeldung/klaxon/ProductData.kt new file mode 100644 index 0000000000..1f30f26ce9 --- /dev/null +++ b/core-kotlin/src/main/kotlin/com/baeldung/klaxon/ProductData.kt @@ -0,0 +1,3 @@ +package com.baeldung.klaxon + +data class ProductData(val name: String, val capacityInGb: Int) \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt new file mode 100644 index 0000000000..525faebd55 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/enums/CardTypeUnitTest.kt @@ -0,0 +1,84 @@ +package com.baeldung.enums + +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +internal class CardTypeUnitTest { + + @Test + fun givenSilverCardType_whenCalculateCashbackPercent_thenReturnCashbackValue() { + assertEquals(0.25f, CardType.SILVER.calculateCashbackPercent()) + } + + @Test + fun givenGoldCardType_whenCalculateCashbackPercent_thenReturnCashbackValue() { + assertEquals(0.5f, CardType.GOLD.calculateCashbackPercent()) + } + + @Test + fun givenPlatinumCardType_whenCalculateCashbackPercent_thenReturnCashbackValue() { + assertEquals(0.75f, CardType.PLATINUM.calculateCashbackPercent()) + } + + @Test + fun givenSilverCardType_whenGetCreditLimit_thenReturnCreditLimit() { + assertEquals(100000, CardType.SILVER.getCreditLimit()) + } + + @Test + fun givenGoldCardType_whenGetCreditLimit_thenReturnCreditLimit() { + assertEquals(200000, CardType.GOLD.getCreditLimit()) + } + + @Test + fun givenPlatinumCardType_whenGetCreditLimit_thenReturnCreditLimit() { + assertEquals(300000, CardType.PLATINUM.getCreditLimit()) + } + + @Test + fun givenSilverCardType_whenCheckColor_thenReturnColor() { + assertEquals("gray", CardType.SILVER.color) + } + + @Test + fun givenGoldCardType_whenCheckColor_thenReturnColor() { + assertEquals("yellow", CardType.GOLD.color) + } + + @Test + fun givenPlatinumCardType_whenCheckColor_thenReturnColor() { + assertEquals("black", CardType.PLATINUM.color) + } + + @Test + fun whenGetCardTypeByColor_thenSilverCardType() { + Assertions.assertEquals(CardType.SILVER, CardType.getCardTypeByColor("gray")) + } + + @Test + fun whenGetCardTypeByColor_thenGoldCardType() { + Assertions.assertEquals(CardType.GOLD, CardType.getCardTypeByColor("yellow")) + } + + @Test + fun whenGetCardTypeByColor_thenPlatinumCardType() { + Assertions.assertEquals(CardType.PLATINUM, CardType.getCardTypeByColor("black")) + } + + @Test + fun whenGetCardTypeByName_thenSilverCardType() { + Assertions.assertEquals(CardType.SILVER, CardType.getCardTypeByName("silver")) + } + + @Test + fun whenGetCardTypeByName_thenGoldCardType() { + Assertions.assertEquals(CardType.GOLD, CardType.getCardTypeByName("gold")) + } + + @Test + fun whenGetCardTypeByName_thenPlatinumCardType() { + Assertions.assertEquals(CardType.PLATINUM, CardType.getCardTypeByName("platinum")) + } + +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt new file mode 100644 index 0000000000..2a7d44a163 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/klaxon/KlaxonUnitTest.kt @@ -0,0 +1,163 @@ +package com.baeldung.klaxon + +import com.beust.klaxon.JsonArray +import com.beust.klaxon.JsonObject +import com.beust.klaxon.JsonReader +import com.beust.klaxon.Klaxon +import com.beust.klaxon.Parser +import com.beust.klaxon.PathMatcher +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.SoftAssertions.assertSoftly +import org.junit.Assert +import org.junit.jupiter.api.Test +import java.io.StringReader +import java.util.regex.Pattern + +class KlaxonUnitTest { + + @Test + fun giveProduct_whenSerialize_thenGetJsonString() { + val product = Product("HDD") + val result = Klaxon().toJsonString(product) + + assertThat(result).isEqualTo("""{"name" : "HDD"}""") + } + + @Test + fun giveJsonString_whenDeserialize_thenGetProduct() { + val result = Klaxon().parse(""" + { + "name" : "RAM" + } + """) + + assertThat(result?.name).isEqualTo("RAM") + } + + @Test + fun giveCustomProduct_whenSerialize_thenGetJsonString() { + val product = CustomProduct("HDD", 1) + val result = Klaxon().toJsonString(product) + + assertThat(result).isEqualTo("""{"productName" : "HDD"}""") + } + + @Test + fun giveJsonArray_whenStreaming_thenGetProductArray() { + val jsonArray = """ + [ + { "name" : "HDD", "capacityInGb" : 512 }, + { "name" : "RAM", "capacityInGb" : 16 } + ]""" + val expectedArray = arrayListOf(ProductData("HDD", 512), + ProductData("RAM", 16)) + val klaxon = Klaxon() + val productArray = arrayListOf() + JsonReader(StringReader(jsonArray)).use { reader -> + reader.beginArray { + while (reader.hasNext()) { + val product = klaxon.parse(reader) + productArray.add(product!!) + } + } + } + + assertThat(productArray).hasSize(2).isEqualTo(expectedArray) + } + + @Test + fun giveJsonString_whenParser_thenGetJsonObject() { + val jsonString = StringBuilder(""" + { + "name" : "HDD", + "capacityInGb" : 512, + "sizeInInch" : 2.5 + } + """) + val parser = Parser() + val json = parser.parse(jsonString) as JsonObject + + assertThat(json).hasSize(3).containsEntry("name", "HDD").containsEntry("capacityInGb", 512).containsEntry("sizeInInch", 2.5) + } + + @Suppress("UNCHECKED_CAST") + @Test + fun giveJsonStringArray_whenParser_thenGetJsonArray() { + val jsonString = StringBuilder(""" + [ + { "name" : "SDD" }, + { "madeIn" : "Taiwan" }, + { "warrantyInYears" : 5 } + ]""") + val parser = Parser() + val json = parser.parse(jsonString) as JsonArray + + assertSoftly({ softly -> + softly.assertThat(json).hasSize(3) + softly.assertThat(json[0]["name"]).isEqualTo("SDD") + softly.assertThat(json[1]["madeIn"]).isEqualTo("Taiwan") + softly.assertThat(json[2]["warrantyInYears"]).isEqualTo(5) + }) + } + + @Test + fun givenJsonString_whenStreaming_thenProcess() { + val jsonString = """ + { + "name" : "HDD", + "madeIn" : "Taiwan", + "warrantyInYears" : 5 + "hasStock" : true + "capacitiesInTb" : [ 1, 2 ], + "features" : { "cacheInMb" : 64, "speedInRpm" : 7200 } + }""" + + JsonReader(StringReader(jsonString)).use { reader -> + reader.beginObject { + while (reader.hasNext()) { + val readName = reader.nextName() + when (readName) { + "name" -> assertThat(reader.nextString()).isEqualTo("HDD") + "madeIn" -> assertThat(reader.nextString()).isEqualTo("Taiwan") + "warrantyInYears" -> assertThat(reader.nextInt()).isEqualTo(5) + "hasStock" -> assertThat(reader.nextBoolean()).isEqualTo(true) + "capacitiesInTb" -> assertThat(reader.nextArray()).contains(1, 2) + "features" -> assertThat(reader.nextObject()).containsEntry("cacheInMb", 64).containsEntry("speedInRpm", 7200) + else -> Assert.fail("Unexpected name: $readName") + } + } + } + } + + } + + @Test + fun givenDiskInventory_whenRegexMatches_thenGetTypes() { + val jsonString = """ + { + "inventory" : { + "disks" : [ + { + "type" : "HDD", + "sizeInGb" : 1000 + }, + { + "type" : "SDD", + "sizeInGb" : 512 + } + ] + } + }""" + val pathMatcher = object : PathMatcher { + override fun pathMatches(path: String) = Pattern.matches(".*inventory.*disks.*type.*", path) + + override fun onMatch(path: String, value: Any) { + when (path) { + "$.inventory.disks[0].type" -> assertThat(value).isEqualTo("HDD") + "$.inventory.disks[1].type" -> assertThat(value).isEqualTo("SDD") + } + } + } + Klaxon().pathMatcher(pathMatcher).parseJsonObject(StringReader(jsonString)) + } +} \ No newline at end of file diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/JavaReflectionTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/JavaReflectionTest.kt new file mode 100644 index 0000000000..0d0e7b724d --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/JavaReflectionTest.kt @@ -0,0 +1,32 @@ +package com.baeldung.kotlin.reflection + +import org.junit.Ignore +import org.junit.Test +import org.slf4j.LoggerFactory + +@Ignore +class JavaReflectionTest { + private val LOG = LoggerFactory.getLogger(KClassTest::class.java) + + @Test + fun listJavaClassMethods() { + Exception::class.java.methods + .forEach { method -> LOG.info("Method: {}", method) } + } + + @Test + fun listKotlinClassMethods() { + JavaReflectionTest::class.java.methods + .forEach { method -> LOG.info("Method: {}", method) } + } + + @Test + fun listKotlinDataClassMethods() { + data class ExampleDataClass(val name: String, var enabled: Boolean) + + ExampleDataClass::class.java.methods + .forEach { method -> LOG.info("Method: {}", method) } + } + + +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KClassTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KClassTest.kt new file mode 100644 index 0000000000..56183b50be --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KClassTest.kt @@ -0,0 +1,69 @@ +package com.baeldung.kotlin.reflection + +import org.junit.Assert +import org.junit.Ignore +import org.junit.Test +import org.slf4j.LoggerFactory +import java.math.BigDecimal +import kotlin.reflect.full.* + +class KClassTest { + private val LOG = LoggerFactory.getLogger(KClassTest::class.java) + + @Test + fun testKClassDetails() { + val stringClass = String::class + Assert.assertEquals("kotlin.String", stringClass.qualifiedName) + Assert.assertFalse(stringClass.isData) + Assert.assertFalse(stringClass.isCompanion) + Assert.assertFalse(stringClass.isAbstract) + Assert.assertTrue(stringClass.isFinal) + Assert.assertFalse(stringClass.isSealed) + + val listClass = List::class + Assert.assertEquals("kotlin.collections.List", listClass.qualifiedName) + Assert.assertFalse(listClass.isData) + Assert.assertFalse(listClass.isCompanion) + Assert.assertTrue(listClass.isAbstract) + Assert.assertFalse(listClass.isFinal) + Assert.assertFalse(listClass.isSealed) + } + + @Test + fun testGetRelated() { + LOG.info("Companion Object: {}", TestSubject::class.companionObject) + LOG.info("Companion Object Instance: {}", TestSubject::class.companionObjectInstance) + LOG.info("Object Instance: {}", TestObject::class.objectInstance) + + Assert.assertSame(TestObject, TestObject::class.objectInstance) + } + + @Test + fun testNewInstance() { + val listClass = ArrayList::class + + val list = listClass.createInstance() + Assert.assertTrue(list is ArrayList) + } + + @Test + @Ignore + fun testMembers() { + val bigDecimalClass = BigDecimal::class + + LOG.info("Constructors: {}", bigDecimalClass.constructors) + LOG.info("Functions: {}", bigDecimalClass.functions) + LOG.info("Properties: {}", bigDecimalClass.memberProperties) + LOG.info("Extension Functions: {}", bigDecimalClass.memberExtensionFunctions) + } +} + +class TestSubject { + companion object { + val name = "TestSubject" + } +} + +object TestObject { + val answer = 42 +} diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KMethodTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KMethodTest.kt new file mode 100644 index 0000000000..17e9913731 --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/reflection/KMethodTest.kt @@ -0,0 +1,88 @@ +package com.baeldung.kotlin.reflection + +import org.junit.Assert +import org.junit.Test +import java.io.ByteArrayInputStream +import java.nio.charset.Charset +import kotlin.reflect.KMutableProperty +import kotlin.reflect.full.starProjectedType + +class KMethodTest { + + @Test + fun testCallMethod() { + val str = "Hello" + val lengthMethod = str::length + + Assert.assertEquals(5, lengthMethod()) + } + + @Test + fun testReturnType() { + val str = "Hello" + val method = str::byteInputStream + + Assert.assertEquals(ByteArrayInputStream::class.starProjectedType, method.returnType) + Assert.assertFalse(method.returnType.isMarkedNullable) + } + + @Test + fun testParams() { + val str = "Hello" + val method = str::byteInputStream + + method.isSuspend + Assert.assertEquals(1, method.parameters.size) + Assert.assertTrue(method.parameters[0].isOptional) + Assert.assertFalse(method.parameters[0].isVararg) + Assert.assertEquals(Charset::class.starProjectedType, method.parameters[0].type) + } + + @Test + fun testMethodDetails() { + val codePoints = String::codePoints + Assert.assertEquals("codePoints", codePoints.name) + Assert.assertFalse(codePoints.isSuspend) + Assert.assertFalse(codePoints.isExternal) + Assert.assertFalse(codePoints.isInline) + Assert.assertFalse(codePoints.isOperator) + + val byteInputStream = String::byteInputStream + Assert.assertEquals("byteInputStream", byteInputStream.name) + Assert.assertFalse(byteInputStream.isSuspend) + Assert.assertFalse(byteInputStream.isExternal) + Assert.assertTrue(byteInputStream.isInline) + Assert.assertFalse(byteInputStream.isOperator) + } + + val readOnlyProperty: Int = 42 + lateinit var mutableProperty: String + + @Test + fun testPropertyDetails() { + val roProperty = this::readOnlyProperty + Assert.assertEquals("readOnlyProperty", roProperty.name) + Assert.assertFalse(roProperty.isLateinit) + Assert.assertFalse(roProperty.isConst) + Assert.assertFalse(roProperty is KMutableProperty<*>) + + val mProperty = this::mutableProperty + Assert.assertEquals("mutableProperty", mProperty.name) + Assert.assertTrue(mProperty.isLateinit) + Assert.assertFalse(mProperty.isConst) + Assert.assertTrue(mProperty is KMutableProperty<*>) + } + + @Test + fun testProperty() { + val prop = this::mutableProperty + + Assert.assertEquals(String::class.starProjectedType, prop.getter.returnType) + + prop.set("Hello") + Assert.assertEquals("Hello", prop.get()) + + prop.setter("World") + Assert.assertEquals("World", prop.getter()) + } +} diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java index e708922988..3100f0c70b 100644 --- a/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java +++ b/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java @@ -5,6 +5,7 @@ import java.util.concurrent.ConcurrentHashMap; import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.couchbase.client.java.Bucket; @@ -18,6 +19,11 @@ public class ClusterServiceImpl implements ClusterService { private Cluster cluster; private Map buckets = new ConcurrentHashMap<>(); + + @Autowired + public ClusterServiceImpl(Cluster cluster) { + this.cluster = cluster; + } @PostConstruct private void init() { diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java b/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java index 459585d995..75a196ff5d 100644 --- a/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java +++ b/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java @@ -18,6 +18,7 @@ public class TutorialBucketService extends AbstractBucketService { @Autowired public TutorialBucketService(ClusterService clusterService) { super(clusterService); + openBucket(); } @Override diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java new file mode 100644 index 0000000000..9e650752d2 --- /dev/null +++ b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java @@ -0,0 +1,24 @@ +package com.baeldung.couchbase.async.person; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +import com.couchbase.client.java.Cluster; +import com.couchbase.client.java.CouchbaseCluster; +import com.couchbase.client.java.env.CouchbaseEnvironment; +import com.couchbase.client.java.env.DefaultCouchbaseEnvironment; + +@Configuration +@ComponentScan(basePackages = {"com.baeldung.couchbase.async.service", "com.baeldung.couchbase.n1ql"}) +public class PersonCrudServiceIntegrationTestConfig { + + @Bean + public Cluster cluster() { + CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder() + .connectTimeout(60000) + .build(); + return CouchbaseCluster.create(env, "127.0.0.1"); + } + +} diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java similarity index 90% rename from couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java index 565aaed5da..267071ab35 100644 --- a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTest.java +++ b/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java @@ -1,27 +1,31 @@ package com.baeldung.couchbase.async.person; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.UUID; -import javax.annotation.PostConstruct; - import org.apache.commons.lang3.RandomStringUtils; +import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baeldung.couchbase.async.AsyncIntegrationTest; -import com.baeldung.couchbase.async.person.Person; -import com.baeldung.couchbase.async.person.PersonCrudService; -import com.baeldung.couchbase.async.person.PersonDocumentConverter; import com.baeldung.couchbase.async.service.BucketService; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.document.JsonDocument; -public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest { +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {PersonCrudServiceIntegrationTestConfig.class}) +public class PersonCrudServiceLiveTest extends AsyncIntegrationTest { @Autowired private PersonCrudService personService; @@ -35,8 +39,8 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest { private Bucket bucket; - @PostConstruct - private void init() { + @Before + public void init() { bucket = bucketService.getBucket(); } diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java similarity index 94% rename from couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java index d0db5d37a3..5f478ae788 100644 --- a/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceIntegrationTest.java +++ b/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java @@ -18,7 +18,7 @@ import com.couchbase.client.java.Bucket; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { AsyncIntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public class ClusterServiceIntegrationTest extends AsyncIntegrationTest { +public class ClusterServiceLiveTest extends AsyncIntegrationTest { @Autowired private ClusterService couchbaseService; diff --git a/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java similarity index 98% rename from couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java index 00d462e32a..d260795ed3 100644 --- a/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceIntegrationTest.java +++ b/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java @@ -14,8 +14,8 @@ import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.view.ViewResult; import com.couchbase.client.java.view.ViewRow; -public class StudentGradeServiceIntegrationTest { - private static final Logger logger = LoggerFactory.getLogger(StudentGradeServiceIntegrationTest.class); +public class StudentGradeServiceLiveTest { + private static final Logger logger = LoggerFactory.getLogger(StudentGradeServiceLiveTest.class); static StudentGradeService studentGradeService; static Set gradeIds = new HashSet<>(); diff --git a/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java similarity index 97% rename from couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java index 8112d7d222..602bb5b8a5 100644 --- a/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLIntegrationTest.java +++ b/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java @@ -1,5 +1,23 @@ package com.baeldung.couchbase.n1ql; +import static com.baeldung.couchbase.n1ql.CodeSnippets.extractJsonResult; +import static com.couchbase.client.java.query.Select.select; +import static com.couchbase.client.java.query.dsl.Expression.i; +import static com.couchbase.client.java.query.dsl.Expression.s; +import static com.couchbase.client.java.query.dsl.Expression.x; +import static org.junit.Assert.assertNotNull; + +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Cluster; import com.couchbase.client.java.document.JsonDocument; @@ -10,28 +28,13 @@ import com.couchbase.client.java.query.N1qlQueryResult; import com.couchbase.client.java.query.N1qlQueryRow; import com.couchbase.client.java.query.Statement; import com.fasterxml.jackson.databind.JsonNode; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + import rx.Observable; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import java.util.stream.Stream; - -import static com.baeldung.couchbase.n1ql.CodeSnippets.extractJsonResult; -import static com.couchbase.client.java.query.Select.select; -import static com.couchbase.client.java.query.dsl.Expression.*; -import static org.junit.Assert.assertNotNull; - @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { IntegrationTestConfig.class }) -public class N1QLIntegrationTest { +public class N1QLLiveTest { @Autowired diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java similarity index 97% rename from couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java index ec15be1acc..493b326d49 100644 --- a/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceIntegrationTest.java +++ b/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java @@ -10,7 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired; import com.baeldung.couchbase.spring.IntegrationTest; -public class PersonCrudServiceIntegrationTest extends IntegrationTest { +public class PersonCrudServiceLiveTest extends IntegrationTest { private static final String CLARK_KENT = "Clark Kent"; private static final String SMALLVILLE = "Smallville"; diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java b/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java similarity index 94% rename from couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java rename to couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java index ead247dfbc..7a89a208f7 100644 --- a/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceIntegrationTest.java +++ b/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java @@ -17,7 +17,7 @@ import com.couchbase.client.java.Bucket; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { IntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public class ClusterServiceIntegrationTest extends IntegrationTest { +public class ClusterServiceLiveTest extends IntegrationTest { @Autowired private ClusterService couchbaseService; diff --git a/custom-pmd-0.0.1.jar b/custom-pmd-0.0.1.jar index 4ad6933865..e19bce6e52 100644 Binary files a/custom-pmd-0.0.1.jar and b/custom-pmd-0.0.1.jar differ diff --git a/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java b/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java index 4136165b6f..3b73f9c21c 100644 --- a/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java +++ b/custom-pmd/src/main/java/org/baeldung/pmd/UnitTestNamingConventionRule.java @@ -11,20 +11,20 @@ public class UnitTestNamingConventionRule extends AbstractJavaRule { private static List allowedEndings = Arrays.asList( "IntegrationTest", + "IntTest", "ManualTest", "JdbcTest", "LiveTest", - "UnitTest"); + "UnitTest", + "jmhTest"); public Object visit(ASTClassOrInterfaceDeclaration node, Object data) { String className = node.getImage(); Objects.requireNonNull(className); - if (className.endsWith("Test") || className.endsWith("Tests")) { - if (allowedEndings.stream() - .noneMatch(className::endsWith)) { - addViolation(data, node); - } + if (className.endsWith("Tests") + || (className.endsWith("Test") && allowedEndings.stream().noneMatch(className::endsWith))) { + addViolation(data, node); } return data; diff --git a/dagger/README.md b/dagger/README.md new file mode 100644 index 0000000000..72cba3d3f2 --- /dev/null +++ b/dagger/README.md @@ -0,0 +1,3 @@ +### Relevant articles: + +- [Introduction to Dagger 2](http://www.baeldung.com/dagger-2) diff --git a/dagger/pom.xml b/dagger/pom.xml new file mode 100644 index 0000000000..f927ce42c4 --- /dev/null +++ b/dagger/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + dagger + dagger + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + junit + junit + ${junit.version} + test + + + + + com.google.dagger + dagger + ${dagger.version} + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.1 + + + + com.google.dagger + dagger-compiler + 2.16 + + + + + + + + + 4.12 + 2.16 + + + \ No newline at end of file diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/Brand.java b/dagger/src/main/java/com/baeldung/dagger/intro/Brand.java new file mode 100644 index 0000000000..5ec6607d67 --- /dev/null +++ b/dagger/src/main/java/com/baeldung/dagger/intro/Brand.java @@ -0,0 +1,45 @@ +package com.baeldung.dagger.intro; + +/** + * Brand of a {@link Car}. + * + * @author Donato Rimenti + * + */ +public class Brand { + + /** + * The name of the brand. + */ + private String name; + + /** + * Instantiates a new Brand. + * + * @param name + * the {@link #name} + */ + public Brand(String name) { + this.name = name; + } + + /** + * Gets the {@link #name}. + * + * @return the {@link #name} + */ + public String getName() { + return name; + } + + /** + * Sets the {@link #name}. + * + * @param name + * the new {@link #name} + */ + public void setName(String name) { + this.name = name; + } + +} diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/Car.java b/dagger/src/main/java/com/baeldung/dagger/intro/Car.java new file mode 100644 index 0000000000..2ad81b8f6c --- /dev/null +++ b/dagger/src/main/java/com/baeldung/dagger/intro/Car.java @@ -0,0 +1,75 @@ +package com.baeldung.dagger.intro; + +import javax.inject.Inject; + +/** + * Represents a car. + * + * @author Donato Rimenti + * + */ +public class Car { + + /** + * The car's engine. + */ + private Engine engine; + + /** + * The car's brand. + */ + private Brand brand; + + /** + * Instantiates a new Car. + * + * @param engine + * the {@link #engine} + * @param brand + * the {@link #brand} + */ + @Inject + public Car(Engine engine, Brand brand) { + this.engine = engine; + this.brand = brand; + } + + /** + * Gets the {@link #engine}. + * + * @return the {@link #engine} + */ + public Engine getEngine() { + return engine; + } + + /** + * Sets the {@link #engine}. + * + * @param engine + * the new {@link #engine} + */ + public void setEngine(Engine engine) { + this.engine = engine; + } + + /** + * Gets the {@link #brand}. + * + * @return the {@link #brand} + */ + public Brand getBrand() { + return brand; + } + + /** + * Sets the {@link #brand}. + * + * @param brand + * the new {@link #brand} + */ + public void setBrand(Brand brand) { + this.brand = brand; + } + +} diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/Engine.java b/dagger/src/main/java/com/baeldung/dagger/intro/Engine.java new file mode 100644 index 0000000000..99e30625cd --- /dev/null +++ b/dagger/src/main/java/com/baeldung/dagger/intro/Engine.java @@ -0,0 +1,24 @@ +package com.baeldung.dagger.intro; + +/** + * Engine of a {@link Car}. + * + * @author Donato Rimenti + * + */ +public class Engine { + + /** + * Starts the engine. + */ + public void start() { + System.out.println("Engine started"); + } + + /** + * Stops the engine. + */ + public void stop() { + System.out.println("Engine stopped"); + } +} diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesComponent.java b/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesComponent.java new file mode 100644 index 0000000000..aeeaab636e --- /dev/null +++ b/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesComponent.java @@ -0,0 +1,24 @@ +package com.baeldung.dagger.intro; + +import javax.inject.Singleton; + +import dagger.Component; + +/** + * Dagger component for building vehicles. + * + * @author Donato Rimenti + * + */ +@Singleton +@Component(modules = VehiclesModule.class) +public interface VehiclesComponent { + + /** + * Builds a {@link Car}. + * + * @return a {@link Car} + */ + public Car buildCar(); + +} \ No newline at end of file diff --git a/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesModule.java b/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesModule.java new file mode 100644 index 0000000000..f6c6e4a108 --- /dev/null +++ b/dagger/src/main/java/com/baeldung/dagger/intro/VehiclesModule.java @@ -0,0 +1,37 @@ +package com.baeldung.dagger.intro; + +import javax.inject.Singleton; + +import dagger.Module; +import dagger.Provides; + +/** + * Dagger module for providing vehicles components. + * + * @author Donato Rimenti + * + */ +@Module +public class VehiclesModule { + + /** + * Creates an {@link Engine}. + * + * @return an {@link Engine} + */ + @Provides + public Engine provideEngine() { + return new Engine(); + } + + /** + * Creates a {@link Brand}. + * + * @return a {@link Brand} + */ + @Provides + @Singleton + public Brand provideBrand() { + return new Brand("Baeldung"); + } +} \ No newline at end of file diff --git a/dagger/src/test/java/com/baeldung/dagger/intro/DaggerUnitTest.java b/dagger/src/test/java/com/baeldung/dagger/intro/DaggerUnitTest.java new file mode 100644 index 0000000000..83e881ffe1 --- /dev/null +++ b/dagger/src/test/java/com/baeldung/dagger/intro/DaggerUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.dagger.intro; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Unit test for building a {@link Car} using Dagger. + * + * @author Donato Rimenti + * + */ +public class DaggerUnitTest { + + /** + * Builds two {@link Car} and checks that the fields are injected correctly. + */ + @Test + public void givenGeneratedComponent_whenBuildingCar_thenDependenciesInjected() { + VehiclesComponent component = DaggerVehiclesComponent.create(); + + Car carOne = component.buildCar(); + Car carTwo = component.buildCar(); + + Assert.assertNotNull(carOne); + Assert.assertNotNull(carTwo); + Assert.assertNotNull(carOne.getEngine()); + Assert.assertNotNull(carTwo.getEngine()); + Assert.assertNotNull(carOne.getBrand()); + Assert.assertNotNull(carTwo.getBrand()); + Assert.assertNotEquals(carOne.getEngine(), carTwo.getEngine()); + Assert.assertEquals(carOne.getBrand(), carTwo.getBrand()); + } + +} diff --git a/deltaspike/pom.xml b/deltaspike/pom.xml index 87f532c3f3..7f4491117b 100644 --- a/deltaspike/pom.xml +++ b/deltaspike/pom.xml @@ -9,6 +9,13 @@ deltaspike A starter Java EE 7 webapp which uses DeltaSpike http://wildfly.org + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + Apache License, Version 2.0 @@ -16,12 +23,12 @@ http://www.apache.org/licenses/LICENSE-2.0.html - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + + redhat-repository-techpreview + https://maven.repository.redhat.com/techpreview/all/ + + @@ -47,6 +54,13 @@ pom import + + org.apache.deltaspike.distribution + distributions-bom + ${deltaspike.version} + pom + import + @@ -160,14 +174,12 @@ org.apache.deltaspike.modules deltaspike-data-module-api - ${deltaspike.version} compile org.apache.deltaspike.modules deltaspike-data-module-impl - ${deltaspike.version} runtime @@ -184,6 +196,71 @@ querydsl-jpa ${querydsl.version} + + + org.apache.deltaspike.modules + deltaspike-test-control-module-api + test + + + + org.apache.deltaspike.modules + deltaspike-test-control-module-impl + test + + + + org.apache.deltaspike.cdictrl + deltaspike-cdictrl-weld + test + + + + org.jboss.weld.se + weld-se-core + ${weld.version} + test + + + + org.hibernate + hibernate-core + provided + + + + org.jboss + jandex + 1.2.5.Final-redhat-1 + + + + com.h2database + h2 + 1.4.197 + test + + + + org.hibernate + hibernate-entitymanager + provided + + + + + junit + junit + test + + + + + org.apache.commons + commons-lang3 + 3.5 + + @@ -226,28 +303,6 @@ - - - - default - - true - - - - - maven-surefire-plugin - ${maven-surefire-plugin.version} - - true - - - - - - UTF-8 3.7.4 - 1.7.2 + 1.8.2 1.0.2.Final - 8.2.2.Final + 8.2.1.Final + 2.1.2.Final 2.6 1.1.3 + 1.8 + 1.8 diff --git a/deltaspike/src/main/java/baeldung/controller/MemberController.java b/deltaspike/src/main/java/baeldung/controller/MemberController.java index 7a9e9800f4..eba36355b7 100644 --- a/deltaspike/src/main/java/baeldung/controller/MemberController.java +++ b/deltaspike/src/main/java/baeldung/controller/MemberController.java @@ -16,6 +16,9 @@ */ package baeldung.controller; +import baeldung.model.Member; +import baeldung.service.MemberRegistration; + import javax.annotation.PostConstruct; import javax.enterprise.inject.Model; import javax.enterprise.inject.Produces; @@ -24,9 +27,6 @@ import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; -import baeldung.model.Member; -import baeldung.service.MemberRegistration; - // The @Model stereotype is a convenience mechanism to make this a request-scoped bean that has an // EL name // Read more about the @Model stereotype in this FAQ: @@ -34,11 +34,9 @@ import baeldung.service.MemberRegistration; @Model public class MemberController { - @Inject - private FacesContext facesContext; + @Inject private FacesContext facesContext; - @Inject - private MemberRegistration memberRegistration; + @Inject private MemberRegistration memberRegistration; @Produces @Named diff --git a/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java b/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java index 9189dbba74..6c2387012d 100644 --- a/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java +++ b/deltaspike/src/main/java/baeldung/data/EntityManagerProducer.java @@ -1,29 +1,18 @@ package baeldung.data; -import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; -import javax.enterprise.inject.Default; -import javax.enterprise.inject.Disposes; import javax.enterprise.inject.Produces; import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.PersistenceUnit; +import javax.persistence.PersistenceContext; -@ApplicationScoped public class EntityManagerProducer { - @PersistenceUnit(unitName = "primary") - private EntityManagerFactory entityManagerFactory; - @Produces - @Default + @PersistenceContext(unitName = "primary") private EntityManager entityManager; + @RequestScoped + @Produces public EntityManager create() { - return this.entityManagerFactory.createEntityManager(); + return entityManager; } - public void dispose(@Disposes @Default EntityManager entityManager) { - if (entityManager.isOpen()) { - entityManager.close(); - } - } } \ No newline at end of file diff --git a/deltaspike/src/main/java/baeldung/data/MemberListProducer.java b/deltaspike/src/main/java/baeldung/data/MemberListProducer.java index c1f5fda31d..989bcea917 100644 --- a/deltaspike/src/main/java/baeldung/data/MemberListProducer.java +++ b/deltaspike/src/main/java/baeldung/data/MemberListProducer.java @@ -16,6 +16,8 @@ */ package baeldung.data; +import baeldung.model.Member; + import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.enterprise.event.Observes; @@ -25,13 +27,10 @@ import javax.inject.Inject; import javax.inject.Named; import java.util.List; -import baeldung.model.Member; - @RequestScoped public class MemberListProducer { - @Inject - private MemberRepository memberRepository; + @Inject private MemberRepository memberRepository; private List members; diff --git a/deltaspike/src/main/java/baeldung/data/MemberRepository.java b/deltaspike/src/main/java/baeldung/data/MemberRepository.java index 220388bcf0..e9c7e52f9c 100644 --- a/deltaspike/src/main/java/baeldung/data/MemberRepository.java +++ b/deltaspike/src/main/java/baeldung/data/MemberRepository.java @@ -18,7 +18,10 @@ package baeldung.data; import baeldung.model.Member; import baeldung.model.QMember; -import org.apache.deltaspike.data.api.*; +import org.apache.deltaspike.data.api.AbstractEntityRepository; +import org.apache.deltaspike.data.api.EntityManagerConfig; +import org.apache.deltaspike.data.api.Query; +import org.apache.deltaspike.data.api.Repository; import java.util.List; @@ -35,6 +38,9 @@ public abstract class MemberRepository extends AbstractEntityRepository findAllOrderedByNameWithQueryDSL() { final QMember member = QMember.member; - return jpaQuery().from(member).orderBy(member.email.asc()).list(member); + return jpaQuery() + .from(member) + .orderBy(member.email.asc()) + .list(member); } } diff --git a/deltaspike/src/main/java/baeldung/data/QueryDslRepositoryExtension.java b/deltaspike/src/main/java/baeldung/data/QueryDslRepositoryExtension.java index 8cb00958ab..4bb8a629de 100644 --- a/deltaspike/src/main/java/baeldung/data/QueryDslRepositoryExtension.java +++ b/deltaspike/src/main/java/baeldung/data/QueryDslRepositoryExtension.java @@ -8,8 +8,7 @@ import javax.inject.Inject; public class QueryDslRepositoryExtension implements QueryDslSupport, DelegateQueryHandler { - @Inject - private QueryInvocationContext context; + @Inject private QueryInvocationContext context; @Override public JPAQuery jpaQuery() { diff --git a/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java b/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java index 41d30d9018..606def4f30 100644 --- a/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java +++ b/deltaspike/src/main/java/baeldung/data/SecondaryEntityManagerProducer.java @@ -2,29 +2,20 @@ package baeldung.data; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.RequestScoped; -import javax.enterprise.inject.Default; -import javax.enterprise.inject.Disposes; import javax.enterprise.inject.Produces; import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.PersistenceUnit; +import javax.persistence.PersistenceContext; @ApplicationScoped public class SecondaryEntityManagerProducer { - @PersistenceUnit(unitName = "secondary") - private EntityManagerFactory entityManagerFactory; + + @PersistenceContext(unitName = "secondary") private EntityManager entityManager; @Produces - @Default @RequestScoped @SecondaryPersistenceUnit public EntityManager create() { - return this.entityManagerFactory.createEntityManager(); + return entityManager; } - public void dispose(@Disposes @Default EntityManager entityManager) { - if (entityManager.isOpen()) { - entityManager.close(); - } - } } \ No newline at end of file diff --git a/deltaspike/src/main/java/baeldung/data/SimpleUserRepository.java b/deltaspike/src/main/java/baeldung/data/SimpleUserRepository.java new file mode 100644 index 0000000000..9ea6115f11 --- /dev/null +++ b/deltaspike/src/main/java/baeldung/data/SimpleUserRepository.java @@ -0,0 +1,45 @@ +package baeldung.data; + +import baeldung.model.User; +import org.apache.deltaspike.data.api.FirstResult; +import org.apache.deltaspike.data.api.MaxResults; +import org.apache.deltaspike.data.api.Repository; + +import java.util.Collection; +import java.util.List; + +/** + * Created by adam. + */ +@Repository(forEntity = User.class) +public abstract class SimpleUserRepository { + public abstract Collection findAll(); + + public abstract Collection findAllOrderByFirstNameAsc(@FirstResult int start, @MaxResults int size); + + public abstract Collection findTop2OrderByFirstNameAsc(); + + public abstract Collection findFirst2OrderByFirstNameAsc(); + + public abstract List findAllOrderByFirstNameAsc(); + + public abstract List findAllOrderByFirstNameAscLastNameDesc(); + + public abstract User findById(Long id); + + public abstract Collection findByFirstName(String firstName); + + public abstract User findAnyByLastName(String lastName); + + public abstract Collection findAnyByFirstName(String firstName); + + public abstract Collection findByFirstNameAndLastName(String firstName, String lastName); + + public abstract Collection findByFirstNameOrLastName(String firstName, String lastName); + + public abstract Collection findByAddress_city(String city); + + public abstract int count(); + + public abstract void remove(User user); +} diff --git a/deltaspike/src/main/java/baeldung/data/UserRepository.java b/deltaspike/src/main/java/baeldung/data/UserRepository.java new file mode 100644 index 0000000000..688e46f5fc --- /dev/null +++ b/deltaspike/src/main/java/baeldung/data/UserRepository.java @@ -0,0 +1,31 @@ +package baeldung.data; + +import baeldung.model.User; +import org.apache.deltaspike.data.api.AbstractEntityRepository; +import org.apache.deltaspike.data.api.Query; +import org.apache.deltaspike.data.api.Repository; + +import java.util.Collection; +import java.util.List; + +/** + * Created by adam. + */ +@Repository +public abstract class UserRepository extends AbstractEntityRepository { + + public List findByFirstName(String firstName) { + return typedQuery("select u from User u where u.firstName = ?1") + .setParameter(1, firstName) + .getResultList(); + } + + public abstract List findByLastName(String lastName); + + @Query("select u from User u where u.firstName = ?1") + public abstract Collection findUsersWithFirstName(String firstName); + + @Query(value = "select * from User where firstName = ?1", isNative = true) + public abstract Collection findUsersWithFirstNameNative(String firstName); + +} diff --git a/deltaspike/src/main/java/baeldung/model/Address.java b/deltaspike/src/main/java/baeldung/model/Address.java new file mode 100644 index 0000000000..ef0d461b9c --- /dev/null +++ b/deltaspike/src/main/java/baeldung/model/Address.java @@ -0,0 +1,51 @@ +package baeldung.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +/** + * Created by adam. + */ +@Entity +public class Address { + + @Id + @GeneratedValue + private Long id; + private String street; + private String city; + private String postCode; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getPostCode() { + return postCode; + } + + public void setPostCode(String postCode) { + this.postCode = postCode; + } +} diff --git a/deltaspike/src/main/java/baeldung/model/Member.java b/deltaspike/src/main/java/baeldung/model/Member.java index e178dcf63a..d9b9b5caf1 100644 --- a/deltaspike/src/main/java/baeldung/model/Member.java +++ b/deltaspike/src/main/java/baeldung/model/Member.java @@ -16,22 +16,16 @@ */ package baeldung.model; -import java.io.Serializable; +import org.hibernate.validator.constraints.Email; +import org.hibernate.validator.constraints.NotEmpty; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.UniqueConstraint; +import javax.persistence.*; import javax.validation.constraints.Digits; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; - -import org.hibernate.validator.constraints.Email; -import org.hibernate.validator.constraints.NotEmpty; +import java.io.Serializable; @SuppressWarnings("serial") @Entity diff --git a/deltaspike/src/main/java/baeldung/model/User.java b/deltaspike/src/main/java/baeldung/model/User.java new file mode 100644 index 0000000000..5560ea0e7c --- /dev/null +++ b/deltaspike/src/main/java/baeldung/model/User.java @@ -0,0 +1,52 @@ +package baeldung.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +/** + * Created by adam. + */ +@Entity +public class User { + + @Id + @GeneratedValue + private Long id; + private String firstName; + private String lastName; + @OneToOne private Address address; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } +} diff --git a/deltaspike/src/main/resources/META-INF/beans.xml b/deltaspike/src/main/resources/META-INF/beans.xml new file mode 100644 index 0000000000..f462814752 --- /dev/null +++ b/deltaspike/src/main/resources/META-INF/beans.xml @@ -0,0 +1,5 @@ + + diff --git a/deltaspike/src/test/java/baeldung/ValidatorProducer.java b/deltaspike/src/test/java/baeldung/ValidatorProducer.java new file mode 100644 index 0000000000..6b895f771e --- /dev/null +++ b/deltaspike/src/test/java/baeldung/ValidatorProducer.java @@ -0,0 +1,21 @@ +package baeldung; + +import javax.enterprise.inject.Produces; +import javax.validation.Validation; +import javax.validation.Validator; + +/** + * Created by adam. + */ +public class ValidatorProducer { + + @Produces + public Validator createValidator() { + return Validation + .byDefaultProvider() + .configure() + .buildValidatorFactory() + .getValidator(); + } + +} diff --git a/deltaspike/src/test/java/baeldung/data/TestEntityManagerProducer.java b/deltaspike/src/test/java/baeldung/data/TestEntityManagerProducer.java new file mode 100644 index 0000000000..139760d7fc --- /dev/null +++ b/deltaspike/src/test/java/baeldung/data/TestEntityManagerProducer.java @@ -0,0 +1,23 @@ +package baeldung.data; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.Produces; +import javax.enterprise.inject.Specializes; +import javax.persistence.EntityManager; +import javax.persistence.Persistence; + +/** + * Created by adam. + */ +public class TestEntityManagerProducer extends EntityManagerProducer { + + @ApplicationScoped + @Produces + @Specializes + public EntityManager create() { + return Persistence + .createEntityManagerFactory("pu-test") + .createEntityManager(); + } + +} diff --git a/deltaspike/src/test/java/baeldung/test/MemberRegistrationIntegrationTest.java b/deltaspike/src/test/java/baeldung/test/MemberRegistrationIntegrationTest.java index 2b6cfe2b02..6db09abaae 100644 --- a/deltaspike/src/test/java/baeldung/test/MemberRegistrationIntegrationTest.java +++ b/deltaspike/src/test/java/baeldung/test/MemberRegistrationIntegrationTest.java @@ -16,19 +16,12 @@ */ package baeldung.test; -import static org.junit.Assert.assertNotNull; - -import java.io.File; -import java.util.logging.Logger; - -import javax.inject.Inject; - import baeldung.data.*; -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.junit.Arquillian; import baeldung.model.Member; import baeldung.service.MemberRegistration; import baeldung.util.Resources; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; @@ -37,24 +30,39 @@ import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Test; import org.junit.runner.RunWith; +import javax.inject.Inject; +import java.io.File; +import java.util.logging.Logger; + +import static org.junit.Assert.assertNotNull; + @RunWith(Arquillian.class) public class MemberRegistrationIntegrationTest { @Deployment public static Archive createTestArchive() { - File[] files = Maven.resolver().loadPomFromFile("pom.xml").importRuntimeDependencies().resolve().withTransitivity().asFile(); + File[] files = Maven + .resolver() + .loadPomFromFile("pom.xml") + .importRuntimeDependencies() + .resolve() + .withTransitivity() + .asFile(); - return ShrinkWrap.create(WebArchive.class, "test.war") - .addClasses(EntityManagerProducer.class, Member.class, MemberRegistration.class, MemberRepository.class, Resources.class, QueryDslRepositoryExtension.class, QueryDslSupport.class, SecondaryPersistenceUnit.class, - SecondaryEntityManagerProducer.class, SecondaryEntityManagerResolver.class) - .addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml").addAsResource("META-INF/apache-deltaspike.properties").addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml").addAsWebInfResource("test-ds.xml") - .addAsWebInfResource("test-secondary-ds.xml").addAsLibraries(files); + return ShrinkWrap + .create(WebArchive.class, "test.war") + .addClasses(EntityManagerProducer.class, Member.class, MemberRegistration.class, MemberRepository.class, Resources.class, QueryDslRepositoryExtension.class, QueryDslSupport.class, SecondaryPersistenceUnit.class, SecondaryEntityManagerProducer.class, + SecondaryEntityManagerResolver.class) + .addAsResource("META-INF/persistence.xml", "META-INF/persistence.xml") + .addAsResource("META-INF/apache-deltaspike.properties") + .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") + .addAsWebInfResource("test-ds.xml") + .addAsWebInfResource("test-secondary-ds.xml") + .addAsLibraries(files); } - @Inject - MemberRegistration memberRegistration; + @Inject MemberRegistration memberRegistration; - @Inject - Logger log; + @Inject Logger log; @Test public void testRegister() throws Exception { diff --git a/deltaspike/src/test/java/baeldung/test/SimpleUserRepositoryUnitTest.java b/deltaspike/src/test/java/baeldung/test/SimpleUserRepositoryUnitTest.java new file mode 100644 index 0000000000..2065338c77 --- /dev/null +++ b/deltaspike/src/test/java/baeldung/test/SimpleUserRepositoryUnitTest.java @@ -0,0 +1,133 @@ +package baeldung.test; + +import baeldung.data.SimpleUserRepository; +import baeldung.model.User; +import org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner; +import org.junit.Test; +import org.junit.runner.RunWith; + +import javax.inject.Inject; +import javax.persistence.EntityManager; +import java.util.List; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.assertThat; + +/** + * Created by adam. + */ +@RunWith(CdiTestRunner.class) +public class SimpleUserRepositoryUnitTest { + + @Inject private EntityManager entityManager; + + @Inject private SimpleUserRepository simpleUserRepository; + + @Test + public void givenFourUsersWhenFindAllShouldReturnFourUsers() { + assertThat(simpleUserRepository + .findAll() + .size(), equalTo(4)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenFindByFirstNameShouldReturnTwoUsers() { + assertThat(simpleUserRepository + .findByFirstName("Adam") + .size(), equalTo(2)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenFindAnyByFirstNameShouldReturnTwoUsers() { + assertThat(simpleUserRepository + .findAnyByFirstName("Adam") + .size(), equalTo(2)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenCountByFirstNameShouldReturnSizeTwo() { + assertThat(simpleUserRepository.count(), equalTo(4)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenRemoveByFirstNameShouldReturnSizeTwo() { + simpleUserRepository.remove(entityManager.merge(simpleUserRepository.findById(1L))); + assertThat(entityManager.find(User.class, 1L), nullValue()); + } + + @Test + public void givenOneUserWithSpecifiedFirstNameAndLastNameWhenFindByFirstNameAndLastNameShouldReturnOneUser() { + assertThat(simpleUserRepository + .findByFirstNameAndLastName("Adam", "LastName1") + .size(), equalTo(1)); + assertThat(simpleUserRepository + .findByFirstNameAndLastName("David", "LastName2") + .size(), equalTo(1)); + } + + @Test + public void givenOneUserWithSpecifiedLastNameWhenFindAnyByLastNameShouldReturnOneUser() { + assertThat(simpleUserRepository.findAnyByLastName("LastName1"), notNullValue()); + } + + @Test + public void givenOneUserWithSpecifiedAddressCityWhenFindByCityShouldReturnOneUser() { + assertThat(simpleUserRepository + .findByAddress_city("London") + .size(), equalTo(1)); + } + + @Test + public void givenUsersWithSpecifiedFirstOrLastNameWhenFindByFirstNameOrLastNameShouldReturnTwoUsers() { + assertThat(simpleUserRepository + .findByFirstNameOrLastName("David", "LastName1") + .size(), equalTo(2)); + } + + @Test + public void givenUsersWhenFindAllOrderByFirstNameAscShouldReturnFirstAdamLastPeter() { + List users = simpleUserRepository.findAllOrderByFirstNameAsc(); + assertThat(users + .get(0) + .getFirstName(), equalTo("Adam")); + assertThat(users + .get(3) + .getFirstName(), equalTo("Peter")); + } + + @Test + public void givenUsersWhenFindAllOrderByFirstNameAscLastNameDescShouldReturnFirstAdamLastPeter() { + List users = simpleUserRepository.findAllOrderByFirstNameAscLastNameDesc(); + assertThat(users + .get(0) + .getFirstName(), equalTo("Adam")); + assertThat(users + .get(3) + .getFirstName(), equalTo("Peter")); + } + + @Test + public void givenUsersWhenFindTop2ShouldReturnTwoUsers() { + assertThat(simpleUserRepository + .findTop2OrderByFirstNameAsc() + .size(), equalTo(2)); + } + + @Test + public void givenUsersWhenFindFirst2ShouldReturnTwoUsers() { + assertThat(simpleUserRepository + .findFirst2OrderByFirstNameAsc() + .size(), equalTo(2)); + } + + @Test + public void givenPagesWithSizeTwoWhenFindAllOrderByFirstNameAscShouldReturnTwoPages() { + assertThat(simpleUserRepository + .findAllOrderByFirstNameAsc(0, 2) + .size(), equalTo(2)); + assertThat(simpleUserRepository + .findAllOrderByFirstNameAsc(2, 4) + .size(), equalTo(2)); + } + +} diff --git a/deltaspike/src/test/java/baeldung/test/UserRepositoryUnitTest.java b/deltaspike/src/test/java/baeldung/test/UserRepositoryUnitTest.java new file mode 100644 index 0000000000..bd07bf2730 --- /dev/null +++ b/deltaspike/src/test/java/baeldung/test/UserRepositoryUnitTest.java @@ -0,0 +1,55 @@ +package baeldung.test; + +import baeldung.data.UserRepository; +import org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner; +import org.junit.Test; +import org.junit.runner.RunWith; + +import javax.inject.Inject; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + +/** + * Created by adam. + */ +@RunWith(CdiTestRunner.class) +public class UserRepositoryUnitTest { + + @Inject private UserRepository userRepository; + + @Test + public void givenFourUsersWhenFindAllShouldReturnFourUsers() { + assertThat(userRepository + .findAll() + .size(), equalTo(4)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenFindByFirstNameShouldReturnTwoUsers() { + assertThat(userRepository + .findByFirstName("Adam") + .size(), equalTo(2)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenFindUsersWithFirstNameShouldReturnTwoUsers() { + assertThat(userRepository + .findUsersWithFirstName("Adam") + .size(), equalTo(2)); + } + + @Test + public void givenTwoUsersWithSpecifiedNameWhenFindUsersWithFirstNameNativeShouldReturnTwoUsers() { + assertThat(userRepository + .findUsersWithFirstNameNative("Adam") + .size(), equalTo(2)); + } + + @Test + public void givenTwoUsersWithSpecifiedLastNameWhenFindByLastNameShouldReturnTwoUsers() { + assertThat(userRepository + .findByLastName("LastName3") + .size(), equalTo(2)); + } +} diff --git a/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties b/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties index a861ad729a..787e58ade0 100644 --- a/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties +++ b/deltaspike/src/test/resources/META-INF/apache-deltaspike.properties @@ -1 +1,3 @@ globalAlternatives.org.apache.deltaspike.jpa.spi.transaction.TransactionStrategy=org.apache.deltaspike.jpa.impl.transaction.BeanManagedUserTransactionStrategy +org.apache.deltaspike.ProjectStage=UnitTest +deltaspike.testcontrol.stop_container=false \ No newline at end of file diff --git a/deltaspike/src/test/resources/META-INF/beans.xml b/deltaspike/src/test/resources/META-INF/beans.xml new file mode 100644 index 0000000000..346b484f2f --- /dev/null +++ b/deltaspike/src/test/resources/META-INF/beans.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/deltaspike/src/test/resources/META-INF/test-persistence.xml b/deltaspike/src/test/resources/META-INF/persistence.xml similarity index 53% rename from deltaspike/src/test/resources/META-INF/test-persistence.xml rename to deltaspike/src/test/resources/META-INF/persistence.xml index bc9fbcbeef..ee69855138 100644 --- a/deltaspike/src/test/resources/META-INF/test-persistence.xml +++ b/deltaspike/src/test/resources/META-INF/persistence.xml @@ -11,6 +11,7 @@ + java:jboss/datasources/baeldung-jee7-seedTestSecondaryDS @@ -18,4 +19,23 @@ + + + org.hibernate.jpa.HibernatePersistenceProvider + + baeldung.model.User + baeldung.model.Address + + + + + + + + + + + + + diff --git a/deltaspike/src/test/resources/arquillian.xml b/deltaspike/src/test/resources/arquillian.xml index 14f9e53bbd..7f02023089 100644 --- a/deltaspike/src/test/resources/arquillian.xml +++ b/deltaspike/src/test/resources/arquillian.xml @@ -28,12 +28,4 @@ - - - - - target\wildfly-run\wildfly-10.0.0.Final - - - diff --git a/deltaspike/src/test/resources/import.sql b/deltaspike/src/test/resources/import.sql new file mode 100644 index 0000000000..f6e06ecee4 --- /dev/null +++ b/deltaspike/src/test/resources/import.sql @@ -0,0 +1,6 @@ +INSERT INTO ADDRESS(ID, STREET, CITY, POSTCODE) VALUES (1, 'Oxford', 'London', 'N121'); + +INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (1, 'Adam', 'LastName1', null); +INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (2, 'David', 'LastName2', null); +INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (3, 'Adam', 'LastName3', null); +INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (4, 'Peter', 'LastName3', 1); \ No newline at end of file diff --git a/drools/pom.xml b/drools/pom.xml index 60df7157f2..a060563eeb 100644 --- a/drools/pom.xml +++ b/drools/pom.xml @@ -6,9 +6,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -54,7 +54,6 @@ 4.4.6 7.4.1.Final 3.13 - 4.3.6.RELEASE diff --git a/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingTest.java b/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingIntegrationTest.java similarity index 95% rename from drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingTest.java rename to drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingIntegrationTest.java index f49d0b82de..fd49f94479 100644 --- a/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingTest.java +++ b/drools/src/test/java/com/baeldung/drools/backward_chaining/BackwardChainingIntegrationTest.java @@ -10,7 +10,7 @@ import com.baeldung.drools.model.Result; import static junit.framework.TestCase.assertEquals; -public class BackwardChainingTest { +public class BackwardChainingIntegrationTest { private Result result; private KieSession ksession; diff --git a/ejb/ejb-client/pom.xml b/ejb/ejb-client/pom.xml index 83dd0aef30..88116f8003 100755 --- a/ejb/ejb-client/pom.xml +++ b/ejb/ejb-client/pom.xml @@ -3,7 +3,6 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 ejb-client - EJB3 Client Maven EJB3 Client Maven diff --git a/ethereumj/README.md b/ethereumj/README.md index 5a0be0bd16..320ae8c9f8 100644 --- a/ethereumj/README.md +++ b/ethereumj/README.md @@ -3,3 +3,4 @@ ### Relevant Articles: - [Introduction to EthereumJ](http://www.baeldung.com/ethereumj) - [Creating and Deploying Smart Contracts with Solidity](http://www.baeldung.com/smart-contracts-ethereum-solidity) +- [Lightweight Ethereum Clients Using Web3j](http://www.baeldung.com/web3j) diff --git a/ethereumj/pom.xml b/ethereumj/pom.xml index 611b7b09eb..6917505f1b 100644 --- a/ethereumj/pom.xml +++ b/ethereumj/pom.xml @@ -10,10 +10,10 @@ ethereumj - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/flips/pom.xml b/flips/pom.xml index be9f584114..34cbab7035 100644 --- a/flips/pom.xml +++ b/flips/pom.xml @@ -8,10 +8,10 @@ flips - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/flips/src/main/java/com/baeldung/flips/model/Foo.java b/flips/src/main/java/com/baeldung/flips/model/Foo.java index d98abb79a9..be15bee15c 100644 --- a/flips/src/main/java/com/baeldung/flips/model/Foo.java +++ b/flips/src/main/java/com/baeldung/flips/model/Foo.java @@ -1,11 +1,12 @@ package com.baeldung.flips.model; import lombok.Data; +import lombok.NonNull; import lombok.RequiredArgsConstructor; @Data @RequiredArgsConstructor public class Foo { - private final String name; - private final int id; + @NonNull private final String name; + @NonNull private final int id; } diff --git a/flips/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java b/flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java similarity index 96% rename from flips/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java rename to flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java index 1b8c78e2a4..9dd4ef064a 100644 --- a/flips/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java +++ b/flips/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java @@ -20,10 +20,10 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; "first.active.after=2999-03-15T00:00:00Z", "logging.level.org.flips=info" -}) +}, webEnvironment = SpringBootTest.WebEnvironment.MOCK) @AutoConfigureMockMvc @ActiveProfiles("dev") -public class FlipControllerTest { +public class FlipControllerIntegrationTest { @Autowired private MockMvc mvc; diff --git a/flyway/pom.xml b/flyway/pom.xml index 3637f1de28..018f9b7f86 100644 --- a/flyway/pom.xml +++ b/flyway/pom.xml @@ -8,10 +8,10 @@ Flyway Callbacks Demo - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/grpc/pom.xml b/grpc/pom.xml index ad563f16fd..fb8312e8df 100644 --- a/grpc/pom.xml +++ b/grpc/pom.xml @@ -5,8 +5,6 @@ grpc-demo 0.0.1-SNAPSHOT jar - grpc-demo - http://maven.apache.org com.baeldung diff --git a/gson/README.md b/gson/README.md index 60c80477b1..bedfbd206c 100644 --- a/gson/README.md +++ b/gson/README.md @@ -6,3 +6,4 @@ ### Relevant Articles: - [Gson Deserialization Cookbook](http://www.baeldung.com/gson-deserialization-guide) - [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson) +- [Exclude Fields from Serialization in Gson](http://www.baeldung.com/gson-exclude-fields-serialization) diff --git a/gson/pom.xml b/gson/pom.xml index 912111374d..9ef775122c 100644 --- a/gson/pom.xml +++ b/gson/pom.xml @@ -1,67 +1,74 @@ - - 4.0.0 - com.baeldung - gson - 0.1-SNAPSHOT - gson + + 4.0.0 + com.baeldung + gson + 0.1-SNAPSHOT + gson - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + - - - - joda-time - joda-time - ${joda-time.version} - - - commons-io - commons-io - ${commons-io.version} - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - com.google.code.gson - gson - ${gson.version} - - + + + + org.projectlombok + lombok + 1.16.10 + provided + + + joda-time + joda-time + ${joda-time.version} + + + commons-io + commons-io + ${commons-io.version} + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + com.google.code.gson + gson + ${gson.version} + + - - gson - - - src/main/resources - true - - - + + gson + + + src/main/resources + true + + + - - - 2.8.0 - - 19.0 - 3.5 - 4.1 - 2.5 - 2.9.6 - + + + 2.8.0 + + 19.0 + 3.5 + 4.1 + 2.5 + 2.9.6 + \ No newline at end of file diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/Exclude.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/Exclude.java new file mode 100644 index 0000000000..429cb9d1b5 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/Exclude.java @@ -0,0 +1,11 @@ +package org.baeldung.gson.serializationwithexclusions; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface Exclude { +} \ No newline at end of file diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClass.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClass.java new file mode 100644 index 0000000000..cc6c498458 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClass.java @@ -0,0 +1,13 @@ +package org.baeldung.gson.serializationwithexclusions; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MyClass { + private long id; + private String name; + private String other; + private MySubClass subclass; +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithAnnotatedFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithAnnotatedFields.java new file mode 100644 index 0000000000..5d41f8a224 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithAnnotatedFields.java @@ -0,0 +1,20 @@ +package org.baeldung.gson.serializationwithexclusions; + +import com.google.gson.annotations.Expose; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MyClassWithAnnotatedFields { + + @Expose + private long id; + @Expose + private String name; + private String other; + @Expose + private MySubClassWithAnnotatedFields subclass; + +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithCustomAnnotatedFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithCustomAnnotatedFields.java new file mode 100644 index 0000000000..ace3583013 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithCustomAnnotatedFields.java @@ -0,0 +1,16 @@ +package org.baeldung.gson.serializationwithexclusions; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MyClassWithCustomAnnotatedFields { + + private long id; + private String name; + @Exclude + private String other; + private MySubClassWithCustomAnnotatedFields subclass; + +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithTransientFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithTransientFields.java new file mode 100644 index 0000000000..5e781a6287 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MyClassWithTransientFields.java @@ -0,0 +1,15 @@ +package org.baeldung.gson.serializationwithexclusions; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MyClassWithTransientFields { + + private long id; + private String name; + private transient String other; + private MySubClassWithTransientFields subclass; + +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClass.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClass.java new file mode 100644 index 0000000000..5adac0697e --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClass.java @@ -0,0 +1,12 @@ +package org.baeldung.gson.serializationwithexclusions; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MySubClass { + private long id; + private String description; + private String otherVerboseInfo; +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithAnnotatedFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithAnnotatedFields.java new file mode 100644 index 0000000000..a0f7b5d277 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithAnnotatedFields.java @@ -0,0 +1,15 @@ +package org.baeldung.gson.serializationwithexclusions; + +import com.google.gson.annotations.Expose; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MySubClassWithAnnotatedFields { + + @Expose private long id; + @Expose private String description; + private String otherVerboseInfo; +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithCustomAnnotatedFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithCustomAnnotatedFields.java new file mode 100644 index 0000000000..f6aa4651b3 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithCustomAnnotatedFields.java @@ -0,0 +1,14 @@ +package org.baeldung.gson.serializationwithexclusions; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MySubClassWithCustomAnnotatedFields { + + private long id; + private String description; + @Exclude + private String otherVerboseInfo; +} diff --git a/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithTransientFields.java b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithTransientFields.java new file mode 100644 index 0000000000..d4e31b0bc8 --- /dev/null +++ b/gson/src/main/java/org/baeldung/gson/serializationwithexclusions/MySubClassWithTransientFields.java @@ -0,0 +1,13 @@ +package org.baeldung.gson.serializationwithexclusions; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class MySubClassWithTransientFields { + + private long id; + private String description; + private transient String otherVerboseInfo; +} diff --git a/gson/src/test/java/org/baeldung/gson/serializationwithexclusions/SerializationWithExclusionsUnitTest.java b/gson/src/test/java/org/baeldung/gson/serializationwithexclusions/SerializationWithExclusionsUnitTest.java new file mode 100644 index 0000000000..632d06946b --- /dev/null +++ b/gson/src/test/java/org/baeldung/gson/serializationwithexclusions/SerializationWithExclusionsUnitTest.java @@ -0,0 +1,104 @@ +package org.baeldung.gson.serializationwithexclusions; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +import com.google.gson.ExclusionStrategy; +import com.google.gson.FieldAttributes; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +class SerializationWithExclusionsUnitTest { + + final String expectedResult = "{\"id\":1,\"name\":\"foo\",\"subclass\":{\"id\":42,\"description\":\"the answer\"}}"; + + @Test + public void givenClassWithTransientFields_whenSerializing_thenCorrectWithoutTransientFields() { + MyClassWithTransientFields source = new MyClassWithTransientFields(1L, "foo", "bar", new MySubClassWithTransientFields(42L, "the answer", "Verbose field which we don't want to be serialized")); + String jsonString = new Gson().toJson(source); + assertEquals(expectedResult, jsonString); + } + + @Test + public void givenClassAnnotated_whenSerializing_thenCorrectWithoutNotAnnotatedFields() { + MyClassWithAnnotatedFields source = new MyClassWithAnnotatedFields(1L, "foo", "bar", new MySubClassWithAnnotatedFields(42L, "the answer", "Verbose field which we don't want to be serialized")); + Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation() + .create(); + String jsonString = gson.toJson(source); + + assertEquals(expectedResult, jsonString); + } + + @Test + public void givenExclusionStrategyByClassesAndFields_whenSerializing_thenFollowStrategy() { + MyClass source = new MyClass(1L, "foo", "bar", new MySubClass(42L, "the answer", "Verbose field which we don't want to be serialized")); + ExclusionStrategy strategy = new ExclusionStrategy() { + @Override + public boolean shouldSkipField(FieldAttributes field) { + if (field.getDeclaringClass() == MyClass.class && field.getName() + .equals("other")) + return true; + if (field.getDeclaringClass() == MySubClass.class && field.getName() + .equals("otherVerboseInfo")) + return true; + return false; + } + + @Override + public boolean shouldSkipClass(Class clazz) { + return false; + } + }; + + Gson gson = new GsonBuilder().addSerializationExclusionStrategy(strategy) + .create(); + String jsonString = gson.toJson(source); + + assertEquals(expectedResult, jsonString); + } + + @Test + public void givenExclusionStrategyByStartsWith_whenSerializing_thenFollowStrategy() { + MyClass source = new MyClass(1L, "foo", "bar", new MySubClass(42L, "the answer", "Verbose field which we don't want to be serialized")); + ExclusionStrategy strategy = new ExclusionStrategy() { + @Override + public boolean shouldSkipClass(Class clazz) { + return false; + } + + @Override + public boolean shouldSkipField(FieldAttributes field) { + return field.getName().startsWith("other"); + } + }; + Gson gson = new GsonBuilder().setExclusionStrategies(strategy) + .create(); + String jsonString = gson.toJson(source); + + assertEquals(expectedResult, jsonString); + } + + @Test + public void givenExclusionStrategyByCustomAnnotation_whenSerializing_thenFollowStrategy() { + MyClassWithCustomAnnotatedFields source = new MyClassWithCustomAnnotatedFields(1L, "foo", "bar", new MySubClassWithCustomAnnotatedFields(42L, "the answer", "Verbose field which we don't want to be serialized")); + ExclusionStrategy strategy = new ExclusionStrategy() { + @Override + public boolean shouldSkipClass(Class clazz) { + return false; + } + + @Override + public boolean shouldSkipField(FieldAttributes field) { + return field.getAnnotation(Exclude.class) != null; + } + + }; + + Gson gson = new GsonBuilder().setExclusionStrategies(strategy) + .create(); + String jsonString = gson.toJson(source); + assertEquals(expectedResult, jsonString); + } + +} \ No newline at end of file diff --git a/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java b/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java similarity index 97% rename from guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java rename to guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java index db82ea6da8..bd3a73c60f 100644 --- a/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java +++ b/guava-modules/guava-18/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java @@ -11,7 +11,7 @@ import java.util.concurrent.ConcurrentHashMap; import static org.hamcrest.CoreMatchers.equalTo; -public class GuavaMiscUtilsTest { +public class GuavaMiscUtilsUnitTest { @Test public void whenHashingData_shouldReturnCorrectHashCode() throws Exception { int receivedData = 123; diff --git a/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java b/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java similarity index 98% rename from guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java rename to guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java index c7b8441b78..6f2d85bb04 100644 --- a/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java +++ b/guava-modules/guava-19/src/test/java/com/baeldung/guava/GuavaMiscUtilsUnitTest.java @@ -12,7 +12,7 @@ import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInA import static org.hamcrest.core.AnyOf.anyOf; import static org.junit.Assert.*; -public class GuavaMiscUtilsTest { +public class GuavaMiscUtilsUnitTest { @Test public void whenGettingLazyStackTrace_ListShouldBeReturned() throws Exception { diff --git a/guava-modules/guava-21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java b/guava-modules/guava-21/src/test/java/com/baeldung/guava/zip/ZipCollectionUnitTest.java similarity index 98% rename from guava-modules/guava-21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java rename to guava-modules/guava-21/src/test/java/com/baeldung/guava/zip/ZipCollectionUnitTest.java index 866e09c6a0..e3d31d9404 100644 --- a/guava-modules/guava-21/src/test/java/com.baeldung.guava.zip/ZipCollectionTest.java +++ b/guava-modules/guava-21/src/test/java/com/baeldung/guava/zip/ZipCollectionUnitTest.java @@ -13,7 +13,7 @@ import java.util.stream.IntStream; import static org.junit.Assert.assertEquals; -public class ZipCollectionTest { +public class ZipCollectionUnitTest { private List names; private List ages; diff --git a/guava/src/test/java/org/baeldung/guava/BloomFilterTest.java b/guava/src/test/java/org/baeldung/guava/BloomFilterUnitTest.java similarity index 97% rename from guava/src/test/java/org/baeldung/guava/BloomFilterTest.java rename to guava/src/test/java/org/baeldung/guava/BloomFilterUnitTest.java index d7c25b7c8d..ff3031a0cb 100644 --- a/guava/src/test/java/org/baeldung/guava/BloomFilterTest.java +++ b/guava/src/test/java/org/baeldung/guava/BloomFilterUnitTest.java @@ -9,7 +9,7 @@ import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; -public class BloomFilterTest { +public class BloomFilterUnitTest { @Test public void givenBloomFilter_whenAddNStringsToIt_thenShouldNotReturnAnyFalsePositive() { diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamTest.java b/guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamUnitTest.java similarity index 94% rename from guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamTest.java rename to guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamUnitTest.java index 5e96f3597c..7293b1631e 100644 --- a/guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamTest.java +++ b/guava/src/test/java/org/baeldung/guava/GuavaCountingOutputStreamUnitTest.java @@ -7,7 +7,7 @@ import org.junit.Test; import com.google.common.io.CountingOutputStream; -public class GuavaCountingOutputStreamTest { +public class GuavaCountingOutputStreamUnitTest { public static final int MAX = 5; @Test(expected = RuntimeException.class) diff --git a/guava/src/test/java/org/baeldung/hamcrest/HamcrestCommonCoreMatchersTest.java b/guava/src/test/java/org/baeldung/hamcrest/HamcrestCommonCoreMatchersTest.java deleted file mode 100644 index 2c85067c9b..0000000000 --- a/guava/src/test/java/org/baeldung/hamcrest/HamcrestCommonCoreMatchersTest.java +++ /dev/null @@ -1,206 +0,0 @@ -package org.baeldung.hamcrest; - -import org.assertj.core.util.Lists; -import org.junit.Test; - -import java.util.List; - -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.StringEndsWith.endsWith; -import static org.hamcrest.core.StringStartsWith.startsWith; - -public class HamcrestCommonCoreMatchersTest { - - @Test - public void givenTestInput_WhenUsingIsForMatch() { - - // GIVEN - String testString = "hamcrest core"; - - // ASSERT - assertThat(testString, is("hamcrest core")); - assertThat(testString, is(equalTo("hamcrest core"))); - } - - @Test - public void givenTestInput_WhenUsingInstanceOfForClassTypeCheck(){ - - assertThat("hamcrest", is(instanceOf(String.class))); - } - - @Test - public void givenTestInput_WhenUsingIsA_ThenAssertType(){ - - assertThat("hamcrest core", isA(String.class)); - } - - @Test - public void givenTestInput_WhenUsingEqualToMatcherForEquality(){ - - // GIVEN - String actualString = "Hamcrest Core"; - List actualList = Lists.newArrayList("hamcrest", "core"); - - // ASSERT - assertThat(actualString, is(equalTo("Hamcrest Core"))); - assertThat(actualList, is(equalTo(Lists.newArrayList("hamcrest", "core")))); - } - - @Test - public void givenTestInput_WhenUsingNotForMatch(){ - - // GIVEN - String testString = "hamcrest"; - - // ASSERT - assertThat(testString, not("hamcrest core")); - assertThat(testString, is(not(equalTo("hamcrest core")))); - assertThat(testString, is(not(instanceOf(Integer.class)))); - } - - @Test - public void givenTestInput_WhenUsingNullValueForNullCheck(){ - - // GIVEN - Integer nullObject = null; - - // ASSERT - assertThat(nullObject, is(nullValue())); - assertThat(nullObject, is(nullValue(Integer.class))); - } - - @Test - public void givenTestInput_WhenUsingNotNullValueForNotNullCheck(){ - - // GIVEN - Integer testNumber = 123; - - // ASSERT - assertThat(testNumber, is(notNullValue())); - assertThat(testNumber, is(notNullValue(Integer.class))); - } - - @Test - public void givenString_WhenStartsWith_ThenCorrect(){ - - // GIVEN - String testString = "hamcrest core"; - - // ASSERT - assertThat(testString, startsWith("hamcrest")); - } - - @Test - public void givenString_WhenEndsWith_ThenCorrect(){ - - // GIVEN - String testString = "hamcrest core"; - - // ASSERT - assertThat(testString, endsWith("core")); - } - - @Test - public void givenString_WhenContainsString_ThenCorrect(){ - - // GIVEN - String testString = "hamcrest core"; - - // ASSERT - assertThat(testString, containsString("co")); - } - - @Test - public void givenTestInput_WhenUsingHasItemInCollection(){ - - // GIVEN - List list = Lists.newArrayList("java", "spring", "baeldung"); - - // ASSERT - assertThat(list, hasItem("java")); - assertThat(list, hasItem(isA(String.class))); - } - - - @Test - public void givenTestInput_WhenUsingHasItemsInCollection(){ - - // GIVEN - List list = Lists.newArrayList("java", "spring", "baeldung"); - - // ASSERT - assertThat(list, hasItems("java", "baeldung")); - assertThat(list, hasItems(isA(String.class), endsWith("ing"))); - } - - @Test - public void givenTestInput_WhenUsingAnyForClassType(){ - - assertThat("hamcrest", is(any(String.class))); - assertThat("hamcrest", is(any(Object.class))); - } - - @Test - public void givenTestInput_WhenUsingAllOfForAllMatchers(){ - - // GIVEN - String testString = "Hamcrest Core"; - - // ASSERT - assertThat(testString, allOf(startsWith("Ham"), endsWith("ore"), containsString("Core"))); - } - - @Test - public void givenTestInput_WhenUsingAnyOfForAnyMatcher(){ - - // GIVEN - String testString = "Hamcrest Core"; - - // ASSERT - assertThat(testString, anyOf(startsWith("Ham"), containsString("baeldung"))); - } - - @Test - public void givenTestInput_WhenUsingBothForMatcher(){ - - // GIVEN - String testString = "Hamcrest Core Matchers"; - - // ASSERT - assertThat(testString, both(startsWith("Ham")).and(containsString("Core"))); - } - - @Test - public void givenTestInput_WhenUsingEitherForMatcher(){ - - // GIVEN - String testString = "Hamcrest Core Matchers"; - - // ASSERT - assertThat(testString, either(startsWith("Bael")).or(containsString("Core"))); - } - - - @Test - public void givenTestInput_WhenUsingEveryItemForMatchInCollection(){ - - // GIVEN - List testItems = Lists.newArrayList("Common", "Core", "Combinable"); - - // ASSERT - assertThat(testItems, everyItem(startsWith("Co"))); - } - - @Test - public void givenTwoTestInputs_WhenUsingSameInstanceForMatch(){ - - // GIVEN - String string1 = "hamcrest"; - String string2 = string1; - - // ASSERT - assertThat(string1, is(sameInstance(string2))); - } - -} \ No newline at end of file diff --git a/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF b/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF index 254272e1c0..e3c07ab38a 100644 --- a/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF +++ b/guest/spring-boot-app/WebContent/META-INF/MANIFEST.MF @@ -1,3 +1,2 @@ Manifest-Version: 1.0 Class-Path: - diff --git a/guest/spring-boot-app/docker/Dockerfile b/guest/spring-boot-app/docker/Dockerfile new file mode 100644 index 0000000000..211e8927a3 --- /dev/null +++ b/guest/spring-boot-app/docker/Dockerfile @@ -0,0 +1,16 @@ +# Alpine Linux with OpenJDK JRE +FROM openjdk:8-jre-alpine +RUN apk add --no-cache bash + +# copy fat WAR +COPY spring-boot-app-0.0.1-SNAPSHOT.war /app.war + +# copy fat WAR +COPY logback.xml /logback.xml + +COPY run.sh /run.sh + +# runs application +#CMD ["/usr/bin/java", "-jar", "-Dspring.profiles.active=default", "-Dlogging.config=/logback.xml", "/app.war"] + +ENTRYPOINT ["/run.sh"] diff --git a/guest/spring-boot-app/docker/logback.xml b/guest/spring-boot-app/docker/logback.xml new file mode 100644 index 0000000000..7e03ddc827 --- /dev/null +++ b/guest/spring-boot-app/docker/logback.xml @@ -0,0 +1,15 @@ + + + + + /var/log/Application/application.log + true + + %-7d{yyyy-MM-dd HH:mm:ss:SSS} %m%n + + + + + + + diff --git a/guest/spring-boot-app/docker/run.sh b/guest/spring-boot-app/docker/run.sh new file mode 100755 index 0000000000..aeecc29371 --- /dev/null +++ b/guest/spring-boot-app/docker/run.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +java -Dspring.profiles.active=$1 -Dlogging.config=/logback.xml -jar /app.war + diff --git a/guest/spring-boot-app/pom.xml b/guest/spring-boot-app/pom.xml index ba57bbd5c5..c02eef7ef3 100644 --- a/guest/spring-boot-app/pom.xml +++ b/guest/spring-boot-app/pom.xml @@ -51,6 +51,22 @@ WebContent + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + com.stackify.Application + ${project.basedir}/docker + + + + + @@ -58,4 +74,4 @@ 8.0.43 - \ No newline at end of file + diff --git a/guest/spring-mvc/pom.xml b/guest/spring-mvc/pom.xml index 169b216ff9..da4d27b14d 100644 --- a/guest/spring-mvc/pom.xml +++ b/guest/spring-mvc/pom.xml @@ -27,28 +27,6 @@ - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - UTF-8 UTF-8 diff --git a/guest/spring-security/pom.xml b/guest/spring-security/pom.xml index 16e946d108..793df750de 100644 --- a/guest/spring-security/pom.xml +++ b/guest/spring-security/pom.xml @@ -45,28 +45,6 @@ - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - UTF-8 UTF-8 diff --git a/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml b/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml deleted file mode 100644 index cf944804db..0000000000 --- a/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml b/handling-spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml deleted file mode 100644 index 94bd63e068..0000000000 --- a/handling-spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - \ No newline at end of file diff --git a/hibernate5/README.md b/hibernate5/README.md index fb1319ed57..afba239919 100644 --- a/hibernate5/README.md +++ b/hibernate5/README.md @@ -10,3 +10,6 @@ - [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) +- [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa) + diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index 130edec8cc..23d7d2e201 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -1,30 +1,14 @@ package com.baeldung.hibernate; -import com.baeldung.hibernate.pojo.Employee; -import com.baeldung.hibernate.pojo.EntityDescription; -import com.baeldung.hibernate.pojo.OrderEntry; -import com.baeldung.hibernate.pojo.OrderEntryIdClass; -import com.baeldung.hibernate.pojo.OrderEntryPK; -import com.baeldung.hibernate.pojo.PointEntity; -import com.baeldung.hibernate.pojo.PolygonEntity; -import com.baeldung.hibernate.pojo.Product; -import com.baeldung.hibernate.pojo.Phone; -import com.baeldung.hibernate.pojo.TemporalValues; -import com.baeldung.hibernate.pojo.Course; -import com.baeldung.hibernate.pojo.Student; -import com.baeldung.hibernate.pojo.User; -import com.baeldung.hibernate.pojo.UserProfile; -import com.baeldung.hibernate.pojo.inheritance.Animal; -import com.baeldung.hibernate.pojo.inheritance.Bag; -import com.baeldung.hibernate.pojo.inheritance.Book; -import com.baeldung.hibernate.pojo.inheritance.Car; -import com.baeldung.hibernate.pojo.inheritance.MyEmployee; -import com.baeldung.hibernate.pojo.inheritance.MyProduct; -import com.baeldung.hibernate.pojo.inheritance.Pen; -import com.baeldung.hibernate.pojo.inheritance.Person; -import com.baeldung.hibernate.pojo.inheritance.Pet; -import com.baeldung.hibernate.pojo.inheritance.Vehicle; - +import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse; +import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent; +import com.baeldung.hibernate.pessimisticlocking.Individual; +import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse; +import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee; +import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent; +import com.baeldung.hibernate.pojo.*; +import com.baeldung.hibernate.pojo.Person; +import com.baeldung.hibernate.pojo.inheritance.*; import org.apache.commons.lang3.StringUtils; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; @@ -82,6 +66,14 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(PointEntity.class); metadataSources.addAnnotatedClass(PolygonEntity.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.pojo.Person.class); + metadataSources.addAnnotatedClass(Individual.class); + metadataSources.addAnnotatedClass(PessimisticLockingEmployee.class); + metadataSources.addAnnotatedClass(PessimisticLockingStudent.class); + metadataSources.addAnnotatedClass(PessimisticLockingCourse.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class); + metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class); + metadataSources.addAnnotatedClass(OptimisticLockingCourse.class); + metadataSources.addAnnotatedClass(OptimisticLockingStudent.class); Metadata metadata = metadataSources.buildMetadata(); return metadata.getSessionFactoryBuilder() diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java new file mode 100644 index 0000000000..f7b8e6bf6d --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.jpabootstrap.application; + +import com.baeldung.hibernate.jpabootstrap.config.JpaEntityManagerFactory; +import com.baeldung.hibernate.jpabootstrap.entities.User; +import javax.persistence.EntityManager; + +public class Application { + + public static void main(String[] args) { + EntityManager entityManager = getJpaEntityManager(); + User user = entityManager.find(User.class, 1); + System.out.println(user); + entityManager.getTransaction().begin(); + user.setName("John"); + user.setEmail("john@domain.com"); + entityManager.merge(user); + entityManager.getTransaction().commit(); + entityManager.getTransaction().begin(); + entityManager.persist(new User("Monica", "monica@domain.com")); + entityManager.getTransaction().commit(); + + // additional CRUD operations + + } + + private static class EntityManagerHolder { + private static final EntityManager ENTITY_MANAGER = new JpaEntityManagerFactory( + new Class[]{User.class}).getEntityManager(); + } + + public static EntityManager getJpaEntityManager() { + return EntityManagerHolder.ENTITY_MANAGER; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java new file mode 100644 index 0000000000..3852b44b64 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java @@ -0,0 +1,131 @@ +package com.baeldung.hibernate.jpabootstrap.config; + +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import javax.sql.DataSource; +import javax.persistence.SharedCacheMode; +import javax.persistence.ValidationMode; +import javax.persistence.spi.ClassTransformer; +import javax.persistence.spi.PersistenceUnitInfo; +import javax.persistence.spi.PersistenceUnitTransactionType; +import org.hibernate.jpa.HibernatePersistenceProvider; + +public class HibernatePersistenceUnitInfo implements PersistenceUnitInfo { + + public static final String JPA_VERSION = "2.1"; + private final String persistenceUnitName; + private PersistenceUnitTransactionType transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; + private final List managedClassNames; + private final List mappingFileNames = new ArrayList<>(); + private final Properties properties; + private DataSource jtaDataSource; + private DataSource nonjtaDataSource; + private final List transformers = new ArrayList<>(); + + public HibernatePersistenceUnitInfo(String persistenceUnitName, List managedClassNames, Properties properties) { + this.persistenceUnitName = persistenceUnitName; + this.managedClassNames = managedClassNames; + this.properties = properties; + } + + @Override + public String getPersistenceUnitName() { + return persistenceUnitName; + } + + @Override + public String getPersistenceProviderClassName() { + return HibernatePersistenceProvider.class.getName(); + } + + @Override + public PersistenceUnitTransactionType getTransactionType() { + return transactionType; + } + + public HibernatePersistenceUnitInfo setJtaDataSource(DataSource jtaDataSource) { + this.jtaDataSource = jtaDataSource; + this.nonjtaDataSource = null; + transactionType = PersistenceUnitTransactionType.JTA; + return this; + } + + @Override + public DataSource getJtaDataSource() { + return jtaDataSource; + } + + public HibernatePersistenceUnitInfo setNonJtaDataSource(DataSource nonJtaDataSource) { + this.nonjtaDataSource = nonJtaDataSource; + this.jtaDataSource = null; + transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL; + return this; + } + + @Override + public DataSource getNonJtaDataSource() { + return nonjtaDataSource; + } + + @Override + public List getMappingFileNames() { + return mappingFileNames; + } + + @Override + public List getJarFileUrls() { + return Collections.emptyList(); + } + + @Override + public URL getPersistenceUnitRootUrl() { + return null; + } + + @Override + public List getManagedClassNames() { + return managedClassNames; + } + + @Override + public boolean excludeUnlistedClasses() { + return false; + } + + @Override + public SharedCacheMode getSharedCacheMode() { + return SharedCacheMode.UNSPECIFIED; + } + + @Override + public ValidationMode getValidationMode() { + return ValidationMode.AUTO; + } + + public Properties getProperties() { + return properties; + } + + @Override + public String getPersistenceXMLSchemaVersion() { + return JPA_VERSION; + } + + @Override + public ClassLoader getClassLoader() { + return Thread.currentThread().getContextClassLoader(); + } + + @Override + public void addTransformer(ClassTransformer transformer) { + transformers.add(transformer); + } + + @Override + public ClassLoader getNewTempClassLoader() { + return null; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java new file mode 100644 index 0000000000..bc1932af6f --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java @@ -0,0 +1,69 @@ +package com.baeldung.hibernate.jpabootstrap.config; + +import com.mysql.cj.jdbc.MysqlDataSource; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; +import javax.persistence.EntityManager; +import javax.sql.DataSource; +import javax.persistence.EntityManagerFactory; +import javax.persistence.spi.PersistenceUnitInfo; +import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; +import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor; + +public class JpaEntityManagerFactory { + + private final String DB_URL = "jdbc:mysql://databaseurl"; + private final String DB_USER_NAME = "username"; + private final String DB_PASSWORD = "password"; + private final Class[] entityClasses; + + public JpaEntityManagerFactory(Class[] entityClasses) { + this.entityClasses = entityClasses; + } + + public EntityManager getEntityManager() { + return getEntityManagerFactory().createEntityManager(); + } + + protected EntityManagerFactory getEntityManagerFactory() { + PersistenceUnitInfo persistenceUnitInfo = getPersistenceUnitInfo(getClass().getSimpleName()); + Map configuration = new HashMap<>(); + return new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration) + .build(); + } + + protected HibernatePersistenceUnitInfo getPersistenceUnitInfo(String name) { + return new HibernatePersistenceUnitInfo(name, getEntityClassNames(), getProperties()); + } + + protected List getEntityClassNames() { + return Arrays.asList(getEntities()) + .stream() + .map(Class::getName) + .collect(Collectors.toList()); + } + + protected Properties getProperties() { + Properties properties = new Properties(); + properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); + properties.put("hibernate.id.new_generator_mappings", false); + properties.put("hibernate.connection.datasource", getMysqlDataSource()); + return properties; + } + + protected Class[] getEntities() { + return entityClasses; + } + + protected DataSource getMysqlDataSource() { + MysqlDataSource mysqlDataSource = new MysqlDataSource(); + mysqlDataSource.setURL(DB_URL); + mysqlDataSource.setUser(DB_USER_NAME); + mysqlDataSource.setPassword(DB_PASSWORD); + return mysqlDataSource; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java new file mode 100644 index 0000000000..86ca1dfa19 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.jpabootstrap.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + private String name; + private String email; + + public User(){} + + public User(String name, String email) { + this.name = name; + this.email = email; + } + + public void setName(String name) { + this.name = name; + } + + public void setEmail(String email) { + this.email = email; + } + + public long getId() { + return id; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } +} \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java new file mode 100644 index 0000000000..1af3e3e21b --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java @@ -0,0 +1,48 @@ +package com.baeldung.hibernate.optimisticlocking; + +import javax.persistence.*; + +@Entity +public class OptimisticLockingCourse { + + @Id + private Long id; + + private String name; + + @ManyToOne + @JoinTable(name = "optimistic_student_course") + private OptimisticLockingStudent student; + + public OptimisticLockingCourse(Long id, String name) { + this.id = id; + this.name = name; + } + + public OptimisticLockingCourse() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public OptimisticLockingStudent getStudent() { + return student; + } + + public void setStudent(OptimisticLockingStudent student) { + this.student = student; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java new file mode 100644 index 0000000000..b79212ae8d --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java @@ -0,0 +1,70 @@ +package com.baeldung.hibernate.optimisticlocking; + +import javax.persistence.*; +import java.util.List; + +@Entity +public class OptimisticLockingStudent { + + @Id + private Long id; + + private String name; + + private String lastName; + @Version + private Integer version; + + @OneToMany(mappedBy = "student") + private List courses; + + public OptimisticLockingStudent(Long id, String name, String lastName, List courses) { + this.id = id; + this.name = name; + this.lastName = lastName; + this.courses = courses; + } + + public OptimisticLockingStudent() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Integer getVersion() { + return version; + } + + public void setVersion(Integer version) { + this.version = version; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public List getCourses() { + return courses; + } + + public void setCourses(List courses) { + this.courses = courses; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java new file mode 100644 index 0000000000..c889cb6127 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.pessimisticlocking; + +import javax.persistence.Embeddable; + +@Embeddable +public class Address { + + private String country; + private String city; + + public Address(String country, String city) { + this.country = country; + this.city = city; + } + + public Address() { + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java new file mode 100644 index 0000000000..cb73cbc958 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java @@ -0,0 +1,58 @@ +package com.baeldung.hibernate.pessimisticlocking; + +import javax.persistence.*; +import java.util.List; + +@Entity +public class Customer { + + @Id + private Long customerId; + private String name; + private String lastName; + @ElementCollection + @CollectionTable(name = "customer_address") + private List
addressList; + + public Customer() { + } + + public Customer(Long customerId, String name, String lastName, List
addressList) { + this.customerId = customerId; + this.name = name; + this.lastName = lastName; + this.addressList = addressList; + } + + public Long getCustomerId() { + return customerId; + } + + public void setCustomerId(Long customerId) { + this.customerId = customerId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public List
getAddressList() { + return addressList; + } + + public void setAddressList(List
addressList) { + this.addressList = addressList; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java new file mode 100644 index 0000000000..e491c09eb5 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java @@ -0,0 +1,49 @@ +package com.baeldung.hibernate.pessimisticlocking; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +@Entity +@Inheritance(strategy = InheritanceType.JOINED) +public class Individual { + + @Id + private Long id; + private String name; + private String lastName; + + public Individual(Long id, String name, String lastName) { + this.id = id; + this.name = name; + this.lastName = lastName; + } + + public Individual() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java new file mode 100644 index 0000000000..aea7d5fc87 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.pessimisticlocking; + +import javax.persistence.*; + +@Entity +public class PessimisticLockingCourse { + + @Id + private Long courseId; + private String name; + @ManyToOne + @JoinTable(name = "student_course") + private PessimisticLockingStudent student; + + public PessimisticLockingCourse(Long courseId, String name, PessimisticLockingStudent student) { + this.courseId = courseId; + this.name = name; + this.student = student; + } + + public PessimisticLockingCourse() { + } + + public Long getCourseId() { + return courseId; + } + + public void setCourseId(Long courseId) { + this.courseId = courseId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public PessimisticLockingStudent getStudent() { + return student; + } + + public void setStudent(PessimisticLockingStudent students) { + this.student = students; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java new file mode 100644 index 0000000000..a1328cbdad --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java @@ -0,0 +1,27 @@ +package com.baeldung.hibernate.pessimisticlocking; + +import javax.persistence.Entity; +import java.math.BigDecimal; + +@Entity +public class PessimisticLockingEmployee extends Individual { + + private BigDecimal salary; + + public PessimisticLockingEmployee(Long id, String name, String lastName, BigDecimal salary) { + super(id, name, lastName); + this.salary = salary; + } + + public PessimisticLockingEmployee() { + super(); + } + + public BigDecimal getSalary() { + return salary; + } + + public void setSalary(BigDecimal average) { + this.salary = average; + } +} diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java new file mode 100644 index 0000000000..e6c5f476b4 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java @@ -0,0 +1,46 @@ +package com.baeldung.hibernate.pessimisticlocking; + +import javax.persistence.*; +import java.util.List; + +@Entity +public class PessimisticLockingStudent { + + @Id + private Long id; + private String name; + @OneToMany(mappedBy = "student") + private List courses; + + public PessimisticLockingStudent(Long id, String name) { + this.id = id; + this.name = name; + } + + public PessimisticLockingStudent() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getCourses() { + return courses; + } + + public void setCourses(List courses) { + this.courses = courses; + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java new file mode 100644 index 0000000000..68b51764e4 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java @@ -0,0 +1,134 @@ +package com.baeldung.hibernate.optimisticlocking; + +import com.baeldung.hibernate.HibernateUtil; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import javax.persistence.EntityManager; +import javax.persistence.LockModeType; +import javax.persistence.OptimisticLockException; +import java.io.IOException; +import java.util.Arrays; + +public class OptimisticLockingIntegrationTest { + + @Before + public void setUp() throws IOException { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + OptimisticLockingCourse course = new OptimisticLockingCourse(1L, "MATH"); + OptimisticLockingStudent student = new OptimisticLockingStudent(1L, "John", "Doe", Arrays.asList(course)); + course.setStudent(student); + entityManager.persist(course); + entityManager.persist(student); + entityManager.getTransaction() + .commit(); + entityManager.close(); + } + + @After + public void clean() throws IOException { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + OptimisticLockingCourse course = entityManager.find(OptimisticLockingCourse.class, 1L); + OptimisticLockingStudent student = entityManager.find(OptimisticLockingStudent.class, 1L); + entityManager.remove(course); + entityManager.remove(student); + entityManager.getTransaction() + .commit(); + entityManager.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntities_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntitiesWithLockByFindMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntitiesWithLockByRefreshMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); + em.refresh(student, LockModeType.OPTIMISTIC); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); + em.refresh(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + @Test(expected = OptimisticLockException.class) + public void givenVersionedEntitiesWithLockByLockMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L); + em.lock(student, LockModeType.OPTIMISTIC); + + EntityManager em2 = getEntityManagerWithOpenTransaction(); + OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L); + em.lock(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT); + student2.setName("RICHARD"); + em2.persist(student2); + em2.getTransaction() + .commit(); + em2.close(); + + student.setName("JOHN"); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + } + + protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException { + String propertyFileName = "hibernate-pessimistic-locking.properties"; + EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName) + .openSession(); + entityManager.getTransaction() + .begin(); + + return entityManager; + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java new file mode 100644 index 0000000000..f416c11d1f --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java @@ -0,0 +1,151 @@ +package com.baeldung.hibernate.pessimisticlocking; + +import com.baeldung.hibernate.HibernateUtil; +import com.vividsolutions.jts.util.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import javax.persistence.*; +import java.io.IOException; +import java.util.Arrays; + +public class BasicPessimisticLockingIntegrationTest { + + @BeforeClass + public static void setUp() throws IOException { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + PessimisticLockingStudent student = new PessimisticLockingStudent(1L, "JOHN"); + PessimisticLockingCourse course = new PessimisticLockingCourse(1L, "MATH", student); + student.setCourses(Arrays.asList(course)); + entityManager.persist(course); + entityManager.persist(student); + entityManager.getTransaction() + .commit(); + entityManager.close(); + } + + @Test + public void givenFoundRecordWithPessimisticRead_whenFindingNewOne_PessimisticLockExceptionThrown() { + try { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + entityManager.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_READ); + + EntityManager entityManager2 = getEntityManagerWithOpenTransaction(); + entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_READ); + + entityManager.close(); + entityManager2.close(); + } catch (Exception e) { + Assert.isTrue(e instanceof PessimisticLockException); + } + } + + @Test + public void givenRecordWithPessimisticReadQuery_whenQueryingNewOne_PessimisticLockExceptionThrown() throws IOException { + try { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + Query query = entityManager.createQuery("from Student where studentId = :studentId"); + query.setParameter("studentId", 1L); + query.setLockMode(LockModeType.PESSIMISTIC_WRITE); + query.getResultList(); + + EntityManager entityManager2 = getEntityManagerWithOpenTransaction(); + Query query2 = entityManager2.createQuery("from Student where studentId = :studentId"); + query2.setParameter("studentId", 1L); + query2.setLockMode(LockModeType.PESSIMISTIC_READ); + query2.getResultList(); + + entityManager.close(); + entityManager2.close(); + } catch (Exception e) { + Assert.isTrue(e instanceof PessimisticLockException); + } + } + + @Test + public void givenRecordWithPessimisticReadLock_whenFindingNewOne_PessimisticLockExceptionThrown() { + try { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L); + entityManager.lock(resultStudent, LockModeType.PESSIMISTIC_READ); + + EntityManager entityManager2 = getEntityManagerWithOpenTransaction(); + entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_FORCE_INCREMENT); + + entityManager.close(); + entityManager2.close(); + } catch (Exception e) { + Assert.isTrue(e instanceof PessimisticLockException); + } + } + + @Test + public void givenRecordAndRefreshWithPessimisticRead_whenFindingWithPessimisticWrite_PessimisticLockExceptionThrown() { + try { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L); + entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_FORCE_INCREMENT); + + EntityManager entityManager2 = getEntityManagerWithOpenTransaction(); + entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_WRITE); + + entityManager.close(); + entityManager2.close(); + } catch (Exception e) { + Assert.isTrue(e instanceof PessimisticLockException); + } + } + + @Test + public void givenRecordWithPessimisticRead_whenUpdatingRecord_PessimisticLockExceptionThrown() { + try { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L); + entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_READ); + + EntityManager entityManager2 = getEntityManagerWithOpenTransaction(); + PessimisticLockingStudent resultStudent2 = entityManager2.find(PessimisticLockingStudent.class, 1L); + resultStudent2.setName("Change"); + entityManager2.persist(resultStudent2); + entityManager2.getTransaction() + .commit(); + + entityManager.close(); + entityManager2.close(); + } catch (Exception e) { + Assert.isTrue(e instanceof PessimisticLockException); + } + } + + @Test + public void givenRecordWithPessimisticWrite_whenUpdatingRecord_PessimisticLockExceptionThrown() { + try { + EntityManager entityManager = getEntityManagerWithOpenTransaction(); + PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L); + entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_WRITE); + + EntityManager entityManager2 = getEntityManagerWithOpenTransaction(); + PessimisticLockingStudent resultStudent2 = entityManager2.find(PessimisticLockingStudent.class, 1L); + resultStudent2.setName("Change"); + entityManager2.persist(resultStudent2); + entityManager2.getTransaction() + .commit(); + + entityManager.close(); + entityManager2.close(); + } catch (Exception e) { + Assert.isTrue(e instanceof PessimisticLockException); + } + } + + protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException { + String propertyFileName = "hibernate-pessimistic-locking.properties"; + EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName) + .openSession(); + entityManager.getTransaction() + .begin(); + + return entityManager; + } + +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java new file mode 100644 index 0000000000..ac56ab7133 --- /dev/null +++ b/hibernate5/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java @@ -0,0 +1,115 @@ +package com.baeldung.hibernate.pessimisticlocking; + +import com.baeldung.hibernate.HibernateUtil; +import org.junit.Test; + +import javax.persistence.EntityManager; +import javax.persistence.LockModeType; +import javax.persistence.PessimisticLockScope; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +public class PessimisticLockScopesIntegrationTest { + + @Test + public void givenEclipseEntityWithJoinInheritance_whenNormalLock_thenShouldChildAndParentEntity() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + PessimisticLockingEmployee employee = new PessimisticLockingEmployee(1L, "JOHN", "SMITH", new BigDecimal(4.5)); + em.persist(employee); + em.getTransaction() + .commit(); + em.close(); + + // NORMAL SCOPE + EntityManager em2 = getEntityManagerWithOpenTransaction(); + PessimisticLockingEmployee foundEmployee = em2.find(PessimisticLockingEmployee.class, 1L, LockModeType.PESSIMISTIC_WRITE); + em2.getTransaction() + .rollback(); + + // EXTENDED SCOPE + Map map = new HashMap<>(); + map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED); + + EntityManager em3 = getEntityManagerWithOpenTransaction(); + foundEmployee = em3.find(PessimisticLockingEmployee.class, 1L, LockModeType.PESSIMISTIC_WRITE, map); + em3.getTransaction() + .rollback(); + + em2.close(); + em3.close(); + } + + @Test + public void givenEntityWithElementCollection_whenLock_thenHibernateExtendedScopeLockOnlyOwningEntity() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + Address address = new Address("Poland", "Warsaw"); + Customer customer = new Customer(1L, "JOE", "DOE", Arrays.asList(address)); + em.persist(customer); + em.getTransaction() + .commit(); + em.close(); + + // NORMAL SCOPE + EntityManager em2 = getEntityManagerWithOpenTransaction(); + Customer foundCustomer = em2.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE); + em2.getTransaction() + .rollback(); + + // EXTENDED SCOPE + Map map = new HashMap<>(); + map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED); + + EntityManager em3 = getEntityManagerWithOpenTransaction(); + foundCustomer = em3.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE, map); + em2.getTransaction() + .rollback(); + + em2.close(); + em3.close(); + } + + @Test + public void givenEntityWithOneToMany_whenLock_thenHibernateExtendedScopeLockOnlyOwningEntity() throws IOException { + EntityManager em = getEntityManagerWithOpenTransaction(); + PessimisticLockingStudent student = new PessimisticLockingStudent(1L, "JOE"); + PessimisticLockingCourse course = new PessimisticLockingCourse(1L, "COURSE", student); + student.setCourses(Arrays.asList(course)); + em.persist(course); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + + // NORMAL SCOPE + EntityManager em2 = getEntityManagerWithOpenTransaction(); + PessimisticLockingCourse foundCourse = em2.find(PessimisticLockingCourse.class, 1L, LockModeType.PESSIMISTIC_WRITE); + em2.getTransaction() + .rollback(); + + // EXTENDED SCOPE + Map map = new HashMap<>(); + map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED); + + EntityManager em3 = getEntityManagerWithOpenTransaction(); + foundCourse = em3.find(PessimisticLockingCourse.class, 1L, LockModeType.PESSIMISTIC_WRITE, map); + em3.getTransaction() + .rollback(); + + em2.close(); + em3.close(); + } + + protected EntityManager getEntityManagerWithOpenTransaction() throws IOException { + String propertyFileName = "hibernate-pessimistic-locking.properties"; + EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName) + .openSession(); + entityManager.getTransaction() + .begin(); + + return entityManager; + } + +} diff --git a/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties b/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties new file mode 100644 index 0000000000..c76bd3358b --- /dev/null +++ b/hibernate5/src/test/resources/hibernate-pessimistic-locking.properties @@ -0,0 +1,8 @@ +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100;MVCC=FALSE +hibernate.connection.username=sa +hibernate.connection.autocommit=true +hibernate.dialect=org.hibernate.dialect.H2Dialect + +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/hystrix/pom.xml b/hystrix/pom.xml index 8e4a9b28b7..b17ca2bfd9 100644 --- a/hystrix/pom.xml +++ b/hystrix/pom.xml @@ -6,10 +6,10 @@ hystrix - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/java-ee-8-security-api/README.md b/java-ee-8-security-api/README.md new file mode 100644 index 0000000000..1735419236 --- /dev/null +++ b/java-ee-8-security-api/README.md @@ -0,0 +1,3 @@ +### Relevant articles + + - [Java EE 8 Security API](http://www.baeldung.com/java-ee-8-security) diff --git a/java-ee-8-security-api/app-auth-basic-store-db/pom.xml b/java-ee-8-security-api/app-auth-basic-store-db/pom.xml new file mode 100644 index 0000000000..7782fd0479 --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/pom.xml @@ -0,0 +1,72 @@ + + + 4.0.0 + + app-auth-basic-store-db + war + + + com.baeldung + java-ee-8-security-api + 1.0-SNAPSHOT + + + + 1.4.197 + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy + package + + copy + + + + + + + com.h2database + h2 + ${h2-version} + jar + + ${project.build.directory}/liberty/wlp/usr/servers/defaultServer/lib/global + + + + + + + + diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AdminServlet.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AdminServlet.java new file mode 100644 index 0000000000..32adbf1abb --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AdminServlet.java @@ -0,0 +1,22 @@ +package com.baeldung.javaee.security; + +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@WebServlet("/admin") +@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"admin_role"})) +public class AdminServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n"); + response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n"); + response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role")); + } +} \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AppConfig.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AppConfig.java new file mode 100644 index 0000000000..a16d944f5a --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/AppConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition; +import javax.security.enterprise.authentication.mechanism.http.CustomFormAuthenticationMechanismDefinition; +import javax.security.enterprise.identitystore.DatabaseIdentityStoreDefinition; + +@BasicAuthenticationMechanismDefinition(realmName = "defaultRealm") +@DatabaseIdentityStoreDefinition( + dataSourceLookup = "java:comp/env/jdbc/securityDS", + callerQuery = "select password from users where username = ?", + groupsQuery = "select GROUPNAME from groups where username = ?" +) +@ApplicationScoped +public class AppConfig { +} diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/DatabaseSetupServlet.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/DatabaseSetupServlet.java new file mode 100644 index 0000000000..3658826e4d --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/DatabaseSetupServlet.java @@ -0,0 +1,59 @@ +package com.baeldung.javaee.security; + +import javax.annotation.Resource; +import javax.annotation.sql.DataSourceDefinition; +import javax.inject.Inject; +import javax.security.enterprise.identitystore.Pbkdf2PasswordHash; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +@DataSourceDefinition( + name = "java:comp/env/jdbc/securityDS", + className = "org.h2.jdbcx.JdbcDataSource", + url = "jdbc:h2:~/securityTest;MODE=Oracle" +) +@WebServlet(value = "/init", loadOnStartup = 0) +public class DatabaseSetupServlet extends HttpServlet { + + @Resource(lookup = "java:comp/env/jdbc/securityDS") + private DataSource dataSource; + + @Inject + private Pbkdf2PasswordHash passwordHash; + + @Override + public void init() throws ServletException { + super.init(); + initdb(); + } + + private void initdb() { + executeUpdate(dataSource, "DROP TABLE IF EXISTS USERS"); + executeUpdate(dataSource, "DROP TABLE IF EXISTS GROUPS"); + + executeUpdate(dataSource, "CREATE TABLE IF NOT EXISTS USERS(username VARCHAR(64) PRIMARY KEY, password VARCHAR(255))"); + executeUpdate(dataSource, "CREATE TABLE IF NOT EXISTS GROUPS(username VARCHAR(64), GROUPNAME VARCHAR(64))"); + + executeUpdate(dataSource, "INSERT INTO USERS VALUES('admin', '" + passwordHash.generate("passadmin".toCharArray()) + "')"); + executeUpdate(dataSource, "INSERT INTO USERS VALUES('user', '" + passwordHash.generate("passuser".toCharArray()) + "')"); + + executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('admin', 'admin_role')"); + executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('admin', 'user_role')"); + executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('user', 'user_role')"); + } + + private void executeUpdate(DataSource dataSource, String query) { + try (Connection connection = dataSource.getConnection()) { + try (PreparedStatement statement = connection.prepareStatement(query)) { + statement.executeUpdate(); + } + } catch (SQLException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/UserServlet.java b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/UserServlet.java new file mode 100644 index 0000000000..548b5f6d85 --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/java/com/baeldung/javaee/security/UserServlet.java @@ -0,0 +1,25 @@ +package com.baeldung.javaee.security; + +import javax.annotation.security.DeclareRoles; +import javax.inject.Inject; +import javax.security.enterprise.SecurityContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + + +@WebServlet("/user") +@ServletSecurity(value = @HttpConstraint(rolesAllowed = {"user_role"})) +public class UserServlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.getWriter().append("User :" + request.getUserPrincipal().getName() + "\n"); + response.getWriter().append("User in Role user_role :" + request.isUserInRole("user_role") + "\n"); + response.getWriter().append("User in Role admin_role :" + request.isUserInRole("admin_role")); + } +} diff --git a/java-ee-8-security-api/app-auth-basic-store-db/src/main/liberty/config/server.xml b/java-ee-8-security-api/app-auth-basic-store-db/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c49adff459 --- /dev/null +++ b/java-ee-8-security-api/app-auth-basic-store-db/src/main/liberty/config/server.xml @@ -0,0 +1,9 @@ + + + + webProfile-8.0 + + + + diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml new file mode 100644 index 0000000000..35a90621ae --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml @@ -0,0 +1,42 @@ + + + 4.0.0 + + app-auth-custom-form-store-custom + war + + + com.baeldung + java-ee-8-security-api + 1.0-SNAPSHOT + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + + diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/AppConfig.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/AppConfig.java new file mode 100644 index 0000000000..bba9fa36ce --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/AppConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.faces.annotation.FacesConfig; +import javax.security.enterprise.authentication.mechanism.http.CustomFormAuthenticationMechanismDefinition; +import javax.security.enterprise.authentication.mechanism.http.LoginToContinue; + + +@CustomFormAuthenticationMechanismDefinition( + loginToContinue = @LoginToContinue( + loginPage = "/login.xhtml", + errorPage = "/login-error.html" + ) +) +@ApplicationScoped +public class AppConfig { +} diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authentication.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authentication.java new file mode 100644 index 0000000000..54219f9750 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authentication.java @@ -0,0 +1,46 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.security.enterprise.credential.UsernamePasswordCredential; +import javax.security.enterprise.identitystore.CredentialValidationResult; +import javax.security.enterprise.identitystore.IdentityStore; +import java.util.*; + +import static javax.security.enterprise.identitystore.CredentialValidationResult.INVALID_RESULT; + +@ApplicationScoped +public class InMemoryIdentityStore4Authentication implements IdentityStore { + + private Map users = new HashMap<>(); + + public InMemoryIdentityStore4Authentication() { + //Init users + // from a file or hardcoded + init(); + } + + private void init() { + //user1 + users.put("user", "pass0"); + //user2 + users.put("admin", "pass1"); + } + + @Override + public int priority() { + return 70; + } + + @Override + public Set validationTypes() { + return EnumSet.of(ValidationType.VALIDATE); + } + + public CredentialValidationResult validate(UsernamePasswordCredential credential) { + String password = users.get(credential.getCaller()); + if (password != null && password.equals(credential.getPasswordAsString())) { + return new CredentialValidationResult(credential.getCaller()); + } + return INVALID_RESULT; + } +} diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authorization.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authorization.java new file mode 100644 index 0000000000..f088ab80b9 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/InMemoryIdentityStore4Authorization.java @@ -0,0 +1,46 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.ApplicationScoped; +import javax.security.enterprise.identitystore.CredentialValidationResult; +import javax.security.enterprise.identitystore.IdentityStore; +import java.util.*; + +@ApplicationScoped +class InMemoryIdentityStore4Authorization implements IdentityStore { + + private Map> userRoles = new HashMap<>(); + + public InMemoryIdentityStore4Authorization() { + //Init users + // from a file or hardcoded + init(); + } + + private void init() { + //user1 + List roles = new ArrayList<>(); + roles.add("USER_ROLE"); + userRoles.put("user", roles); + //user2 + roles = new ArrayList<>(); + roles.add("USER_ROLE"); + roles.add("ADMIN_ROLE"); + userRoles.put("admin", roles); + } + + @Override + public int priority() { + return 80; + } + + @Override + public Set validationTypes() { + return EnumSet.of(ValidationType.PROVIDE_GROUPS); + } + + @Override + public Set getCallerGroups(CredentialValidationResult validationResult) { + List roles = userRoles.get(validationResult.getCallerPrincipal().getName()); + return new HashSet<>(roles); + } +} diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/LoginBean.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/LoginBean.java new file mode 100644 index 0000000000..f8ee83432a --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/LoginBean.java @@ -0,0 +1,81 @@ +package com.baeldung.javaee.security; + +import javax.enterprise.context.RequestScoped; +import javax.faces.annotation.FacesConfig; +import javax.faces.application.FacesMessage; +import javax.faces.context.FacesContext; +import javax.inject.Inject; +import javax.inject.Named; +import javax.security.enterprise.AuthenticationStatus; +import javax.security.enterprise.SecurityContext; +import javax.security.enterprise.credential.Credential; +import javax.security.enterprise.credential.Password; +import javax.security.enterprise.credential.UsernamePasswordCredential; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.validation.constraints.NotNull; + +import static javax.faces.application.FacesMessage.SEVERITY_ERROR; +import static javax.security.enterprise.AuthenticationStatus.SEND_CONTINUE; +import static javax.security.enterprise.AuthenticationStatus.SEND_FAILURE; +import static javax.security.enterprise.authentication.mechanism.http.AuthenticationParameters.withParams; + +@FacesConfig +@Named +@RequestScoped +public class LoginBean { + + @Inject + private SecurityContext securityContext; + + @Inject + private FacesContext facesContext; + + @NotNull + private String username; + + @NotNull + private String password; + + public void login() { + Credential credential = new UsernamePasswordCredential(username, new Password(password)); + AuthenticationStatus status = securityContext.authenticate( + getHttpRequestFromFacesContext(), + getHttpResponseFromFacesContext(), + withParams().credential(credential)); + if (status.equals(SEND_CONTINUE)) { + facesContext.responseComplete(); + } else if (status.equals(SEND_FAILURE)) { + facesContext.addMessage(null, + new FacesMessage(SEVERITY_ERROR, "Authentication failed", null)); + } + } + + private HttpServletRequest getHttpRequestFromFacesContext() { + return (HttpServletRequest) facesContext + .getExternalContext() + .getRequest(); + } + + private HttpServletResponse getHttpResponseFromFacesContext() { + return (HttpServletResponse) facesContext + .getExternalContext() + .getResponse(); + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/WelcomeServlet.java b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/WelcomeServlet.java new file mode 100644 index 0000000000..fb9c944140 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/java/com/baeldung/javaee/security/WelcomeServlet.java @@ -0,0 +1,31 @@ +package com.baeldung.javaee.security; + +import javax.inject.Inject; +import javax.security.enterprise.SecurityContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.HttpConstraint; +import javax.servlet.annotation.ServletSecurity; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@WebServlet("/welcome") +@ServletSecurity(@HttpConstraint(rolesAllowed = "USER_ROLE")) +public class WelcomeServlet extends HttpServlet { + + @Inject + private SecurityContext securityContext; + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + securityContext.hasAccessToWebResource("/protectedServlet", "GET"); + resp.getWriter().write("" + + "Authentication type :" + req.getAuthType() + "\n" + + "Caller Principal :" + securityContext.getCallerPrincipal() + "\n" + + "User in Role USER_ROLE :" + securityContext.isCallerInRole("USER_ROLE") + "\n" + + "User in Role ADMIN_ROLE :" + securityContext.isCallerInRole("ADMIN_ROLE") + "\n" + + ""); + } +} \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/liberty/config/server.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c49adff459 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/liberty/config/server.xml @@ -0,0 +1,9 @@ + + + + webProfile-8.0 + + + + diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/beans.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 0000000000..2f4726a77e --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,7 @@ + + + diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/web.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..bd219bf983 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,27 @@ + + + + + javax.faces.validator.ENABLE_VALIDATE_WHOLE_BEAN + true + + + + javax.faces.ENABLE_CDI_RESOLVER_CHAIN + true + + + + Faces Servlet + javax.faces.webapp.FacesServlet + 1 + + + Faces Servlet + *.xhtml + + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login-error.html b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login-error.html new file mode 100644 index 0000000000..c540797b54 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login-error.html @@ -0,0 +1,10 @@ + + + + + Title + + +Custom Form Authentication Error + + \ No newline at end of file diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login.xhtml b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login.xhtml new file mode 100644 index 0000000000..48928b2513 --- /dev/null +++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/src/main/webapp/login.xhtml @@ -0,0 +1,32 @@ + + + + + + + +

+ Custom Form-based Authentication +

+ +
+

+ Username + +

+

+ Password + +

+

+ +

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

+ Welcome !! +

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

+ Form-based Authentication +

+
+

+ Username + +

+

+ Password + +

+

+ +

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

+ Form-based Authentication +

+
+

+ Username + +

+

+ Password + +

+

+ +

+
+ + \ No newline at end of file diff --git a/java-ee-8-security-api/pom.xml b/java-ee-8-security-api/pom.xml new file mode 100644 index 0000000000..cdc288f469 --- /dev/null +++ b/java-ee-8-security-api/pom.xml @@ -0,0 +1,73 @@ + + + 4.0.0 + + com.baeldung + java-ee-8-security-api + 1.0-SNAPSHOT + pom + + + 1.8 + 1.8 + UTF-8 + + 9080 + 9443 + + 8.0 + 2.3 + 18.0.0.1 + 1.4.197 + + + + app-auth-basic-store-db + app-auth-form-store-ldap + app-auth-custom-form-store-custom + app-auth-custom-no-store + + + + + javax + javaee-web-api + ${javaee-version} + provided + + + + + + + maven-war-plugin + + false + pom.xml + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + ${liberty-maven-plugin.version} + + + + https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/nightly/2018-05-25_1422/openliberty-all-20180525-1300.zip + + + true + project + src/main/liberty/config/server.xml + true + + ${defaultHttpPort} + ${defaultHttpsPort} + + + + + + diff --git a/java-lite/src/test/java/app/models/ProductTest.java b/java-lite/src/test/java/app/models/ProductUnitTest.java similarity index 95% rename from java-lite/src/test/java/app/models/ProductTest.java rename to java-lite/src/test/java/app/models/ProductUnitTest.java index 5e5c6e8845..416df67d0e 100644 --- a/java-lite/src/test/java/app/models/ProductTest.java +++ b/java-lite/src/test/java/app/models/ProductUnitTest.java @@ -4,7 +4,7 @@ import org.javalite.activejdbc.Base; import org.junit.Assert; import org.junit.Test; -public class ProductTest { +public class ProductUnitTest { //@Test public void givenSavedProduct_WhenFindFirst_ThenSavedProductIsReturned() { diff --git a/java-spi/README.md b/java-spi/README.md new file mode 100644 index 0000000000..d2658c42fe --- /dev/null +++ b/java-spi/README.md @@ -0,0 +1,4 @@ + +### Relevant Articles: + +- [Java Service Provider Interface](http://www.baeldung.com/java-spi) diff --git a/java-vavr-stream/README.md b/java-vavr-stream/README.md new file mode 100644 index 0000000000..64299cde11 --- /dev/null +++ b/java-vavr-stream/README.md @@ -0,0 +1,5 @@ + +### Relevant Articles: + +- [Java Streams vs Vavr Streams](http://www.baeldung.com/vavr-java-streams) + diff --git a/java-websocket/pom.xml b/java-websocket/pom.xml index 461182e504..85078bd696 100644 --- a/java-websocket/pom.xml +++ b/java-websocket/pom.xml @@ -5,8 +5,6 @@ java-websocket war 0.0.1-SNAPSHOT - java-websocket Maven Webapp - http://maven.apache.org com.baeldung diff --git a/javax-servlets/README.md b/javax-servlets/README.md index 84330ac94c..55ca1116aa 100644 --- a/javax-servlets/README.md +++ b/javax-servlets/README.md @@ -2,3 +2,6 @@ - [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets) - [An MVC Example with Servlets and JSP](http://www.baeldung.com/mvc-servlet-jsp) - [Handling Cookies and a Session in a Java Servlet](http://www.baeldung.com/java-servlet-cookies-session) +- [Uploading Files with Servlets and JSP](http://www.baeldung.com/upload-file-servlet) +- [Example of Downloading File in a Servlet](http://www.baeldung.com/servlet-download-file) +- [Returning a JSON Response from a Servlet](http://www.baeldung.com/servlet-json-response) diff --git a/javax-servlets/pom.xml b/javax-servlets/pom.xml index 69d952da9c..f64ce67a1f 100644 --- a/javax-servlets/pom.xml +++ b/javax-servlets/pom.xml @@ -1,46 +1,79 @@ - 4.0.0 - javax-servlets - 1.0-SNAPSHOT + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + javax-servlets + 1.0-SNAPSHOT - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - - javax.servlet - javax.servlet-api - ${javax.servlet.version} - - - org.apache.httpcomponents - httpclient - ${org.apache.httpcomponents.version} - test - - - commons-logging - commons-logging - - - - - org.springframework - spring-test - ${spring-test.version} - test - - + + + + commons-fileupload + commons-fileupload + 1.3.3 + + + commons-io + commons-io + 2.6 + - - 3.1.0 - 4.5.3 - 5.0.5.RELEASE - + + + 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 + + + + + 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/Constants.java b/javax-servlets/src/main/java/com/baeldung/Constants.java new file mode 100644 index 0000000000..90c64870ad --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/Constants.java @@ -0,0 +1,11 @@ +package com.baeldung; + +public class Constants { + + public static final String UPLOAD_DIRECTORY = "upload"; + public static final String DEFAULT_FILENAME = "default.file"; + + public static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; + public static final int MAX_FILE_SIZE = 1024 * 1024 * 40; + public static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; +} \ No newline at end of file diff --git a/javax-servlets/src/main/java/com/baeldung/model/Employee.java b/javax-servlets/src/main/java/com/baeldung/model/Employee.java new file mode 100644 index 0000000000..698a598962 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/model/Employee.java @@ -0,0 +1,72 @@ +package com.baeldung.model; + +public class Employee { + + private int id; + private String name; + private String department; + private long salary; + + public Employee(int id, String name, String department, long salary) { + super(); + this.id = id; + this.name = name; + this.department = department; + this.salary = salary; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + id; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Employee other = (Employee) obj; + if (id != other.id) + return false; + return true; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDepartment() { + return department; + } + + public void setDepartment(String department) { + this.department = department; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + +} diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/DownloadServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/DownloadServlet.java new file mode 100644 index 0000000000..9bbf8f4095 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/DownloadServlet.java @@ -0,0 +1,35 @@ +package com.baeldung.servlets; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@WebServlet("/download") +public class DownloadServlet extends HttpServlet { + private final int ARBITARY_SIZE = 1048; + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + resp.setContentType("text/plain"); + resp.setHeader("Content-disposition", "attachment; filename=sample.txt"); + + OutputStream out = resp.getOutputStream(); + InputStream in = req.getServletContext().getResourceAsStream("/WEB-INF/sample.txt"); + + byte[] buffer = new byte[ARBITARY_SIZE]; + + int numBytesRead; + while ((numBytesRead = in.read(buffer)) > 0) { + out.write(buffer, 0, numBytesRead); + } + + in.close(); + out.flush(); + } +} diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/EmployeeServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/EmployeeServlet.java new file mode 100644 index 0000000000..dbc1a010f7 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/EmployeeServlet.java @@ -0,0 +1,34 @@ +package com.baeldung.servlets; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.baeldung.model.Employee; +import com.google.gson.Gson; + + +@WebServlet(name = "EmployeeServlet", urlPatterns = "/employeeServlet") +public class EmployeeServlet extends HttpServlet { + + private Gson gson = new Gson(); + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException { + + Employee employee = new Employee(1, "Karan", "IT", 5000); + String employeeJsonString = this.gson.toJson(employee); + + PrintWriter out = response.getWriter(); + response.setContentType("application/json"); + response.setCharacterEncoding("UTF-8"); + out.print(employeeJsonString); + out.flush(); + } + +} diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/ErrorHandlerServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/ErrorHandlerServlet.java new file mode 100644 index 0000000000..0008e837c0 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/ErrorHandlerServlet.java @@ -0,0 +1,34 @@ +package com.baeldung.servlets; + +import javax.servlet.annotation.*; +import javax.servlet.http.*; +import java.io.*; +import java.util.*; + +import static javax.servlet.RequestDispatcher.*; + +@WebServlet(urlPatterns = "/errorHandler") +public class ErrorHandlerServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws IOException { + resp.setContentType("text/html; charset=utf-8"); + try (PrintWriter writer = resp.getWriter()) { + writer.write("Error description"); + writer.write("

Error description

"); + writer.write("
    "); + Arrays.asList(ERROR_STATUS_CODE, ERROR_EXCEPTION_TYPE, ERROR_MESSAGE) + .forEach(e -> + writer.write("
  • " + e + ":" + req.getAttribute(e) + "
  • ") + ); + writer.write("
"); + writer.write(""); + } + + Exception exception = (Exception) req.getAttribute(ERROR_EXCEPTION); + if (IllegalArgumentException.class.isInstance(exception)) { + getServletContext().log("Error on an application argument", exception); + } + } +} \ No newline at end of file diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/MultipartServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/MultipartServlet.java new file mode 100644 index 0000000000..185edcf916 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/MultipartServlet.java @@ -0,0 +1,54 @@ +package com.baeldung.servlets; + +import com.baeldung.Constants; + +import javax.servlet.ServletException; +import javax.servlet.annotation.MultipartConfig; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.Part; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; + +import static com.baeldung.Constants.UPLOAD_DIRECTORY; + +@WebServlet( + name = "MultiPartServlet", + urlPatterns = {"/multiPartServlet"} +) +@MultipartConfig(fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024 * 1024 * 5 * 5) +public class MultipartServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private String getFileName(Part part) { + for (String content : part.getHeader("content-disposition").split(";")) { + if (content.trim().startsWith("filename")) + return content.substring(content.indexOf("=") + 2, content.length() - 1); + } + return Constants.DEFAULT_FILENAME; + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; + File uploadDir = new File(uploadPath); + if (!uploadDir.exists()) + uploadDir.mkdir(); + + try { + String fileName = ""; + for (Part part : request.getParts()) { + fileName = getFileName(part); + part.write(uploadPath + File.separator + fileName); + } + request.setAttribute("message", "File " + fileName + " has uploaded successfully!"); + } catch (FileNotFoundException fne) { + request.setAttribute("message", "There was an error: " + fne.getMessage()); + } + getServletContext().getRequestDispatcher("/result.jsp").forward(request, response); + } +} \ No newline at end of file diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/RandomErrorServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/RandomErrorServlet.java new file mode 100644 index 0000000000..c95bd2cec0 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/RandomErrorServlet.java @@ -0,0 +1,13 @@ +package com.baeldung.servlets; + +import javax.servlet.annotation.*; +import javax.servlet.http.*; + +@WebServlet(urlPatterns = "/randomError") +public class RandomErrorServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest req, final HttpServletResponse resp) { + throw new IllegalStateException("Random error"); + } +} \ No newline at end of file diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/UploadServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/UploadServlet.java new file mode 100644 index 0000000000..4de7b20913 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/UploadServlet.java @@ -0,0 +1,63 @@ +package com.baeldung.servlets; + +import javax.servlet.annotation.WebServlet; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.IOException; +import java.util.List; + +import static com.baeldung.Constants.*; + +@WebServlet( + name = "UploadServlet", + urlPatterns = {"/uploadFile"} +) +public class UploadServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + if (ServletFileUpload.isMultipartContent(request)) { + + DiskFileItemFactory factory = new DiskFileItemFactory(); + factory.setSizeThreshold(MEMORY_THRESHOLD); + factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); + + ServletFileUpload upload = new ServletFileUpload(factory); + upload.setFileSizeMax(MAX_FILE_SIZE); + upload.setSizeMax(MAX_REQUEST_SIZE); + String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; + File uploadDir = new File(uploadPath); + if (!uploadDir.exists()) { + uploadDir.mkdir(); + } + + try { + List formItems = upload.parseRequest(request); + + if (formItems != null && formItems.size() > 0) { + for (FileItem item : formItems) { + if (!item.isFormField()) { + String fileName = new File(item.getName()).getName(); + String filePath = uploadPath + File.separator + fileName; + File storeFile = new File(filePath); + item.write(storeFile); + request.setAttribute("message", "File " + fileName + " has uploaded successfully!"); + } + } + } + } catch (Exception ex) { + request.setAttribute("message", "There was an error: " + ex.getMessage()); + } + getServletContext().getRequestDispatcher("/result.jsp").forward(request, response); + } + } +} \ No newline at end of file diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/UploadWelcomeServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/UploadWelcomeServlet.java new file mode 100644 index 0000000000..56cec546be --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/UploadWelcomeServlet.java @@ -0,0 +1,18 @@ +package com.baeldung.servlets; + +import java.io.IOException; +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(name = "UploadWelcomeServlet", urlPatterns = "/uploadwelcome") +public class UploadWelcomeServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + request.getRequestDispatcher("/upload.jsp").forward(request, response); + } +} diff --git a/javax-servlets/src/main/webapp/WEB-INF/web.xml b/javax-servlets/src/main/webapp/WEB-INF/web.xml index 66934d8fd3..c9a06ac52d 100644 --- a/javax-servlets/src/main/webapp/WEB-INF/web.xml +++ b/javax-servlets/src/main/webapp/WEB-INF/web.xml @@ -1,7 +1,16 @@ - - + + 404 + /error-404.html + + + + java.lang.Exception + /errorHandler + \ No newline at end of file diff --git a/javax-servlets/src/main/webapp/error-404.html b/javax-servlets/src/main/webapp/error-404.html new file mode 100644 index 0000000000..b36fc44160 --- /dev/null +++ b/javax-servlets/src/main/webapp/error-404.html @@ -0,0 +1,14 @@ + + + + + Error page + + + +

Error: Page not found

+ +Go back home + + + \ No newline at end of file diff --git a/javax-servlets/src/main/webapp/result.jsp b/javax-servlets/src/main/webapp/result.jsp new file mode 100644 index 0000000000..2e985cb322 --- /dev/null +++ b/javax-servlets/src/main/webapp/result.jsp @@ -0,0 +1,13 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> + + + + + + Upload Result + + + +

${message}

+ + \ No newline at end of file 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/main/webapp/upload.jsp b/javax-servlets/src/main/webapp/upload.jsp new file mode 100644 index 0000000000..f365484892 --- /dev/null +++ b/javax-servlets/src/main/webapp/upload.jsp @@ -0,0 +1,23 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> + + + + + + File Upload Demo + + + +
Apache FileUpload
+
+ Choose a file: +
+ +
+ +
Servlet Multipart
+
+ Choose a file: +
+ + \ No newline at end of file diff --git a/javax-servlets/src/test/java/com/baeldung/servlets/EmployeeServletIntegrationTest.java b/javax-servlets/src/test/java/com/baeldung/servlets/EmployeeServletIntegrationTest.java new file mode 100644 index 0000000000..4fe4908075 --- /dev/null +++ b/javax-servlets/src/test/java/com/baeldung/servlets/EmployeeServletIntegrationTest.java @@ -0,0 +1,54 @@ +package com.baeldung.servlets; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +import java.io.PrintWriter; +import java.io.StringWriter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import com.baeldung.model.Employee; +import com.google.gson.Gson; + + +@RunWith(MockitoJUnitRunner.class) +public class EmployeeServletIntegrationTest { + + @Mock + HttpServletRequest httpServletRequest; + + @Mock + HttpServletResponse httpServletResponse; + + Employee employee; + + @Test + public void whenPostRequestToEmployeeServlet_thenEmployeeReturnedAsJson() throws Exception { + + //Given + int id = 1; + String name = "Karan Khanna"; + String department = "IT"; + long salary = 5000; + employee = new Employee(id, name, department, salary); + + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + when(httpServletResponse.getWriter()).thenReturn(pw); + + EmployeeServlet employeeServlet = new EmployeeServlet(); + employeeServlet.doGet(httpServletRequest, httpServletResponse); + + String employeeJsonString = sw.getBuffer().toString().trim(); + Employee fetchedEmployee = new Gson().fromJson(employeeJsonString, Employee.class); + assertEquals(fetchedEmployee, employee); + } + +} diff --git a/jaxb/pom.xml b/jaxb/pom.xml index 26d7c8d362..f8e5ec0977 100644 --- a/jaxb/pom.xml +++ b/jaxb/pom.xml @@ -39,6 +39,11 @@ commons-lang3 ${commons-lang3.version} + + javax.activation + activation + 1.1 +
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java index 0a3da677ce..26cd5814ac 100644 --- a/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java +++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java @@ -1,48 +1,48 @@ - -package com.baeldung.jaxb.gen; - -import javax.xml.bind.annotation.XmlRegistry; - - -/** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the com.baeldung.jaxb.gen package. - *

An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. - * - */ -@XmlRegistry -public class ObjectFactory { - - - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.baeldung.jaxb.gen - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link UserRequest } - * - */ - public UserRequest createUserRequest() { - return new UserRequest(); - } - - /** - * Create an instance of {@link UserResponse } - * - */ - public UserResponse createUserResponse() { - return new UserResponse(); - } - -} + +package com.baeldung.jaxb.gen; + +import javax.xml.bind.annotation.XmlRegistry; + + +/** + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the com.baeldung.jaxb.gen package. + *

An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are + * provided in this class. + * + */ +@XmlRegistry +public class ObjectFactory { + + + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.baeldung.jaxb.gen + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link UserRequest } + * + */ + public UserRequest createUserRequest() { + return new UserRequest(); + } + + /** + * Create an instance of {@link UserResponse } + * + */ + public UserResponse createUserResponse() { + return new UserResponse(); + } + +} diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java index 1c1abc61a6..4cfbeb8d46 100644 --- a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java +++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java @@ -1,87 +1,87 @@ - -package com.baeldung.jaxb.gen; - -import java.io.Serializable; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - - -/** - *

Java class for UserRequest complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="UserRequest">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
- *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "UserRequest", propOrder = { - "id", - "name" -}) -@XmlRootElement(name = "userRequest") -public class UserRequest - implements Serializable -{ - - private final static long serialVersionUID = -1L; - protected int id; - @XmlElement(required = true) - protected String name; - - /** - * Gets the value of the id property. - * - */ - public int getId() { - return id; - } - - /** - * Sets the value of the id property. - * - */ - public void setId(int value) { - this.id = value; - } - - /** - * Gets the value of the name property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getName() { - return name; - } - - /** - * Sets the value of the name property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setName(String value) { - this.name = value; - } - -} + +package com.baeldung.jaxb.gen; + +import java.io.Serializable; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for UserRequest complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="UserRequest">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
+ *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "UserRequest", propOrder = { + "id", + "name" +}) +@XmlRootElement(name = "userRequest") +public class UserRequest + implements Serializable +{ + + private final static long serialVersionUID = -1L; + protected int id; + @XmlElement(required = true) + protected String name; + + /** + * Gets the value of the id property. + * + */ + public int getId() { + return id; + } + + /** + * Sets the value of the id property. + * + */ + public void setId(int value) { + this.id = value; + } + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + +} diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java index b80405e4a9..d86778403a 100644 --- a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java +++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java @@ -1,149 +1,149 @@ - -package com.baeldung.jaxb.gen; - -import java.io.Serializable; -import java.util.Calendar; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlSchemaType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import org.w3._2001.xmlschema.Adapter1; - - -/** - *

Java class for UserResponse complex type. - * - *

The following schema fragment specifies the expected content contained within this class. - * - *

- * <complexType name="UserResponse">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
- *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="gender" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="created" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
- * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "UserResponse", propOrder = { - "id", - "name", - "gender", - "created" -}) -@XmlRootElement(name = "userResponse") -public class UserResponse - implements Serializable -{ - - private final static long serialVersionUID = -1L; - protected int id; - @XmlElement(required = true) - protected String name; - @XmlElement(required = true) - protected String gender; - @XmlElement(required = true, type = String.class) - @XmlJavaTypeAdapter(Adapter1 .class) - @XmlSchemaType(name = "dateTime") - protected Calendar created; - - /** - * Gets the value of the id property. - * - */ - public int getId() { - return id; - } - - /** - * Sets the value of the id property. - * - */ - public void setId(int value) { - this.id = value; - } - - /** - * Gets the value of the name property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getName() { - return name; - } - - /** - * Sets the value of the name property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setName(String value) { - this.name = value; - } - - /** - * Gets the value of the gender property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getGender() { - return gender; - } - - /** - * Sets the value of the gender property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setGender(String value) { - this.gender = value; - } - - /** - * Gets the value of the created property. - * - * @return - * possible object is - * {@link String } - * - */ - public Calendar getCreated() { - return created; - } - - /** - * Sets the value of the created property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setCreated(Calendar value) { - this.created = value; - } - -} + +package com.baeldung.jaxb.gen; + +import java.io.Serializable; +import java.util.Calendar; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import org.w3._2001.xmlschema.Adapter1; + + +/** + *

Java class for UserResponse complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType name="UserResponse">
+ *   <complexContent>
+ *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+ *       <sequence>
+ *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}int"/>
+ *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="gender" type="{http://www.w3.org/2001/XMLSchema}string"/>
+ *         <element name="created" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
+ *       </sequence>
+ *     </restriction>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "UserResponse", propOrder = { + "id", + "name", + "gender", + "created" +}) +@XmlRootElement(name = "userResponse") +public class UserResponse + implements Serializable +{ + + private final static long serialVersionUID = -1L; + protected int id; + @XmlElement(required = true) + protected String name; + @XmlElement(required = true) + protected String gender; + @XmlElement(required = true, type = String.class) + @XmlJavaTypeAdapter(Adapter1 .class) + @XmlSchemaType(name = "dateTime") + protected Calendar created; + + /** + * Gets the value of the id property. + * + */ + public int getId() { + return id; + } + + /** + * Sets the value of the id property. + * + */ + public void setId(int value) { + this.id = value; + } + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + + /** + * Gets the value of the gender property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getGender() { + return gender; + } + + /** + * Sets the value of the gender property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setGender(String value) { + this.gender = value; + } + + /** + * Gets the value of the created property. + * + * @return + * possible object is + * {@link String } + * + */ + public Calendar getCreated() { + return created; + } + + /** + * Sets the value of the created property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCreated(Calendar value) { + this.created = value; + } + +} diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java index 639d00179c..6384eab27f 100644 --- a/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java +++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java @@ -1,2 +1,2 @@ -@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/jaxb/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) -package com.baeldung.jaxb.gen; +@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/jaxb/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) +package com.baeldung.jaxb.gen; diff --git a/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java b/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java index 54b3c360dc..b4865b5510 100644 --- a/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java +++ b/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java @@ -1,23 +1,23 @@ - -package org.w3._2001.xmlschema; - -import java.util.Calendar; -import javax.xml.bind.annotation.adapters.XmlAdapter; - -public class Adapter1 - extends XmlAdapter -{ - - - public Calendar unmarshal(String value) { - return (javax.xml.bind.DatatypeConverter.parseDateTime(value)); - } - - public String marshal(Calendar value) { - if (value == null) { - return null; - } - return (javax.xml.bind.DatatypeConverter.printDateTime(value)); - } - -} + +package org.w3._2001.xmlschema; + +import java.util.Calendar; +import javax.xml.bind.annotation.adapters.XmlAdapter; + +public class Adapter1 + extends XmlAdapter +{ + + + public Calendar unmarshal(String value) { + return (javax.xml.bind.DatatypeConverter.parseDateTime(value)); + } + + public String marshal(Calendar value) { + if (value == null) { + return null; + } + return (javax.xml.bind.DatatypeConverter.printDateTime(value)); + } + +} diff --git a/jaxb/src/main/resources/log4jstructuraldp.properties b/jaxb/src/main/resources/log4jstructuraldp.properties new file mode 100644 index 0000000000..5bc2bfe4b9 --- /dev/null +++ b/jaxb/src/main/resources/log4jstructuraldp.properties @@ -0,0 +1,9 @@ + +# Root logger +log4j.rootLogger=INFO, file, stdout + +# Write to console +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java b/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java index b2dde85c0f..77b7f1a0b3 100644 --- a/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java +++ b/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java @@ -44,7 +44,7 @@ public class JaxbIntegrationTest { File bookFile = new File(this.getClass().getResource("/book.xml").getFile()); String sampleBookXML = FileUtils.readFileToString(sampleBookFile, "UTF-8"); String marshallerBookXML = FileUtils.readFileToString(bookFile, "UTF-8"); - Assert.assertEquals(sampleBookXML, marshallerBookXML); + Assert.assertEquals(sampleBookXML.replace("\r", "").replace("\n", ""), marshallerBookXML.replace("\r", "").replace("\n", "")); } @Test diff --git a/jaxb/src/test/resources/book.xml b/jaxb/src/test/resources/book.xml new file mode 100644 index 0000000000..605d531b16 --- /dev/null +++ b/jaxb/src/test/resources/book.xml @@ -0,0 +1,5 @@ + + + Book1 + 2016-12-16T17:28:49.718Z + diff --git a/jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java b/jee-7/src/test/java/com/baeldung/convListVal/ConvListValLiveTest.java similarity index 98% rename from jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/convListVal/ConvListValLiveTest.java index caeba95e45..0d6fd295e6 100644 --- a/jee-7/src/test/java/com/baeldung/convListVal/ConvListValIntegrationTest.java +++ b/jee-7/src/test/java/com/baeldung/convListVal/ConvListValLiveTest.java @@ -22,7 +22,7 @@ import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; @RunWith(Arquillian.class) -public class ConvListValIntegrationTest { +public class ConvListValLiveTest { @ArquillianResource private URL deploymentUrl; diff --git a/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanLiveTest.java similarity index 98% rename from jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanLiveTest.java index 0e4c91ad67..41dde6549d 100644 --- a/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanIntegrationTest.java +++ b/jee-7/src/test/java/com/baeldung/timer/AutomaticTimerBeanLiveTest.java @@ -21,7 +21,7 @@ import static org.hamcrest.Matchers.equalTo; @RunWith(Arquillian.class) -public class AutomaticTimerBeanIntegrationTest { +public class AutomaticTimerBeanLiveTest { //the @AutomaticTimerBean has a method called every 10 seconds //testing the difference ==> 100000 diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanLiveTest.java similarity index 96% rename from jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanLiveTest.java index 13cd1729db..350c094f38 100644 --- a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanIntegrationTest.java +++ b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticAtFixedRateTimerBeanLiveTest.java @@ -21,7 +21,7 @@ import static org.hamcrest.Matchers.is; @RunWith(Arquillian.class) -public class ProgrammaticAtFixedRateTimerBeanIntegrationTest { +public class ProgrammaticAtFixedRateTimerBeanLiveTest { final static long TIMEOUT = 1000; final static long TOLERANCE = 500l; diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java similarity index 97% rename from jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java index b90cb6d909..ad079c131b 100644 --- a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanIntegrationTest.java +++ b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticTimerBeanLiveTest.java @@ -19,7 +19,7 @@ import static org.hamcrest.Matchers.is; @RunWith(Arquillian.class) -public class ProgrammaticTimerBeanIntegrationTest { +public class ProgrammaticTimerBeanLiveTest { final static long TIMEOUT = 5000l; final static long TOLERANCE = 1000l; diff --git a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanLiveTest.java similarity index 97% rename from jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanLiveTest.java index e2e660f79b..974f0a285f 100644 --- a/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanIntegrationTest.java +++ b/jee-7/src/test/java/com/baeldung/timer/ProgrammaticWithFixedDelayTimerBeanLiveTest.java @@ -21,7 +21,7 @@ import static org.hamcrest.Matchers.is; @RunWith(Arquillian.class) -public class ProgrammaticWithFixedDelayTimerBeanIntegrationTest { +public class ProgrammaticWithFixedDelayTimerBeanLiveTest { final static long TIMEOUT = 15000l; final static long TOLERANCE = 1000l; diff --git a/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java b/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanLiveTest.java similarity index 97% rename from jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java rename to jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanLiveTest.java index 580edade77..a4ed9ceb68 100644 --- a/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanIntegrationTest.java +++ b/jee-7/src/test/java/com/baeldung/timer/ScheduleTimerBeanLiveTest.java @@ -20,7 +20,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @RunWith(Arquillian.class) -public class ScheduleTimerBeanIntegrationTest { +public class ScheduleTimerBeanLiveTest { private final static long TIMEOUT = 5000l; private final static long TOLERANCE = 1000l; diff --git a/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java similarity index 95% rename from jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java rename to jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java index 72ba4cc5b9..a6fd606e3f 100644 --- a/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java +++ b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java @@ -7,7 +7,7 @@ import org.junit.Ignore; import org.junit.Test; @Ignore -public class JerseyClientTest { +public class JerseyClientIntegrationTest { private static int HTTP_OK = 200; diff --git a/jhipster/jhipster-microservice/car-app/pom.xml b/jhipster/jhipster-microservice/car-app/pom.xml index 77e214234e..e5593bdbb9 100644 --- a/jhipster/jhipster-microservice/car-app/pom.xml +++ b/jhipster/jhipster-microservice/car-app/pom.xml @@ -3,10 +3,10 @@ 4.0.0 - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 com.car.app diff --git a/jhipster/jhipster-microservice/dealer-app/pom.xml b/jhipster/jhipster-microservice/dealer-app/pom.xml index beada8f064..3c21e0042f 100644 --- a/jhipster/jhipster-microservice/dealer-app/pom.xml +++ b/jhipster/jhipster-microservice/dealer-app/pom.xml @@ -3,10 +3,10 @@ 4.0.0 - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 com.dealer.app diff --git a/jhipster/jhipster-microservice/gateway-app/pom.xml b/jhipster/jhipster-microservice/gateway-app/pom.xml index d90addf51b..42808e26ce 100644 --- a/jhipster/jhipster-microservice/gateway-app/pom.xml +++ b/jhipster/jhipster-microservice/gateway-app/pom.xml @@ -3,10 +3,10 @@ 4.0.0 - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 com.gateway diff --git a/jhipster/jhipster-monolithic/pom.xml b/jhipster/jhipster-monolithic/pom.xml index fc8e8353b4..c8c9578fd6 100644 --- a/jhipster/jhipster-monolithic/pom.xml +++ b/jhipster/jhipster-monolithic/pom.xml @@ -3,10 +3,10 @@ 4.0.0 - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 com.baeldung diff --git a/jjwt/pom.xml b/jjwt/pom.xml index 51d4dcf1c0..2aa52b8818 100644 --- a/jjwt/pom.xml +++ b/jjwt/pom.xml @@ -10,10 +10,10 @@ Exercising the JJWT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/jmeter/pom.xml b/jmeter/pom.xml index bb5769ef57..5f9509f0be 100644 --- a/jmeter/pom.xml +++ b/jmeter/pom.xml @@ -9,10 +9,10 @@ Intro to Performance testing using JMeter - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/jni/README.md b/jni/README.md new file mode 100644 index 0000000000..663cafb0c0 --- /dev/null +++ b/jni/README.md @@ -0,0 +1,4 @@ + +### Relevant Articles: + +- [Guide to JNI (Java Native Interface)](http://www.baeldung.com/jni) diff --git a/jni/native/linux_x86_64/libnative.so b/jni/native/linux_x86_64/libnative.so new file mode 100755 index 0000000000..213491e268 Binary files /dev/null and b/jni/native/linux_x86_64/libnative.so differ diff --git a/jni/native/macos/libnative.dylib b/jni/native/macos/libnative.dylib new file mode 100755 index 0000000000..6d1264d696 Binary files /dev/null and b/jni/native/macos/libnative.dylib differ diff --git a/jni/native/win32/native.dll b/jni/native/win32/native.dll new file mode 100644 index 0000000000..683cdb1435 Binary files /dev/null and b/jni/native/win32/native.dll differ diff --git a/jni/pom.xml b/jni/pom.xml new file mode 100644 index 0000000000..752277f526 --- /dev/null +++ b/jni/pom.xml @@ -0,0 +1,15 @@ + + 4.0.0 + com.baeldung + jni + 0.0.1-SNAPSHOT + + + + junit + junit + 4.8.1 + test + + + \ No newline at end of file diff --git a/jni/src/main/cpp/com_baeldung_jni_ExampleObjectsJNI.cpp b/jni/src/main/cpp/com_baeldung_jni_ExampleObjectsJNI.cpp new file mode 100644 index 0000000000..65c11cb9e1 --- /dev/null +++ b/jni/src/main/cpp/com_baeldung_jni_ExampleObjectsJNI.cpp @@ -0,0 +1,48 @@ +#include "com_baeldung_jni_ExampleObjectsJNI.h" +#include + +/* + * Class: com_baeldung_jni_ExampleObjectsJNI + * Method: createUser + * Signature: (Ljava/lang/String;D)Lcom/baeldung/jni/UserData; + */ +JNIEXPORT jobject JNICALL Java_com_baeldung_jni_ExampleObjectsJNI_createUser + (JNIEnv *env, jobject thisObject, jstring name, jdouble balance){ + + // Create the object of the class UserData + jclass userDataClass = env->FindClass("com/baeldung/jni/UserData"); + jobject newUserData = env->AllocObject(userDataClass); + + // Get UserData fields to set + jfieldID nameField = env->GetFieldID(userDataClass , "name", "Ljava/lang/String;"); + jfieldID balanceField = env->GetFieldID(userDataClass , "balance", "D"); + + // Set the values of the new object + env->SetObjectField(newUserData, nameField, name); + env->SetDoubleField(newUserData, balanceField, balance); + + // Return the created object + return newUserData; + } + +/* + * Class: com_baeldung_jni_ExampleObjectsJNI + * Method: printUserData + * Signature: (Lcom/baeldung/jni/UserData;)Ljava/lang/String; + */ +JNIEXPORT jstring JNICALL Java_com_baeldung_jni_ExampleObjectsJNI_printUserData + (JNIEnv *env, jobject thisObject, jobject userData){ + + // Find the class method id + jclass userDataClass = env->GetObjectClass(userData); + jmethodID methodId = env->GetMethodID(userDataClass, "getUserInfo", "()Ljava/lang/String;"); + + // Call the object method and get the result + jstring result = (jstring)env->CallObjectMethod(userData, methodId); + + // Print the result + std::cout << "C++: User data is: " << env->GetStringUTFChars(result, NULL) << std::endl; + + return result; + } + diff --git a/jni/src/main/cpp/com_baeldung_jni_ExampleObjectsJNI.h b/jni/src/main/cpp/com_baeldung_jni_ExampleObjectsJNI.h new file mode 100644 index 0000000000..28cb782eed --- /dev/null +++ b/jni/src/main/cpp/com_baeldung_jni_ExampleObjectsJNI.h @@ -0,0 +1,29 @@ +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class com_baeldung_jni_ExampleObjectsJNI */ + +#ifndef _Included_com_baeldung_jni_ExampleObjectsJNI +#define _Included_com_baeldung_jni_ExampleObjectsJNI +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: com_baeldung_jni_ExampleObjectsJNI + * Method: createUser + * Signature: (Ljava/lang/String;D)Lcom/baeldung/jni/UserData; + */ +JNIEXPORT jobject JNICALL Java_com_baeldung_jni_ExampleObjectsJNI_createUser + (JNIEnv *, jobject, jstring, jdouble); + +/* + * Class: com_baeldung_jni_ExampleObjectsJNI + * Method: printUserData + * Signature: (Lcom/baeldung/jni/UserData;)V + */ +JNIEXPORT jstring JNICALL Java_com_baeldung_jni_ExampleObjectsJNI_printUserData + (JNIEnv *, jobject, jobject); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/jni/src/main/cpp/com_baeldung_jni_ExampleParametersJNI.cpp b/jni/src/main/cpp/com_baeldung_jni_ExampleParametersJNI.cpp new file mode 100644 index 0000000000..319b85f592 --- /dev/null +++ b/jni/src/main/cpp/com_baeldung_jni_ExampleParametersJNI.cpp @@ -0,0 +1,34 @@ +#include "com_baeldung_jni_ExampleParametersJNI.h" +#include +#include + +/* + * Class: com_baeldung_jni_ExampleParametersJNI + * Method: sumIntegers + * Signature: (II)J + */ +JNIEXPORT jlong JNICALL Java_com_baeldung_jni_ExampleParametersJNI_sumIntegers (JNIEnv* env, jobject thisObject, jint first, jint second){ + std::cout << "C++: The numbers received are : " << first << " and " << second << std::endl; + return (long)first + (long)second; +} + + +/* + * Class: com_baeldung_jni_ExampleParametersJNI + * Method: sayHelloToMe + * Signature: (Ljava/lang/String;Z)Ljava/lang/String; + */ +JNIEXPORT jstring JNICALL Java_com_baeldung_jni_ExampleParametersJNI_sayHelloToMe (JNIEnv* env, jobject thisObject, jstring name, jboolean isFemale){ + const char* nameCharPointer = env->GetStringUTFChars(name, NULL); + std::cout << "C++: The string received is: " << nameCharPointer << std::endl; + std::string title; + if(isFemale){ + title = "Ms. "; + } + else{ + title = "Mr. "; + } + + std::string fullName = title + nameCharPointer; + return env->NewStringUTF(fullName.c_str()); +} diff --git a/jni/src/main/cpp/com_baeldung_jni_ExampleParametersJNI.h b/jni/src/main/cpp/com_baeldung_jni_ExampleParametersJNI.h new file mode 100644 index 0000000000..58b9a2ca2f --- /dev/null +++ b/jni/src/main/cpp/com_baeldung_jni_ExampleParametersJNI.h @@ -0,0 +1,29 @@ +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class com_baeldung_jni_ExampleParametersJNI */ + +#ifndef _Included_com_baeldung_jni_ExampleParametersJNI +#define _Included_com_baeldung_jni_ExampleParametersJNI +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: com_baeldung_jni_ExampleParametersJNI + * Method: sumIntegers + * Signature: (II)J + */ +JNIEXPORT jlong JNICALL Java_com_baeldung_jni_ExampleParametersJNI_sumIntegers + (JNIEnv*, jobject, jint, jint); + +/* + * Class: com_baeldung_jni_ExampleParametersJNI + * Method: sayHelloToMe + * Signature: (Ljava/lang/String;Z)Ljava/lang/String; + */ +JNIEXPORT jstring JNICALL Java_com_baeldung_jni_ExampleParametersJNI_sayHelloToMe + (JNIEnv*, jobject, jstring, jboolean); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/jni/src/main/cpp/com_baeldung_jni_HelloWorldJNI.cpp b/jni/src/main/cpp/com_baeldung_jni_HelloWorldJNI.cpp new file mode 100644 index 0000000000..d2001ebdac --- /dev/null +++ b/jni/src/main/cpp/com_baeldung_jni_HelloWorldJNI.cpp @@ -0,0 +1,13 @@ +#include "com_baeldung_jni_HelloWorldJNI.h" +#include + +/* + * Class: com_baeldung_jni_HelloWorldJNI + * Method: sayHello + * Signature: ()Ljava/lang/String; + */ +JNIEXPORT jstring JNICALL Java_com_baeldung_jni_HelloWorldJNI_sayHello (JNIEnv* env, jobject thisObject) { + std::string hello = "Hello from C++ !!"; + std::cout << hello << std::endl; + return env->NewStringUTF(hello.c_str()); +} \ No newline at end of file diff --git a/jni/src/main/cpp/com_baeldung_jni_HelloWorldJNI.h b/jni/src/main/cpp/com_baeldung_jni_HelloWorldJNI.h new file mode 100644 index 0000000000..fbdd4cc8f7 --- /dev/null +++ b/jni/src/main/cpp/com_baeldung_jni_HelloWorldJNI.h @@ -0,0 +1,21 @@ +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class com_baeldung_jni_HelloWorldJNI */ + +#ifndef _Included_com_baeldung_jni_HelloWorldJNI +#define _Included_com_baeldung_jni_HelloWorldJNI +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: com_baeldung_jni_HelloWorldJNI + * Method: sayHello + * Signature: ()V + */ +JNIEXPORT jstring JNICALL Java_com_baeldung_jni_HelloWorldJNI_sayHello + (JNIEnv *, jobject); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/jni/src/main/cpp/generateNativeLib.bat b/jni/src/main/cpp/generateNativeLib.bat new file mode 100644 index 0000000000..73fb29fa66 --- /dev/null +++ b/jni/src/main/cpp/generateNativeLib.bat @@ -0,0 +1,6 @@ +REM Create the header with javac -h . ClassName.java +REM Remember to set your JAVA_HOME env var +g++ -c -I%JAVA_HOME%\include -I%JAVA_HOME%\include\win32 com_baeldung_jni_HelloWorldJNI.cpp -o com_baeldung_jni_HelloWorldJNI.o +g++ -c -I%JAVA_HOME%\include -I%JAVA_HOME%\include\win32 com_baeldung_jni_ExampleParametersJNI.cpp -o com_baeldung_jni_ExampleParametersJNI.o +g++ -c -I%JAVA_HOME%\include -I%JAVA_HOME%\include\win32 com_baeldung_jni_ExampleObjectsJNI.cpp -o com_baeldung_jni_ExampleObjectsJNI.o +g++ -shared -o ..\..\..\native\win32\native.dll com_baeldung_jni_HelloWorldJNI.o com_baeldung_jni_ExampleParametersJNI.o com_baeldung_jni_ExampleObjectsJNI.o -Wl,--add-stdcall-alias \ No newline at end of file diff --git a/jni/src/main/cpp/generateNativeLib.sh b/jni/src/main/cpp/generateNativeLib.sh new file mode 100755 index 0000000000..4a90d1ee04 --- /dev/null +++ b/jni/src/main/cpp/generateNativeLib.sh @@ -0,0 +1,7 @@ +# Create the header with javac -h . ClassName.java +# Remember to set your JAVA_HOME env var +g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/linux com_baeldung_jni_HelloWorldJNI.cpp -o com_baeldung_jni_HelloWorldJNI.o +g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/linux com_baeldung_jni_ExampleParametersJNI.cpp -o com_baeldung_jni_ExampleParametersJNI.o +g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/linux com_baeldung_jni_ExampleObjectsJNI.cpp -o com_baeldung_jni_ExampleObjectsJNI.o +g++ -shared -fPIC -o ../../../native/linux_x86_64/libnative.so com_baeldung_jni_HelloWorldJNI.o com_baeldung_jni_ExampleParametersJNI.o com_baeldung_jni_ExampleObjectsJNI.o -lc +# Don't forget to set java.library.path to point to the folder where you have the libnative you're loading. \ No newline at end of file diff --git a/jni/src/main/cpp/generateNativeLibMac.sh b/jni/src/main/cpp/generateNativeLibMac.sh new file mode 100755 index 0000000000..d11dcc7c01 --- /dev/null +++ b/jni/src/main/cpp/generateNativeLibMac.sh @@ -0,0 +1,6 @@ +# Create the header with javac -h . ClassName.java +# Remember to set your JAVA_HOME env var +g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/darwin com_baeldung_jni_HelloWorldJNI.cpp -o com_baeldung_jni_HelloWorldJNI.o +g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/darwin com_baeldung_jni_ExampleParametersJNI.cpp -o com_baeldung_jni_ExampleParametersJNI.o +g++ -c -fPIC -I${JAVA_HOME}/include -I${JAVA_HOME}/include/darwin com_baeldung_jni_ExampleObjectsJNI.cpp -o com_baeldung_jni_ExampleObjectsJNI.o +g++ -dynamiclib -o ../../../native/macos/libnative.dylib com_baeldung_jni_HelloWorldJNI.o com_baeldung_jni_ExampleParametersJNI.o com_baeldung_jni_ExampleObjectsJNI.o -lc \ No newline at end of file diff --git a/jni/src/main/java/com/baeldung/jni/ExampleObjectsJNI.java b/jni/src/main/java/com/baeldung/jni/ExampleObjectsJNI.java new file mode 100644 index 0000000000..b8ebfb3cd5 --- /dev/null +++ b/jni/src/main/java/com/baeldung/jni/ExampleObjectsJNI.java @@ -0,0 +1,19 @@ +package com.baeldung.jni; + +public class ExampleObjectsJNI { + + static { + System.loadLibrary("native"); + } + + public static void main(String[] args) { + ExampleObjectsJNI instance = new ExampleObjectsJNI(); + UserData newUser = instance.createUser("John Doe", 450.67); + instance.printUserData(newUser); + } + + public native UserData createUser(String name, double balance); + + public native String printUserData(UserData user); + +} diff --git a/jni/src/main/java/com/baeldung/jni/ExampleParametersJNI.java b/jni/src/main/java/com/baeldung/jni/ExampleParametersJNI.java new file mode 100644 index 0000000000..f4553b7773 --- /dev/null +++ b/jni/src/main/java/com/baeldung/jni/ExampleParametersJNI.java @@ -0,0 +1,20 @@ +package com.baeldung.jni; + +public class ExampleParametersJNI { + + static { + System.loadLibrary("native"); + } + + public static void main(String[] args) { + System.out.println("Java: My full name: " + new ExampleParametersJNI().sayHelloToMe("Martin", false)); + long sumFromNative = new ExampleParametersJNI().sumIntegers(456, 44); + System.out.println("Java: The sum coming from native code is: " + sumFromNative); + } + + // Declare another method sumIntegers that receives two integers and return a long with the sum + public native long sumIntegers(int first, int second); + + // Declare another method sayHelloToMe that receives the name and gender and returns the proper salutation + public native String sayHelloToMe(String name, boolean isFemale); +} diff --git a/jni/src/main/java/com/baeldung/jni/HelloWorldJNI.java b/jni/src/main/java/com/baeldung/jni/HelloWorldJNI.java new file mode 100644 index 0000000000..a351238900 --- /dev/null +++ b/jni/src/main/java/com/baeldung/jni/HelloWorldJNI.java @@ -0,0 +1,15 @@ +package com.baeldung.jni; + +public class HelloWorldJNI { + + static { + System.loadLibrary("native"); + } + + public static void main(String[] args) { + new HelloWorldJNI().sayHello(); + } + + // Declare a native method sayHello() that receives no arguments and returns void + public native String sayHello(); +} diff --git a/jni/src/main/java/com/baeldung/jni/UserData.java b/jni/src/main/java/com/baeldung/jni/UserData.java new file mode 100644 index 0000000000..5b93f9dfb0 --- /dev/null +++ b/jni/src/main/java/com/baeldung/jni/UserData.java @@ -0,0 +1,11 @@ +package com.baeldung.jni; + +public class UserData { + + public String name; + public double balance; + + public String getUserInfo() { + return "[name]=" + name + ", [balance]=" + balance; + } +} diff --git a/jni/src/test/java/com/baeldung/jni/JNINativeTests.java b/jni/src/test/java/com/baeldung/jni/JNINativeTests.java new file mode 100644 index 0000000000..42e572d41b --- /dev/null +++ b/jni/src/test/java/com/baeldung/jni/JNINativeTests.java @@ -0,0 +1,58 @@ +package com.baeldung.jni; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; + +public class JNINativeTests { + + @Before + public void setup() { + System.loadLibrary("native"); + } + + @Test + public void whenNativeHelloWorld_thenOutputIsAsExpected() { + HelloWorldJNI helloWorld = new HelloWorldJNI(); + String helloFromNative = helloWorld.sayHello(); + assertTrue(!helloFromNative.isEmpty() && helloFromNative.equals("Hello from C++ !!")); + } + + @Test + public void whenSumNative_thenResultIsArithmeticallyCorrect() { + ExampleParametersJNI parametersNativeMethods = new ExampleParametersJNI(); + assertTrue(parametersNativeMethods.sumIntegers(200, 400) == 600L); + } + + @Test + public void whenSayingNativeHelloToMe_thenResultIsAsExpected() { + ExampleParametersJNI parametersNativeMethods = new ExampleParametersJNI(); + assertEquals(parametersNativeMethods.sayHelloToMe("Orange", true), "Ms. Orange"); + } + + @Test + public void whenCreatingNativeObject_thenObjectIsNotNullAndHasCorrectData() { + String name = "Iker Casillas"; + double balance = 2378.78; + ExampleObjectsJNI objectsNativeMethods = new ExampleObjectsJNI(); + UserData userFromNative = objectsNativeMethods.createUser(name, balance); + assertNotNull(userFromNative); + assertEquals(userFromNative.name, name); + assertTrue(userFromNative.balance == balance); + } + + @Test + public void whenNativeCallingObjectMethod_thenResultIsAsExpected() { + String name = "Sergio Ramos"; + double balance = 666.77; + ExampleObjectsJNI objectsNativeMethods = new ExampleObjectsJNI(); + UserData userData = new UserData(); + userData.name = name; + userData.balance = balance; + assertEquals(objectsNativeMethods.printUserData(userData), "[name]=" + name + ", [balance]=" + balance); + } + +} diff --git a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java similarity index 98% rename from jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java rename to jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java index c0fb5485aa..8bc8c854da 100644 --- a/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureIntegrationTest.java +++ b/jpa-storedprocedure/src/test/java/com/baeldung/jpa/storedprocedure/StoredProcedureLiveTest.java @@ -15,7 +15,7 @@ import org.junit.Test; import com.baeldung.jpa.model.Car; -public class StoredProcedureIntegrationTest { +public class StoredProcedureLiveTest { private static EntityManagerFactory factory = null; private static EntityManager entityManager = null; diff --git a/json-path/src/main/resources/online_store.json b/json-path/src/main/resources/online_store.json new file mode 100644 index 0000000000..c0ddf274d8 --- /dev/null +++ b/json-path/src/main/resources/online_store.json @@ -0,0 +1,23 @@ +{ + "items":{ + "book":[ + { + "author":"Arthur Conan Doyle", + "title":"Sherlock Holmes", + "price":8.99 + }, + { + "author":"J. R. R. Tolkien", + "title":"The Lord of the Rings", + "isbn":"0-395-19395-8", + "price":22.99 + } + ], + "bicycle":{ + "color":"red", + "price":19.95 + } + }, + "url":"mystore.com", + "owner":"baeldung" +} \ No newline at end of file diff --git a/json-path/src/test/java/com/baeldung/jsonpath/introduction/JsonPathUnitTest.java b/json-path/src/test/java/com/baeldung/jsonpath/introduction/JsonPathUnitTest.java new file mode 100644 index 0000000000..3408629a6d --- /dev/null +++ b/json-path/src/test/java/com/baeldung/jsonpath/introduction/JsonPathUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.jsonpath.introduction; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.Map; + +import org.junit.BeforeClass; +import org.junit.Test; + +import com.jayway.jsonpath.JsonPath; + +import net.minidev.json.JSONArray; + +public class JsonPathUnitTest { + + private static String json; + private static File jsonFile = new File("src/main/resources/online_store.json"); + + private static String readFile(File file, Charset charset) throws IOException { + return new String(Files.readAllBytes(file.toPath()), charset); + } + + @BeforeClass + public static void init() throws IOException { + json = readFile(jsonFile, StandardCharsets.UTF_8); + } + + @Test + public void shouldMatchCountOfObjects() { + Map objectMap = JsonPath.read(json, "$"); + assertEquals(3, objectMap.keySet() + .size()); + } + + @Test + public void shouldMatchCountOfArrays() { + JSONArray jsonArray = JsonPath.read(json, "$.items.book[*]"); + assertEquals(2, jsonArray.size()); + } + +} 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/README.md b/kotlin-js/README.md new file mode 100644 index 0000000000..445ad6da9a --- /dev/null +++ b/kotlin-js/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Kotlin and Javascript](http://www.baeldung.com/kotlin-javascript) diff --git a/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/kotlin-ktor/.gitignore b/kotlin-ktor/.gitignore new file mode 100644 index 0000000000..0c017e8f8c --- /dev/null +++ b/kotlin-ktor/.gitignore @@ -0,0 +1,14 @@ +/bin/ + +#ignore gradle +.gradle/ + + +#ignore build and generated files +build/ +node/ +out/ + +#ignore installed node modules and package lock file +node_modules/ +package-lock.json diff --git a/kotlin-ktor/build.gradle b/kotlin-ktor/build.gradle new file mode 100755 index 0000000000..11aef74857 --- /dev/null +++ b/kotlin-ktor/build.gradle @@ -0,0 +1,47 @@ + + +group 'com.baeldung.ktor' +version '1.0-SNAPSHOT' + + +buildscript { + ext.kotlin_version = '1.2.40' + ext.ktor_version = '0.9.2' + + repositories { + mavenCentral() + } + dependencies { + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +apply plugin: 'java' +apply plugin: 'kotlin' +apply plugin: 'application' + +mainClassName = 'APIServer.kt' + +sourceCompatibility = 1.8 +compileKotlin { kotlinOptions.jvmTarget = "1.8" } +compileTestKotlin { kotlinOptions.jvmTarget = "1.8" } + +kotlin { experimental { coroutines "enable" } } + +repositories { + mavenCentral() + jcenter() + maven { url "https://dl.bintray.com/kotlin/ktor" } +} + +dependencies { + compile "io.ktor:ktor-server-netty:$ktor_version" + compile "ch.qos.logback:logback-classic:1.2.1" + compile "io.ktor:ktor-gson:$ktor_version" + testCompile group: 'junit', name: 'junit', version: '4.12' + +} +task runServer(type: JavaExec) { + main = 'APIServer' + classpath = sourceSets.main.runtimeClasspath +} \ No newline at end of file diff --git a/kotlin-ktor/gradle/wrapper/gradle-wrapper.jar b/kotlin-ktor/gradle/wrapper/gradle-wrapper.jar new file mode 100755 index 0000000000..01b8bf6b1f Binary files /dev/null and b/kotlin-ktor/gradle/wrapper/gradle-wrapper.jar differ diff --git a/kotlin-ktor/gradle/wrapper/gradle-wrapper.properties b/kotlin-ktor/gradle/wrapper/gradle-wrapper.properties new file mode 100755 index 0000000000..0b83b5a3e3 --- /dev/null +++ b/kotlin-ktor/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-ktor/gradlew b/kotlin-ktor/gradlew new file mode 100755 index 0000000000..cccdd3d517 --- /dev/null +++ b/kotlin-ktor/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-ktor/gradlew.bat b/kotlin-ktor/gradlew.bat new file mode 100755 index 0000000000..e95643d6a2 --- /dev/null +++ b/kotlin-ktor/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-ktor/resources/logback.xml b/kotlin-ktor/resources/logback.xml new file mode 100755 index 0000000000..274cdcdb02 --- /dev/null +++ b/kotlin-ktor/resources/logback.xml @@ -0,0 +1,11 @@ + + + + %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + \ No newline at end of file diff --git a/kotlin-ktor/settings.gradle b/kotlin-ktor/settings.gradle new file mode 100755 index 0000000000..13bbce9583 --- /dev/null +++ b/kotlin-ktor/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'KtorWithKotlin' + diff --git a/kotlin-ktor/src/main/kotlin/APIServer.kt b/kotlin-ktor/src/main/kotlin/APIServer.kt new file mode 100755 index 0000000000..e67609e8b2 --- /dev/null +++ b/kotlin-ktor/src/main/kotlin/APIServer.kt @@ -0,0 +1,57 @@ +@file:JvmName("APIServer") + + + +import io.ktor.application.call +import io.ktor.application.install +import io.ktor.features.CallLogging +import io.ktor.features.ContentNegotiation +import io.ktor.features.DefaultHeaders +import io.ktor.gson.gson +import io.ktor.http.ContentType +import io.ktor.request.path +import io.ktor.response.respond +import io.ktor.response.respondText +import io.ktor.routing.get +import io.ktor.routing.routing +import io.ktor.server.engine.embeddedServer +import io.ktor.server.netty.Netty +import org.slf4j.event.Level + +data class Author(val name: String, val website: String) +fun main(args: Array) { + + val jsonResponse = """{ + "id": 1, + "task": "Pay waterbill", + "description": "Pay water bill today", + }""" + + + embeddedServer(Netty, 8080) { + install(DefaultHeaders) { + header("X-Developer", "Baeldung") + } + install(CallLogging) { + level = Level.INFO + filter { call -> call.request.path().startsWith("/todo") } + filter { call -> call.request.path().startsWith("/author") } + } + install(ContentNegotiation) { + gson { + setPrettyPrinting() + } + } + routing { + get("/todo") { + call.respondText(jsonResponse, ContentType.Application.Json) + } + get("/author") { + val author = Author("baeldung", "baeldung.com") + call.respond(author) + + } + + } + }.start(wait = true) +} \ No newline at end of file diff --git a/kotlin-ktor/webapp/WEB-INF/web.xml b/kotlin-ktor/webapp/WEB-INF/web.xml new file mode 100755 index 0000000000..513a80cb27 --- /dev/null +++ b/kotlin-ktor/webapp/WEB-INF/web.xml @@ -0,0 +1,35 @@ + + + + + + + io.ktor.ktor.config + application.conf + + + + KtorServlet + KtorServlet + io.ktor.server.servlet.ServletApplicationEngine + + + true + + + + 304857600 + 304857600 + 0 + + + + + KtorServlet + / + + + \ No newline at end of file diff --git a/libraries-data/README.md b/libraries-data/README.md index 1d7078d203..718f38d703 100644 --- a/libraries-data/README.md +++ b/libraries-data/README.md @@ -3,5 +3,9 @@ - [Introduction to ORMLite](http://www.baeldung.com/ormlite) - [Introduction To Kryo](http://www.baeldung.com/kryo) - [Introduction to KafkaStreams in Java](http://www.baeldung.com/java-kafka-streams) +- [Guide to Java Data Objects](http://www.baeldung.com/jdo) +- [Intro to JDO Queries 2/2](http://www.baeldung.com/jdo-queries) +- [Introduction to HikariCP](http://www.baeldung.com/hikaricp) +- [Introduction to JCache](http://www.baeldung.com/jcache) - [A Guide to Apache Ignite](http://www.baeldung.com/apache-ignite) -- [Apache Ignite with Spring Data](http://www.baeldung.com/apache-ignite-spring-data) +- [Apache Ignite with Spring Data](http://www.baeldung.com/apache-ignite-spring-data) \ No newline at end of file diff --git a/libraries-data/log4j.properties b/libraries-data/log4j.properties new file mode 100644 index 0000000000..2173c5d96f --- /dev/null +++ b/libraries-data/log4j.properties @@ -0,0 +1 @@ +log4j.rootLogger=INFO, stdout diff --git a/libraries-data/myPersistence.xml b/libraries-data/myPersistence.xml new file mode 100644 index 0000000000..de2c250957 --- /dev/null +++ b/libraries-data/myPersistence.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index c0e90a51b2..f1531a8eae 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -87,6 +87,60 @@ gson ${gson.version} + + + com.zaxxer + HikariCP + 2.7.2 + compile + + + + org.datanucleus + javax.jdo + 3.2.0-m7 + + + org.datanucleus + datanucleus-core + 5.1.1 + + + org.datanucleus + datanucleus-api-jdo + 5.1.1 + + + org.datanucleus + datanucleus-rdbms + 5.1.1 + + + org.datanucleus + datanucleus-maven-plugin + 5.0.2 + + + org.datanucleus + datanucleus-xml + 5.0.0-release + + + org.datanucleus + datanucleus-jdo-query + 5.0.4 + + + + javax.cache + cache-api + ${cache.version} + + + com.hazelcast + hazelcast + ${hazelcast.version} + @@ -176,6 +230,29 @@ + + + org.datanucleus + datanucleus-maven-plugin + 5.0.2 + + JDO + ${basedir}/datanucleus.properties + ${basedir}/log4j.properties + true + false + + + + + process-classes + + enhance + + + + + @@ -196,8 +273,10 @@ 1.0.0 2.4.0 2.8.2 + 1.1.0 + 3.8.4 1.8 3.0.0 - \ No newline at end of file + diff --git a/libraries/src/main/java/com/baeldung/hikaricp/DataSource.java b/libraries-data/src/main/java/com/baeldung/hikaricp/DataSource.java similarity index 100% rename from libraries/src/main/java/com/baeldung/hikaricp/DataSource.java rename to libraries-data/src/main/java/com/baeldung/hikaricp/DataSource.java diff --git a/libraries/src/main/java/com/baeldung/hikaricp/Employee.java b/libraries-data/src/main/java/com/baeldung/hikaricp/Employee.java similarity index 100% rename from libraries/src/main/java/com/baeldung/hikaricp/Employee.java rename to libraries-data/src/main/java/com/baeldung/hikaricp/Employee.java diff --git a/libraries/src/main/java/com/baeldung/hikaricp/HikariCPDemo.java b/libraries-data/src/main/java/com/baeldung/hikaricp/HikariCPDemo.java similarity index 100% rename from libraries/src/main/java/com/baeldung/hikaricp/HikariCPDemo.java rename to libraries-data/src/main/java/com/baeldung/hikaricp/HikariCPDemo.java diff --git a/libraries/src/main/java/com/baeldung/jcache/SimpleCacheEntryListener.java b/libraries-data/src/main/java/com/baeldung/jcache/SimpleCacheEntryListener.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jcache/SimpleCacheEntryListener.java rename to libraries-data/src/main/java/com/baeldung/jcache/SimpleCacheEntryListener.java diff --git a/libraries/src/main/java/com/baeldung/jcache/SimpleCacheLoader.java b/libraries-data/src/main/java/com/baeldung/jcache/SimpleCacheLoader.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jcache/SimpleCacheLoader.java rename to libraries-data/src/main/java/com/baeldung/jcache/SimpleCacheLoader.java diff --git a/libraries/src/main/java/com/baeldung/jcache/SimpleEntryProcessor.java b/libraries-data/src/main/java/com/baeldung/jcache/SimpleEntryProcessor.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jcache/SimpleEntryProcessor.java rename to libraries-data/src/main/java/com/baeldung/jcache/SimpleEntryProcessor.java diff --git a/libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java b/libraries-data/src/main/java/com/baeldung/jdo/GuideToJDO.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java rename to libraries-data/src/main/java/com/baeldung/jdo/GuideToJDO.java diff --git a/libraries/src/main/java/com/baeldung/jdo/Product.java b/libraries-data/src/main/java/com/baeldung/jdo/Product.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jdo/Product.java rename to libraries-data/src/main/java/com/baeldung/jdo/Product.java diff --git a/libraries/src/main/java/com/baeldung/jdo/ProductXML.java b/libraries-data/src/main/java/com/baeldung/jdo/ProductXML.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jdo/ProductXML.java rename to libraries-data/src/main/java/com/baeldung/jdo/ProductXML.java diff --git a/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java b/libraries-data/src/main/java/com/baeldung/jdo/query/MyApp.java similarity index 97% rename from libraries/src/main/java/com/baeldung/jdo/query/MyApp.java rename to libraries-data/src/main/java/com/baeldung/jdo/query/MyApp.java index 235142d16e..30f019a79d 100644 --- a/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java +++ b/libraries-data/src/main/java/com/baeldung/jdo/query/MyApp.java @@ -1,96 +1,96 @@ -package com.baeldung.jdo.query; - -import java.util.List; - -import javax.jdo.JDOQLTypedQuery; -import javax.jdo.PersistenceManager; -import javax.jdo.PersistenceManagerFactory; -import javax.jdo.Query; - -import org.datanucleus.api.jdo.JDOPersistenceManagerFactory; -import org.datanucleus.metadata.PersistenceUnitMetaData; - -public class MyApp { - - private static PersistenceManagerFactory pmf; - private static PersistenceManager pm; - - public static void main(String[] args) { - - defineDynamicPersistentUnit(); - createTestData(); - queryUsingJDOQL(); - queryUsingTypedJDOQL(); - queryUsingSQL(); - queryUsingJPQL(); - - } - - public static void createTestData() { - ProductItem item1 = new ProductItem("supportedItem", "price less than 10", "SoldOut", 5); - ProductItem item2 = new ProductItem("pro2", "price less than 10", "InStock", 8); - ProductItem item3 = new ProductItem("pro3", "price more than 10", "SoldOut", 15); - - if (pm != null) { - pm.makePersistent(item1); - pm.makePersistent(item2); - pm.makePersistent(item3); - } - } - - public static void defineDynamicPersistentUnit() { - - PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); - pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:mysql://localhost:3306/jdo_db"); - pumd.addProperty("javax.jdo.option.ConnectionUserName", "root"); - pumd.addProperty("javax.jdo.option.ConnectionPassword", "admin"); - pumd.addProperty("javax.jdo.option.ConnectionDriverName", "com.mysql.jdbc.Driver"); - pumd.addProperty("datanucleus.schema.autoCreateAll", "true"); - - pmf = new JDOPersistenceManagerFactory(pumd, null); - pm = pmf.getPersistenceManager(); - } - - public static void queryUsingJDOQL() { - - Query query = pm.newQuery("SELECT FROM com.baeldung.jdo.query.ProductItem " + "WHERE price < threshold PARAMETERS double threshold"); - List explicitParamResults = (List) query.execute(10); - - query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold"); - query.setParameters("double threshold"); - List explicitParamResults2 = (List) query.execute(10); - - query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold"); - List implicitParamResults = (List) query.execute(10); - - } - - public static void queryUsingTypedJDOQL() { - JDOQLTypedQuery tq = pm.newJDOQLTypedQuery(ProductItem.class); - QProductItem cand = QProductItem.candidate(); - tq = tq.filter(cand.price.lt(10).and(cand.name.startsWith("pro"))); - List results = tq.executeList(); - - } - - public static void queryUsingSQL() { - - Query query = pm.newQuery("javax.jdo.query.SQL", "select * from " + "product_item where price < ? and status = ?"); - query.setClass(ProductItem.class); - query.setParameters(10, "InStock"); - List results = query.executeList(); - - } - - public static void queryUsingJPQL() { - Query query = pm.newQuery("JPQL", "select i from " + "com.baeldung.jdo.query.ProductItem i where i.price < 10" + " and i.status = 'InStock'"); - List results = (List) query.execute(); - - } - - public static void namedQuery() { - Query query = pm.newNamedQuery(ProductItem.class, "PriceBelow10"); - List results = query.executeList(); - - } -} +package com.baeldung.jdo.query; + +import java.util.List; + +import javax.jdo.JDOQLTypedQuery; +import javax.jdo.PersistenceManager; +import javax.jdo.PersistenceManagerFactory; +import javax.jdo.Query; + +import org.datanucleus.api.jdo.JDOPersistenceManagerFactory; +import org.datanucleus.metadata.PersistenceUnitMetaData; + +public class MyApp { + + private static PersistenceManagerFactory pmf; + private static PersistenceManager pm; + + public static void main(String[] args) { + + defineDynamicPersistentUnit(); + createTestData(); + queryUsingJDOQL(); + queryUsingTypedJDOQL(); + queryUsingSQL(); + queryUsingJPQL(); + + } + + public static void createTestData() { + ProductItem item1 = new ProductItem("supportedItem", "price less than 10", "SoldOut", 5); + ProductItem item2 = new ProductItem("pro2", "price less than 10", "InStock", 8); + ProductItem item3 = new ProductItem("pro3", "price more than 10", "SoldOut", 15); + + if (pm != null) { + pm.makePersistent(item1); + pm.makePersistent(item2); + pm.makePersistent(item3); + } + } + + public static void defineDynamicPersistentUnit() { + + PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); + pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:mysql://localhost:3306/jdo_db"); + pumd.addProperty("javax.jdo.option.ConnectionUserName", "root"); + pumd.addProperty("javax.jdo.option.ConnectionPassword", "admin"); + pumd.addProperty("javax.jdo.option.ConnectionDriverName", "com.mysql.jdbc.Driver"); + pumd.addProperty("datanucleus.schema.autoCreateAll", "true"); + + pmf = new JDOPersistenceManagerFactory(pumd, null); + pm = pmf.getPersistenceManager(); + } + + public static void queryUsingJDOQL() { + + Query query = pm.newQuery("SELECT FROM com.baeldung.jdo.query.ProductItem " + "WHERE price < threshold PARAMETERS double threshold"); + List explicitParamResults = (List) query.execute(10); + + query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold"); + query.setParameters("double threshold"); + List explicitParamResults2 = (List) query.execute(10); + + query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold"); + List implicitParamResults = (List) query.execute(10); + + } + + public static void queryUsingTypedJDOQL() { + JDOQLTypedQuery tq = pm.newJDOQLTypedQuery(ProductItem.class); + QProductItem cand = QProductItem.candidate(); + tq = tq.filter(cand.price.lt(10).and(cand.name.startsWith("pro"))); + List results = tq.executeList(); + + } + + public static void queryUsingSQL() { + + Query query = pm.newQuery("javax.jdo.query.SQL", "select * from " + "product_item where price < ? and status = ?"); + query.setClass(ProductItem.class); + query.setParameters(10, "InStock"); + List results = query.executeList(); + + } + + public static void queryUsingJPQL() { + Query query = pm.newQuery("JPQL", "select i from " + "com.baeldung.jdo.query.ProductItem i where i.price < 10" + " and i.status = 'InStock'"); + List results = (List) query.execute(); + + } + + public static void namedQuery() { + Query query = pm.newNamedQuery(ProductItem.class, "PriceBelow10"); + List results = query.executeList(); + + } +} diff --git a/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java b/libraries-data/src/main/java/com/baeldung/jdo/query/ProductItem.java similarity index 95% rename from libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java rename to libraries-data/src/main/java/com/baeldung/jdo/query/ProductItem.java index fbe999ba2a..25dd8bdb98 100644 --- a/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java +++ b/libraries-data/src/main/java/com/baeldung/jdo/query/ProductItem.java @@ -1,70 +1,70 @@ -package com.baeldung.jdo.query; - -import javax.jdo.annotations.IdGeneratorStrategy; -import javax.jdo.annotations.PersistenceCapable; -import javax.jdo.annotations.Persistent; -import javax.jdo.annotations.PrimaryKey; - -@PersistenceCapable(table = "product_item") -public class ProductItem { - - @PrimaryKey - @Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT) - int id; - String name; - String description; - String status; - double price; - - public ProductItem() { - - } - - public ProductItem(String name, String description, String status, double price) { - this.name = name; - this.description = description; - this.status = status; - this.price = price; - } - - 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 getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public double getPrice() { - return price; - } - - public void setPrice(double price) { - this.price = price; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - -} +package com.baeldung.jdo.query; + +import javax.jdo.annotations.IdGeneratorStrategy; +import javax.jdo.annotations.PersistenceCapable; +import javax.jdo.annotations.Persistent; +import javax.jdo.annotations.PrimaryKey; + +@PersistenceCapable(table = "product_item") +public class ProductItem { + + @PrimaryKey + @Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT) + int id; + String name; + String description; + String status; + double price; + + public ProductItem() { + + } + + public ProductItem(String name, String description, String status, double price) { + this.name = name; + this.description = description; + this.status = status; + this.price = price; + } + + 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 getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + +} diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java b/libraries-data/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java similarity index 96% rename from libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java rename to libraries-data/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java index acfc26627a..0673ff341c 100644 --- a/libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java +++ b/libraries-data/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java @@ -1,66 +1,66 @@ -package com.baeldung.jdo.xml; - -import java.util.ArrayList; -import java.util.List; - -import javax.jdo.annotations.Element; -import javax.jdo.annotations.PersistenceCapable; -import javax.jdo.annotations.PrimaryKey; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; - -@PersistenceCapable(schema = "/myproduct/people", table = "person") -public class AnnotadedPerson { - @XmlAttribute - private long personNum; - - @PrimaryKey - private String firstName; - private String lastName; - - @XmlElementWrapper(name = "phone-numbers") - @XmlElement(name = "phone-number") - @Element(types = String.class) - private List phoneNumbers = new ArrayList(); - - public AnnotadedPerson(long personNum, String firstName, String lastName) { - super(); - this.personNum = personNum; - this.firstName = firstName; - this.lastName = lastName; - } - - public long getPersonNum() { - return personNum; - } - - public void setPersonNum(long personNum) { - this.personNum = personNum; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public List getPhoneNumbers() { - return phoneNumbers; - } - - public void setPhoneNumbers(List phoneNumbers) { - this.phoneNumbers = phoneNumbers; - } - -} +package com.baeldung.jdo.xml; + +import java.util.ArrayList; +import java.util.List; + +import javax.jdo.annotations.Element; +import javax.jdo.annotations.PersistenceCapable; +import javax.jdo.annotations.PrimaryKey; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; + +@PersistenceCapable(schema = "/myproduct/people", table = "person") +public class AnnotadedPerson { + @XmlAttribute + private long personNum; + + @PrimaryKey + private String firstName; + private String lastName; + + @XmlElementWrapper(name = "phone-numbers") + @XmlElement(name = "phone-number") + @Element(types = String.class) + private List phoneNumbers = new ArrayList(); + + public AnnotadedPerson(long personNum, String firstName, String lastName) { + super(); + this.personNum = personNum; + this.firstName = firstName; + this.lastName = lastName; + } + + public long getPersonNum() { + return personNum; + } + + public void setPersonNum(long personNum) { + this.personNum = personNum; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public List getPhoneNumbers() { + return phoneNumbers; + } + + public void setPhoneNumbers(List phoneNumbers) { + this.phoneNumbers = phoneNumbers; + } + +} diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java b/libraries-data/src/main/java/com/baeldung/jdo/xml/MyApp.java similarity index 97% rename from libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java rename to libraries-data/src/main/java/com/baeldung/jdo/xml/MyApp.java index c75d3695f7..b43b45f415 100644 --- a/libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java +++ b/libraries-data/src/main/java/com/baeldung/jdo/xml/MyApp.java @@ -1,105 +1,105 @@ -package com.baeldung.jdo.xml; - -import java.util.List; - -import javax.jdo.JDOHelper; -import javax.jdo.PersistenceManager; -import javax.jdo.PersistenceManagerFactory; -import javax.jdo.Query; -import javax.jdo.Transaction; - -import org.datanucleus.api.jdo.JDOPersistenceManagerFactory; -import org.datanucleus.metadata.PersistenceUnitMetaData; - -public class MyApp { - - private static PersistenceUnitMetaData pumd; - private static PersistenceManagerFactory pmf; - private static PersistenceManager pm; - - public static void main(String[] args) { - - // persist product object using dynamic persistence unit - defineDynamicPersistentUnit(); - Product product = new Product("id1", "Sony Discman", "A standard discman from Sony", 49.99); - persistObject(product); - closePersistenceManager(); - - // persist AnnotatedPerson object using named pmf - defineNamedPersistenceManagerFactory("XmlDatastore"); - AnnotadedPerson annotatedPerson = new AnnotadedPerson(654320, "annotated", "person"); - annotatedPerson.getPhoneNumbers().add("999999999"); - annotatedPerson.getPhoneNumbers().add("000000000"); - persistObject(annotatedPerson); - queryAnnotatedPersonsInXML(); - closePersistenceManager(); - - // persist Person object using PMF created by properties file - definePersistenceManagerFactoryUsingPropertiesFile("META-INF\\datanucleus.properties"); - Person person = new Person(654321, "bealdung", "author"); - person.getPhoneNumbers().add("123456789"); - person.getPhoneNumbers().add("987654321"); - persistObject(person); - queryPersonsInXML(); - closePersistenceManager(); - } - - public static void defineDynamicPersistentUnit() { - - PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); - pumd.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myfile_dynamicPMF.xml"); - pumd.addProperty("datanucleus.schema.autoCreateAll", "true"); - pumd.addProperty("datanucleus.xml.indentSize", "4"); - - pmf = new JDOPersistenceManagerFactory(pumd, null); - pm = pmf.getPersistenceManager(); - } - - public static void defineNamedPersistenceManagerFactory(String pmfName) { - - pmf = JDOHelper.getPersistenceManagerFactory("XmlDatastore"); - pm = pmf.getPersistenceManager(); - } - - public static void definePersistenceManagerFactoryUsingPropertiesFile(String filePath) { - - pmf = JDOHelper.getPersistenceManagerFactory(filePath); - pm = pmf.getPersistenceManager(); - } - - public static void closePersistenceManager() { - - if (pm != null && !pm.isClosed()) { - pm.close(); - } - } - - public static void persistObject(Object obj) { - - Transaction tx = pm.currentTransaction(); - - try { - tx.begin(); - pm.makePersistent(obj); - tx.commit(); - } finally { - if (tx.isActive()) { - tx.rollback(); - } - } - } - - public static void queryPersonsInXML() { - - Query query = pm.newQuery(Person.class); - List result = query.executeList(); - System.out.println("name: " + result.get(0).getFirstName()); - } - - public static void queryAnnotatedPersonsInXML() { - - Query query = pm.newQuery(AnnotadedPerson.class); - List result = query.executeList(); - System.out.println("name: " + result.get(0).getFirstName()); - } -} +package com.baeldung.jdo.xml; + +import java.util.List; + +import javax.jdo.JDOHelper; +import javax.jdo.PersistenceManager; +import javax.jdo.PersistenceManagerFactory; +import javax.jdo.Query; +import javax.jdo.Transaction; + +import org.datanucleus.api.jdo.JDOPersistenceManagerFactory; +import org.datanucleus.metadata.PersistenceUnitMetaData; + +public class MyApp { + + private static PersistenceUnitMetaData pumd; + private static PersistenceManagerFactory pmf; + private static PersistenceManager pm; + + public static void main(String[] args) { + + // persist product object using dynamic persistence unit + defineDynamicPersistentUnit(); + Product product = new Product("id1", "Sony Discman", "A standard discman from Sony", 49.99); + persistObject(product); + closePersistenceManager(); + + // persist AnnotatedPerson object using named pmf + defineNamedPersistenceManagerFactory("XmlDatastore"); + AnnotadedPerson annotatedPerson = new AnnotadedPerson(654320, "annotated", "person"); + annotatedPerson.getPhoneNumbers().add("999999999"); + annotatedPerson.getPhoneNumbers().add("000000000"); + persistObject(annotatedPerson); + queryAnnotatedPersonsInXML(); + closePersistenceManager(); + + // persist Person object using PMF created by properties file + definePersistenceManagerFactoryUsingPropertiesFile("META-INF\\datanucleus.properties"); + Person person = new Person(654321, "bealdung", "author"); + person.getPhoneNumbers().add("123456789"); + person.getPhoneNumbers().add("987654321"); + persistObject(person); + queryPersonsInXML(); + closePersistenceManager(); + } + + public static void defineDynamicPersistentUnit() { + + PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null); + pumd.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myfile_dynamicPMF.xml"); + pumd.addProperty("datanucleus.schema.autoCreateAll", "true"); + pumd.addProperty("datanucleus.xml.indentSize", "4"); + + pmf = new JDOPersistenceManagerFactory(pumd, null); + pm = pmf.getPersistenceManager(); + } + + public static void defineNamedPersistenceManagerFactory(String pmfName) { + + pmf = JDOHelper.getPersistenceManagerFactory("XmlDatastore"); + pm = pmf.getPersistenceManager(); + } + + public static void definePersistenceManagerFactoryUsingPropertiesFile(String filePath) { + + pmf = JDOHelper.getPersistenceManagerFactory(filePath); + pm = pmf.getPersistenceManager(); + } + + public static void closePersistenceManager() { + + if (pm != null && !pm.isClosed()) { + pm.close(); + } + } + + public static void persistObject(Object obj) { + + Transaction tx = pm.currentTransaction(); + + try { + tx.begin(); + pm.makePersistent(obj); + tx.commit(); + } finally { + if (tx.isActive()) { + tx.rollback(); + } + } + } + + public static void queryPersonsInXML() { + + Query query = pm.newQuery(Person.class); + List result = query.executeList(); + System.out.println("name: " + result.get(0).getFirstName()); + } + + public static void queryAnnotatedPersonsInXML() { + + Query query = pm.newQuery(AnnotadedPerson.class); + List result = query.executeList(); + System.out.println("name: " + result.get(0).getFirstName()); + } +} diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/Person.java b/libraries-data/src/main/java/com/baeldung/jdo/xml/Person.java similarity index 95% rename from libraries/src/main/java/com/baeldung/jdo/xml/Person.java rename to libraries-data/src/main/java/com/baeldung/jdo/xml/Person.java index 0678201afd..4fbc81ee03 100644 --- a/libraries/src/main/java/com/baeldung/jdo/xml/Person.java +++ b/libraries-data/src/main/java/com/baeldung/jdo/xml/Person.java @@ -1,58 +1,58 @@ -package com.baeldung.jdo.xml; - -import java.util.ArrayList; -import java.util.List; - -import javax.jdo.annotations.PersistenceCapable; -import javax.jdo.annotations.PrimaryKey; - -@PersistenceCapable -public class Person { - private long personNum; - - @PrimaryKey - private String firstName; - private String lastName; - - private List phoneNumbers = new ArrayList(); - - public Person(long personNum, String firstName, String lastName) { - super(); - this.personNum = personNum; - this.firstName = firstName; - this.lastName = lastName; - } - - public long getPersonNum() { - return personNum; - } - - public void setPersonNum(long personNum) { - this.personNum = personNum; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public List getPhoneNumbers() { - return phoneNumbers; - } - - public void setPhoneNumbers(List phoneNumbers) { - this.phoneNumbers = phoneNumbers; - } - -} +package com.baeldung.jdo.xml; + +import java.util.ArrayList; +import java.util.List; + +import javax.jdo.annotations.PersistenceCapable; +import javax.jdo.annotations.PrimaryKey; + +@PersistenceCapable +public class Person { + private long personNum; + + @PrimaryKey + private String firstName; + private String lastName; + + private List phoneNumbers = new ArrayList(); + + public Person(long personNum, String firstName, String lastName) { + super(); + this.personNum = personNum; + this.firstName = firstName; + this.lastName = lastName; + } + + public long getPersonNum() { + return personNum; + } + + public void setPersonNum(long personNum) { + this.personNum = personNum; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public List getPhoneNumbers() { + return phoneNumbers; + } + + public void setPhoneNumbers(List phoneNumbers) { + this.phoneNumbers = phoneNumbers; + } + +} diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/Product.java b/libraries-data/src/main/java/com/baeldung/jdo/xml/Product.java similarity index 94% rename from libraries/src/main/java/com/baeldung/jdo/xml/Product.java rename to libraries-data/src/main/java/com/baeldung/jdo/xml/Product.java index 1e46f212cb..5aac05834d 100644 --- a/libraries/src/main/java/com/baeldung/jdo/xml/Product.java +++ b/libraries-data/src/main/java/com/baeldung/jdo/xml/Product.java @@ -1,58 +1,58 @@ -package com.baeldung.jdo.xml; - -import javax.jdo.annotations.PersistenceCapable; -import javax.jdo.annotations.PrimaryKey; - -@PersistenceCapable -public class Product { - - @PrimaryKey - String id; - String name; - String description; - double price; - - public Product() { - - } - - public Product(String id, String name, String description, double price) { - this.id = id; - this.name = name; - this.description = description; - this.price = price; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public double getPrice() { - return price; - } - - public void setPrice(double price) { - this.price = price; - } - -} +package com.baeldung.jdo.xml; + +import javax.jdo.annotations.PersistenceCapable; +import javax.jdo.annotations.PrimaryKey; + +@PersistenceCapable +public class Product { + + @PrimaryKey + String id; + String name; + String description; + double price; + + public Product() { + + } + + public Product(String id, String name, String description, double price) { + this.id = id; + this.name = name; + this.description = description; + this.price = price; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } + +} diff --git a/libraries-data/src/main/resources/META-INF/BenchmarkList b/libraries-data/src/main/resources/META-INF/BenchmarkList new file mode 100644 index 0000000000..e69de29bb2 diff --git a/libraries-data/src/main/resources/META-INF/datanucleus.properties b/libraries-data/src/main/resources/META-INF/datanucleus.properties new file mode 100644 index 0000000000..7470a58d23 --- /dev/null +++ b/libraries-data/src/main/resources/META-INF/datanucleus.properties @@ -0,0 +1,4 @@ +javax.jdo.PersistenceManagerFactoryClass=org.datanucleus.api.jdo.JDOPersistenceManagerFactory +javax.jdo.option.ConnectionURL= xml:file:myfile-ds.xml +datanucleus.xml.indentSize=6 +datanucleus.schema.autoCreateAll=true \ No newline at end of file diff --git a/libraries/src/main/resources/META-INF/jdoconfig.xml b/libraries-data/src/main/resources/META-INF/jdoconfig.xml similarity index 98% rename from libraries/src/main/resources/META-INF/jdoconfig.xml rename to libraries-data/src/main/resources/META-INF/jdoconfig.xml index 77da460686..910f63cb9a 100644 --- a/libraries/src/main/resources/META-INF/jdoconfig.xml +++ b/libraries-data/src/main/resources/META-INF/jdoconfig.xml @@ -1,17 +1,17 @@ - - - - - - - - - - + + + + + + + + + + \ No newline at end of file diff --git a/libraries/src/main/resources/META-INF/package.jdo b/libraries-data/src/main/resources/META-INF/package.jdo similarity index 97% rename from libraries/src/main/resources/META-INF/package.jdo rename to libraries-data/src/main/resources/META-INF/package.jdo index d3cf501bb6..7f85bbbd58 100644 --- a/libraries/src/main/resources/META-INF/package.jdo +++ b/libraries-data/src/main/resources/META-INF/package.jdo @@ -1,29 +1,29 @@ - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/libraries/src/main/resources/db.sql b/libraries-data/src/main/resources/db.sql similarity index 100% rename from libraries/src/main/resources/db.sql rename to libraries-data/src/main/resources/db.sql diff --git a/libraries/src/test/java/com/baeldung/hikaricp/HikariCPIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/hikaricp/HikariCPIntegrationTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/hikaricp/HikariCPIntegrationTest.java rename to libraries-data/src/test/java/com/baeldung/hikaricp/HikariCPIntegrationTest.java diff --git a/libraries/src/test/java/com/baeldung/jcache/CacheLoaderTest.java b/libraries-data/src/test/java/com/baeldung/jcache/CacheLoaderIntegrationTest.java similarity index 78% rename from libraries/src/test/java/com/baeldung/jcache/CacheLoaderTest.java rename to libraries-data/src/test/java/com/baeldung/jcache/CacheLoaderIntegrationTest.java index a4747785cd..8017418eba 100644 --- a/libraries/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"; @@ -21,7 +21,8 @@ public class CacheLoaderTest { @Before public void setup() { - CachingProvider cachingProvider = Caching.getCachingProvider(); + // Adding fully qualified class name because of multiple Cache Provider (Ignite and Hazelcast) + CachingProvider cachingProvider = Caching.getCachingProvider("com.hazelcast.cache.HazelcastCachingProvider"); CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration config = new MutableConfiguration().setReadThrough(true).setCacheLoaderFactory(new FactoryBuilder.SingletonFactory<>(new SimpleCacheLoader())); this.cache = cacheManager.createCache("SimpleCache", config); @@ -29,7 +30,7 @@ public class CacheLoaderTest { @After public void tearDown() { - Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME); + Caching.getCachingProvider("com.hazelcast.cache.HazelcastCachingProvider").getCacheManager().destroyCache(CACHE_NAME); } @Test @@ -39,4 +40,4 @@ public class CacheLoaderTest { assertEquals("fromCache" + i, value); } } -} \ No newline at end of file +} diff --git a/libraries/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java similarity index 82% rename from libraries/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java rename to libraries-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java index 61c98d0126..fd1e9c29a9 100644 --- a/libraries/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java +++ b/libraries-data/src/test/java/com/baeldung/jcache/EntryProcessorIntegrationTest.java @@ -15,12 +15,13 @@ import static org.junit.Assert.assertEquals; public class EntryProcessorIntegrationTest { private static final String CACHE_NAME = "MyCache"; + private static final String CACHE_PROVIDER_NAME = "com.hazelcast.cache.HazelcastCachingProvider"; private Cache cache; @Before public void instantiateCache() { - CachingProvider cachingProvider = Caching.getCachingProvider(); + CachingProvider cachingProvider = Caching.getCachingProvider(CACHE_PROVIDER_NAME); CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration config = new MutableConfiguration<>(); this.cache = cacheManager.createCache(CACHE_NAME, config); @@ -29,7 +30,7 @@ public class EntryProcessorIntegrationTest { @After public void tearDown() { - Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME); + Caching.getCachingProvider(CACHE_PROVIDER_NAME).getCacheManager().destroyCache(CACHE_NAME); } @Test diff --git a/libraries/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java similarity index 88% rename from libraries/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java rename to libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java index fcbfbe6111..512a75ec61 100644 --- a/libraries/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java +++ b/libraries-data/src/test/java/com/baeldung/jcache/EventListenerIntegrationTest.java @@ -17,6 +17,7 @@ import static org.junit.Assert.assertEquals; public class EventListenerIntegrationTest { private static final String CACHE_NAME = "MyCache"; + private static final String CACHE_PROVIDER_NAME = "com.hazelcast.cache.HazelcastCachingProvider"; private Cache cache; private SimpleCacheEntryListener listener; @@ -24,7 +25,7 @@ public class EventListenerIntegrationTest { @Before public void setup() { - CachingProvider cachingProvider = Caching.getCachingProvider(); + CachingProvider cachingProvider = Caching.getCachingProvider(CACHE_PROVIDER_NAME); CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration config = new MutableConfiguration(); this.cache = cacheManager.createCache("MyCache", config); @@ -33,7 +34,7 @@ public class EventListenerIntegrationTest { @After public void tearDown() { - Caching.getCachingProvider().getCacheManager().destroyCache(CACHE_NAME); + Caching.getCachingProvider(CACHE_PROVIDER_NAME).getCacheManager().destroyCache(CACHE_NAME); } @Test diff --git a/libraries/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java similarity index 94% rename from libraries/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java rename to libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java index fac3d32bcb..33521469fa 100644 --- a/libraries/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java +++ b/libraries-data/src/test/java/com/baeldung/jcache/JCacheIntegrationTest.java @@ -14,7 +14,7 @@ public class JCacheIntegrationTest { @Test public void instantiateCache() { - CachingProvider cachingProvider = Caching.getCachingProvider(); + CachingProvider cachingProvider = Caching.getCachingProvider("com.hazelcast.cache.HazelcastCachingProvider"); CacheManager cacheManager = cachingProvider.getCacheManager(); MutableConfiguration config = new MutableConfiguration<>(); Cache cache = cacheManager.createCache("simpleCache", config); diff --git a/libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java b/libraries-data/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java rename to libraries-data/src/test/java/com/baeldung/jdo/GuideToJDOIntegrationTest.java diff --git a/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml b/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml index a1951f09b7..6e5d212fb8 100644 --- a/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml +++ b/libraries-data/src/test/resources/reladomo/ReladomoTestConfig.xml @@ -2,6 +2,6 @@ - + \ No newline at end of file diff --git a/libraries/.gitignore b/libraries/.gitignore new file mode 100644 index 0000000000..ac45fafa62 --- /dev/null +++ b/libraries/.gitignore @@ -0,0 +1,8 @@ +*.class + +# Folders # +/gensrc +/target + +# Packaged files # +*.jar diff --git a/libraries/README.md b/libraries/README.md index f197ab1270..3ef6303c88 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -17,9 +17,7 @@ - [Introduction to Quartz](http://www.baeldung.com/quartz) - [How to Warm Up the JVM](http://www.baeldung.com/java-jvm-warmup) - [Apache Commons Collections SetUtils](http://www.baeldung.com/apache-commons-setutils) -- [Guide to Java Data Objects](http://www.baeldung.com/jdo) - [Software Transactional Memory in Java Using Multiverse](http://www.baeldung.com/java-multiverse-stm) -- [Introduction to HikariCP](http://www.baeldung.com/hikaricp) - [Serenity BDD with Spring and JBehave](http://www.baeldung.com/serenity-spring-jbehave) - [Locality-Sensitive Hashing in Java Using Java-LSH](http://www.baeldung.com/locality-sensitive-hashing) - [Apache Commons Collections OrderedMap](http://www.baeldung.com/apache-commons-ordered-map) @@ -47,7 +45,6 @@ - [Guide to JDeferred](http://www.baeldung.com/jdeferred) - [Integrating Retrofit with RxJava](http://www.baeldung.com/retrofit-rxjava) - [Introduction to MBassador](http://www.baeldung.com/mbassador) -- [Introduction to JCache](http://www.baeldung.com/jcache) - [Introduction to Retrofit](http://www.baeldung.com/retrofit) - [Using Pairs in Java](http://www.baeldung.com/java-pairs) - [Apache Commons Collections Bag](http://www.baeldung.com/apache-commons-bag) @@ -56,7 +53,6 @@ - [Introduction To Docx4J](http://www.baeldung.com/docx4j) - [Introduction to StreamEx](http://www.baeldung.com/streamex) - [Introduction to BouncyCastle with Java](http://www.baeldung.com/java-bouncy-castle) -- [Intro to JDO Queries 2/2](http://www.baeldung.com/jdo-queries) - [Guide to google-http-client](http://www.baeldung.com/google-http-client) - [Interact with Google Sheets from Java](http://www.baeldung.com/google-sheets-java-client) - [Programatically Create, Configure, and Run a Tomcat Server](http://www.baeldung.com/tomcat-programmatic-setup) @@ -83,6 +79,8 @@ - [Java Concurrency Utility with JCTools](http://www.baeldung.com/java-concurrency-jc-tools) - [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils) - [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel) +- [Creating REST Microservices with Javalin](http://www.baeldung.com/javalin-rest-microservices) + The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own. diff --git a/libraries/pom.xml b/libraries/pom.xml index 678ba3279c..e3a6656995 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -698,6 +698,42 @@ jctools-core ${jctools.version} + + + org.apache.commons + commons-math3 + ${common-math3-version} + + + org.knowm.xchart + xchart + ${xchart-version} + + + + commons-net + commons-net + ${commons-net.version} + + + org.mockftpserver + MockFtpServer + ${mockftpserver.version} + test + + + + com.squareup + javapoet + ${javapoet.version} + + + org.hamcrest + hamcrest-all + ${hamcrest-all.version} + test + + @@ -910,6 +946,12 @@ 0.9.4.0006L 2.1.2 2.5.11 + 3.6.1 + 3.5.2 + 3.6 + 2.7.1 + 1.10.0 + 1.3 \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/commons/math3/Histogram.java b/libraries/src/main/java/com/baeldung/commons/math3/Histogram.java new file mode 100644 index 0000000000..a8c15887be --- /dev/null +++ b/libraries/src/main/java/com/baeldung/commons/math3/Histogram.java @@ -0,0 +1,97 @@ +package com.baeldung.commons.math3; + +import org.apache.commons.math3.stat.Frequency; +import org.knowm.xchart.CategoryChart; +import org.knowm.xchart.CategoryChartBuilder; +import org.knowm.xchart.SwingWrapper; +import org.knowm.xchart.style.Styler; + +import java.util.*; + +public class Histogram { + + private Map distributionMap; + private int classWidth; + + public Histogram() { + + distributionMap = new TreeMap(); + classWidth = 10; + Map distributionMap = processRawData(); + List yData = new ArrayList(); + yData.addAll(distributionMap.values()); + List xData = Arrays.asList(distributionMap.keySet().toArray()); + + CategoryChart chart = buildChart(xData, yData); + new SwingWrapper<>(chart).displayChart(); + + } + + private CategoryChart buildChart(List xData, List yData) { + + // Create Chart + CategoryChart chart = new CategoryChartBuilder().width(800).height(600) + .title("Age Distribution") + .xAxisTitle("Age Group") + .yAxisTitle("Frequency") + .build(); + + chart.getStyler().setLegendPosition(Styler.LegendPosition.InsideNW); + chart.getStyler().setAvailableSpaceFill(0.99); + chart.getStyler().setOverlapped(true); + + chart.addSeries("age group", xData, yData); + + return chart; + } + + private Map processRawData() { + + List datasetList = Arrays.asList( + 36, 25, 38, 46, 55, 68, 72, + 55, 36, 38, 67, 45, 22, 48, + 91, 46, 52, 61, 58, 55); + Frequency frequency = new Frequency(); + datasetList.forEach(d -> frequency.addValue(Double.parseDouble(d.toString()))); + + datasetList.stream() + .map(d -> Double.parseDouble(d.toString())) + .distinct() + .forEach(observation -> { + long observationFrequency = frequency.getCount(observation); + int upperBoundary = (observation > classWidth) + ? Math.multiplyExact( (int) Math.ceil(observation / classWidth), classWidth) + : classWidth; + int lowerBoundary = (upperBoundary > classWidth) + ? Math.subtractExact(upperBoundary, classWidth) + : 0; + String bin = lowerBoundary + "-" + upperBoundary; + + updateDistributionMap(lowerBoundary, bin, observationFrequency); + + }); + + return distributionMap; + } + + private void updateDistributionMap(int lowerBoundary, String bin, long observationFrequency) { + + int prevLowerBoundary = (lowerBoundary > classWidth) ? lowerBoundary - classWidth : 0; + String prevBin = prevLowerBoundary + "-" + lowerBoundary; + if(!distributionMap.containsKey(prevBin)) + distributionMap.put(prevBin, 0); + + if(!distributionMap.containsKey(bin)) { + distributionMap.put(bin, observationFrequency); + } + else { + long oldFrequency = Long.parseLong(distributionMap.get(bin).toString()); + distributionMap.replace(bin, oldFrequency + observationFrequency); + } + } + + public static void main(String[] args) { + new Histogram(); + } + +} diff --git a/libraries/src/main/java/com/baeldung/ftp/FtpClient.java b/libraries/src/main/java/com/baeldung/ftp/FtpClient.java new file mode 100644 index 0000000000..209bed35f0 --- /dev/null +++ b/libraries/src/main/java/com/baeldung/ftp/FtpClient.java @@ -0,0 +1,63 @@ +package com.baeldung.ftp; + +import org.apache.commons.net.PrintCommandListener; +import org.apache.commons.net.ftp.FTPClient; +import org.apache.commons.net.ftp.FTPFile; +import org.apache.commons.net.ftp.FTPReply; + +import java.io.*; +import java.util.Arrays; +import java.util.Collection; +import java.util.stream.Collectors; + +class FtpClient { + + private final String server; + private final int port; + private final String user; + private final String password; + private FTPClient ftp; + + FtpClient(String server, int port, String user, String password) { + this.server = server; + this.port = port; + this.user = user; + this.password = password; + } + + void open() throws IOException { + ftp = new FTPClient(); + + ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); + + ftp.connect(server, port); + int reply = ftp.getReplyCode(); + if (!FTPReply.isPositiveCompletion(reply)) { + ftp.disconnect(); + throw new IOException("Exception in connecting to FTP Server"); + } + + ftp.login(user, password); + } + + void close() throws IOException { + ftp.disconnect(); + } + + Collection listFiles(String path) throws IOException { + FTPFile[] files = ftp.listFiles(path); + + return Arrays.stream(files) + .map(FTPFile::getName) + .collect(Collectors.toList()); + } + + void putFileToPath(File file, String path) throws IOException { + ftp.storeFile(path, new FileInputStream(file)); + } + + void downloadFile(String source, String destination) throws IOException { + FileOutputStream out = new FileOutputStream(destination); + ftp.retrieveFile(source, out); + } +} diff --git a/libraries/src/main/java/com/baeldung/javalin/User/UserController.java b/libraries/src/main/java/com/baeldung/javalin/User/UserController.java index fd713606cf..685890c6d7 100644 --- a/libraries/src/main/java/com/baeldung/javalin/User/UserController.java +++ b/libraries/src/main/java/com/baeldung/javalin/User/UserController.java @@ -14,7 +14,7 @@ public class UserController { public static Handler fetchById = ctx -> { int id = Integer.parseInt(Objects.requireNonNull(ctx.param("id"))); UserDao dao = UserDao.instance(); - User user = dao.getUserById(id); + User user = dao.getUserById(id).get(); if (user == null) { ctx.html("Not Found"); } else { diff --git a/libraries/src/main/java/com/baeldung/javapoet/PersonGenerator.java b/libraries/src/main/java/com/baeldung/javapoet/PersonGenerator.java new file mode 100644 index 0000000000..6dd41cc0bd --- /dev/null +++ b/libraries/src/main/java/com/baeldung/javapoet/PersonGenerator.java @@ -0,0 +1,183 @@ +package com.baeldung.javapoet; + +import com.squareup.javapoet.ClassName; +import com.squareup.javapoet.CodeBlock; +import com.squareup.javapoet.FieldSpec; +import com.squareup.javapoet.JavaFile; +import com.squareup.javapoet.MethodSpec; +import com.squareup.javapoet.ParameterSpec; +import com.squareup.javapoet.ParameterizedTypeName; +import com.squareup.javapoet.TypeName; +import com.squareup.javapoet.TypeSpec; + +import javax.lang.model.element.Modifier; +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.stream.IntStream; + +public class PersonGenerator { + + private static final String FOUR_WHITESPACES = " "; + private static final String PERSON_PACKAGE_NAME = "com.baeldung.javapoet.test.person"; + + private File outputFile; + + public PersonGenerator() { + outputFile = new File(getOutputPath().toUri()); + } + + public static String getPersonPackageName() { + return PERSON_PACKAGE_NAME; + } + + public Path getOutputPath() { + return Paths.get(new File(".").getAbsolutePath() + "/gensrc"); + } + + public FieldSpec getDefaultNameField() { + return FieldSpec + .builder(String.class, "DEFAULT_NAME") + .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL) + .initializer("$S", "Alice") + .build(); + } + + public MethodSpec getSortByLengthMethod() { + return MethodSpec + .methodBuilder("sortByLength") + .addModifiers(Modifier.PUBLIC, Modifier.STATIC) + .addParameter(ParameterSpec + .builder(ParameterizedTypeName.get(ClassName.get(List.class), TypeName.get(String.class)), "strings") + .build()) + .addStatement("$T.sort($N, $L)", Collections.class, "strings", getComparatorAnonymousClass()) + .build(); + } + + public MethodSpec getPrintNameMultipleTimesMethod() { + return MethodSpec + .methodBuilder("printNameMultipleTimes") + .addModifiers(Modifier.PUBLIC) + .addCode(getPrintNameMultipleTimesLambdaImpl()) + .build(); + } + + public CodeBlock getPrintNameMultipleTimesImpl() { + return CodeBlock + .builder() + .beginControlFlow("for (int i = $L; i < $L; i++)") + .addStatement("System.out.println(name)") + .endControlFlow() + .build(); + } + + public CodeBlock getPrintNameMultipleTimesLambdaImpl() { + return CodeBlock + .builder() + .addStatement("$T<$T> names = new $T<>()", List.class, String.class, ArrayList.class) + .addStatement("$T.range($L, $L).forEach(i -> names.add(name))", IntStream.class, 0, 10) + .addStatement("names.forEach(System.out::println)") + .build(); + } + + public TypeSpec getGenderEnum() { + return TypeSpec + .enumBuilder("Gender") + .addModifiers(Modifier.PUBLIC) + .addEnumConstant("MALE") + .addEnumConstant("FEMALE") + .addEnumConstant("UNSPECIFIED") + .build(); + } + + public TypeSpec getPersonInterface() { + return TypeSpec + .interfaceBuilder("Person") + .addModifiers(Modifier.PUBLIC) + .addField(getDefaultNameField()) + .addMethod(MethodSpec + .methodBuilder("getName") + .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) + .returns(String.class) + .build()) + .addMethod(MethodSpec + .methodBuilder("getDefaultName") + .addModifiers(Modifier.PUBLIC, Modifier.DEFAULT) + .returns(String.class) + .addCode(CodeBlock + .builder() + .addStatement("return DEFAULT_NAME") + .build()) + .build()) + .build(); + } + + public TypeSpec getStudentClass() { + return TypeSpec + .classBuilder("Student") + .addSuperinterface(ClassName.get(PERSON_PACKAGE_NAME, "Person")) + .addModifiers(Modifier.PUBLIC) + .addField(FieldSpec + .builder(String.class, "name") + .addModifiers(Modifier.PRIVATE) + .build()) + .addMethod(MethodSpec + .methodBuilder("getName") + .addAnnotation(Override.class) + .addModifiers(Modifier.PUBLIC) + .returns(String.class) + .addStatement("return this.name") + .build()) + .addMethod(MethodSpec + .methodBuilder("setName") + .addParameter(String.class, "name") + .addModifiers(Modifier.PUBLIC) + .addStatement("this.name = name") + .build()) + .addMethod(getPrintNameMultipleTimesMethod()) + .addMethod(getSortByLengthMethod()) + .build(); + } + + public TypeSpec getComparatorAnonymousClass() { + return TypeSpec + .anonymousClassBuilder("") + .addSuperinterface(ParameterizedTypeName.get(Comparator.class, String.class)) + .addMethod(MethodSpec + .methodBuilder("compare") + .addModifiers(Modifier.PUBLIC) + .addAnnotation(Override.class) + .addParameter(String.class, "a") + .addParameter(String.class, "b") + .returns(int.class) + .addStatement("return a.length() - b.length()") + .build()) + .build(); + } + + public void generateGenderEnum() throws IOException { + writeToOutputFile(getPersonPackageName(), getGenderEnum()); + } + + public void generatePersonInterface() throws IOException { + writeToOutputFile(getPersonPackageName(), getPersonInterface()); + } + + public void generateStudentClass() throws IOException { + writeToOutputFile(getPersonPackageName(), getStudentClass()); + } + + private void writeToOutputFile(String packageName, TypeSpec typeSpec) throws IOException { + JavaFile javaFile = JavaFile + .builder(packageName, typeSpec) + .indent(FOUR_WHITESPACES) + .build(); + javaFile.writeTo(outputFile); + } + +} diff --git a/libraries/src/test/java/com/baeldung/date/StringToDateUnitTest.java b/libraries/src/test/java/com/baeldung/date/StringToDateUnitTest.java new file mode 100644 index 0000000000..e07422a9c6 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/date/StringToDateUnitTest.java @@ -0,0 +1,141 @@ +package com.baeldung.date; + +import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Locale; + +import org.apache.commons.lang3.time.DateUtils; +import org.joda.time.DateTime; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +public class StringToDateUnitTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetCorrectLocalDate() { + LocalDate expectedLocalDate = LocalDate.of(2018, 05, 05); + + LocalDate date = LocalDate.parse("2018-05-05"); + + assertThat(date).isEqualTo(expectedLocalDate); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetCorrectLocalDateTime() { + LocalDateTime expectedLocalDateTime = LocalDateTime.of(2018, 05, 05, 11, 50, 55); + + LocalDateTime dateTime = LocalDateTime.parse("2018-05-05T11:50:55"); + + assertThat(dateTime).isEqualTo(expectedLocalDateTime); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetDateTimeParseException() { + thrown.expect(DateTimeParseException.class); + thrown.expectMessage("Text '2018-05-05' could not be parsed at index 10"); + + LocalDateTime.parse("2018-05-05"); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetCorrectZonedDateTime() { + LocalDateTime localDateTime = LocalDateTime.of(2015, 05, 05, 10, 15, 30); + ZonedDateTime expectedZonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("Europe/Paris")); + + ZonedDateTime zonedDateTime = ZonedDateTime.parse("2015-05-05T10:15:30+01:00[Europe/Paris]"); + + assertThat(zonedDateTime).isEqualTo(expectedZonedDateTime); + } + + @Test + public void givenDateString_whenConvertedToDateUsingFormatter_thenWeGetCorrectLocalDate() { + LocalDate expectedLocalDate = LocalDate.of(1959, 7, 9); + + String dateInString = "19590709"; + LocalDate date = LocalDate.parse(dateInString, DateTimeFormatter.BASIC_ISO_DATE); + + assertThat(date).isEqualTo(expectedLocalDate); + } + + @Test + public void givenDateString_whenConvertedToDateUsingCustomFormatter_thenWeGetCorrectLocalDate() { + LocalDate expectedLocalDate = LocalDate.of(1980, 05, 05); + + String dateInString = "Mon, 05 May 1980"; + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, d MMM yyyy", Locale.ENGLISH); + LocalDate dateTime = LocalDate.parse(dateInString, formatter); + + assertThat(dateTime).isEqualTo(expectedLocalDate); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetCorrectDate() throws ParseException { + SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH); + + String dateInString = "7-Jun-2013"; + Date date = formatter.parse(dateInString); + + assertDateIsCorrect(date); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetParseException() throws ParseException { + SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH); + + thrown.expect(ParseException.class); + thrown.expectMessage("Unparseable date: \"07/06/2013\""); + + String dateInString = "07/06/2013"; + formatter.parse(dateInString); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetCorrectJodaDateTime() { + org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss"); + + String dateInString = "07/06/2013 10:11:59"; + DateTime dateTime = DateTime.parse(dateInString, formatter); + + assertEquals("Day of Month should be 7: ", 7, dateTime.getDayOfMonth()); + assertEquals("Month should be: ", 6, dateTime.getMonthOfYear()); + assertEquals("Year should be: ", 2013, dateTime.getYear()); + + assertEquals("Hour of day should be: ", 10, dateTime.getHourOfDay()); + assertEquals("Minutes of hour should be: ", 11, dateTime.getMinuteOfHour()); + assertEquals("Seconds of minute should be: ", 59, dateTime.getSecondOfMinute()); + } + + @Test + public void givenDateString_whenConvertedToDate_thenWeGetCorrectDateTime() throws ParseException { + String dateInString = "07/06-2013"; + Date date = DateUtils.parseDate(dateInString, new String[] { "yyyy-MM-dd HH:mm:ss", "dd/MM-yyyy" }); + + assertDateIsCorrect(date); + } + + private void assertDateIsCorrect(Date date) { + Calendar calendar = new GregorianCalendar(Locale.ENGLISH); + calendar.setTime(date); + + assertEquals("Day of Month should be 7: ", 7, calendar.get(Calendar.DAY_OF_MONTH)); + assertEquals("Month should be: ", 5, calendar.get(Calendar.MONTH)); + assertEquals("Year should be: ", 2013, calendar.get(Calendar.YEAR)); + } + +} diff --git a/libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java b/libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java new file mode 100644 index 0000000000..43da69f96d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java @@ -0,0 +1,73 @@ +package com.baeldung.ftp; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockftpserver.fake.FakeFtpServer; +import org.mockftpserver.fake.UserAccount; +import org.mockftpserver.fake.filesystem.DirectoryEntry; +import org.mockftpserver.fake.filesystem.FileEntry; +import org.mockftpserver.fake.filesystem.FileSystem; +import org.mockftpserver.fake.filesystem.UnixFakeFileSystem; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.Collection; + +import static org.assertj.core.api.Assertions.assertThat; + +public class FtpClientIntegrationTest { + + private FakeFtpServer fakeFtpServer; + + private FtpClient ftpClient; + + @Before + public void setup() throws IOException { + fakeFtpServer = new FakeFtpServer(); + fakeFtpServer.addUserAccount(new UserAccount("user", "password", "/data")); + + FileSystem fileSystem = new UnixFakeFileSystem(); + fileSystem.add(new DirectoryEntry("/data")); + fileSystem.add(new FileEntry("/data/foobar.txt", "abcdef 1234567890")); + fakeFtpServer.setFileSystem(fileSystem); + fakeFtpServer.setServerControlPort(0); + + fakeFtpServer.start(); + + ftpClient = new FtpClient("localhost", fakeFtpServer.getServerControlPort(), "user", "password"); + ftpClient.open(); + } + + @After + public void teardown() throws IOException { + ftpClient.close(); + fakeFtpServer.stop(); + } + + @Test + public void givenRemoteFile_whenListingRemoteFiles_thenItIsContainedInList() throws IOException { + Collection files = ftpClient.listFiles(""); + + assertThat(files).contains("foobar.txt"); + } + + @Test + public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException { + ftpClient.downloadFile("/foobar.txt", "downloaded_buz.txt"); + + assertThat(new File("downloaded_buz.txt")).exists(); + new File("downloaded_buz.txt").delete(); // cleanup + } + + @Test + public void givenLocalFile_whenUploadingIt_thenItExistsOnRemoteLocation() throws URISyntaxException, IOException { + File file = new File(getClass().getClassLoader().getResource("ftp/baz.txt").toURI()); + + ftpClient.putFileToPath(file, "/buz.txt"); + + assertThat(fakeFtpServer.getFileSystem().exists("/buz.txt")).isTrue(); + } + +} diff --git a/libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java b/libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java new file mode 100644 index 0000000000..ef6809b02d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java @@ -0,0 +1,63 @@ +package com.baeldung.ftp; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockftpserver.fake.FakeFtpServer; +import org.mockftpserver.fake.UserAccount; +import org.mockftpserver.fake.filesystem.DirectoryEntry; +import org.mockftpserver.fake.filesystem.FileEntry; +import org.mockftpserver.fake.filesystem.FileSystem; +import org.mockftpserver.fake.filesystem.UnixFakeFileSystem; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; +import java.nio.file.Files; +import java.util.Collection; + +import static org.assertj.core.api.Assertions.assertThat; + +public class JdkFtpClientIntegrationTest { + + private FakeFtpServer fakeFtpServer; + + + @Before + public void setup() throws IOException { + fakeFtpServer = new FakeFtpServer(); + fakeFtpServer.addUserAccount(new UserAccount("user", "password", "/data")); + + FileSystem fileSystem = new UnixFakeFileSystem(); + fileSystem.add(new DirectoryEntry("/data")); + fileSystem.add(new FileEntry("/data/foobar.txt", "abcdef 1234567890")); + fakeFtpServer.setFileSystem(fileSystem); + fakeFtpServer.setServerControlPort(0); + + fakeFtpServer.start(); + } + + @After + public void teardown() throws IOException { + fakeFtpServer.stop(); + } + + @Test + public void givenRemoteFile_whenDownloading_thenItIsOnTheLocalFilesystem() throws IOException { + String ftpUrl = String.format("ftp://user:password@localhost:%d/foobar.txt", fakeFtpServer.getServerControlPort()); + + URLConnection urlConnection = new URL(ftpUrl).openConnection(); + InputStream inputStream = urlConnection.getInputStream(); + Files.copy(inputStream, new File("downloaded_buz.txt").toPath()); + inputStream.close(); + + assertThat(new File("downloaded_buz.txt")).exists(); + + new File("downloaded_buz.txt").delete(); // cleanup + } + +} diff --git a/libraries/src/test/java/com/baeldung/javapoet/test/PersonGeneratorUnitTest.java b/libraries/src/test/java/com/baeldung/javapoet/test/PersonGeneratorUnitTest.java new file mode 100644 index 0000000000..61bf3ebc33 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/javapoet/test/PersonGeneratorUnitTest.java @@ -0,0 +1,99 @@ +package com.baeldung.javapoet.test; + +import com.baeldung.javapoet.PersonGenerator; +import org.apache.commons.io.FileUtils; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +@RunWith(JUnit4.class) +public class PersonGeneratorUnitTest { + + private PersonGenerator generator; + private Path generatedFolderPath; + private Path expectedFolderPath; + + @Before + public void setUp() { + String packagePath = this + .getClass() + .getPackage() + .getName() + .replace(".", "/") + "/person"; + generator = new PersonGenerator(); + generatedFolderPath = generator + .getOutputPath() + .resolve(packagePath); + expectedFolderPath = Paths.get(new File(".").getAbsolutePath() + "/src/test/java/" + packagePath); + } + + @After + public void tearDown() throws Exception { + FileUtils.deleteDirectory(new File(generator + .getOutputPath() + .toUri())); + } + + @Test + public void whenGenerateGenderEnum_thenGenerateGenderEnumAndWriteToFile() throws IOException { + generator.generateGenderEnum(); + String fileName = "Gender.java"; + assertThatFileIsGeneratedAsExpected(fileName); + deleteGeneratedFile(fileName); + } + + @Test + public void whenGeneratePersonInterface_thenGeneratePersonInterfaceAndWriteToFile() throws IOException { + generator.generatePersonInterface(); + String fileName = "Person.java"; + assertThatFileIsGeneratedAsExpected(fileName); + deleteGeneratedFile(fileName); + } + + @Test + public void whenGenerateStudentClass_thenGenerateStudentClassAndWriteToFile() throws IOException { + generator.generateStudentClass(); + String fileName = "Student.java"; + assertThatFileIsGeneratedAsExpected(fileName); + deleteGeneratedFile(fileName); + } + + private void assertThatFileIsGeneratedAsExpected(String fileName) throws IOException { + String generatedFileContent = extractFileContent(generatedFolderPath.resolve(fileName)); + String expectedFileContent = extractFileContent(expectedFolderPath.resolve(fileName)); + + assertThat("Generated file is identical to the file with the expected content", generatedFileContent, is(equalTo(expectedFileContent))); + + } + + private void deleteGeneratedFile(String fileName) throws IOException { + Path generatedFilePath = generatedFolderPath.resolve(fileName); + Files.delete(generatedFilePath); + } + + private String extractFileContent(Path filePath) throws IOException { + byte[] fileContentAsBytes = Files.readAllBytes(filePath); + String fileContentAsString = new String(fileContentAsBytes, StandardCharsets.UTF_8); + + if (!fileContentAsString.contains("\r\n")) { + // file is not in DOS format + // convert it first, so that the content comparison will be relevant + return fileContentAsString.replaceAll("\n", "\r\n"); + } + return fileContentAsString; + } + +} diff --git a/libraries/src/test/java/com/baeldung/javapoet/test/person/Gender.java b/libraries/src/test/java/com/baeldung/javapoet/test/person/Gender.java new file mode 100644 index 0000000000..3c5657fb9d --- /dev/null +++ b/libraries/src/test/java/com/baeldung/javapoet/test/person/Gender.java @@ -0,0 +1,9 @@ +package com.baeldung.javapoet.test.person; + +public enum Gender { + MALE, + + FEMALE, + + UNSPECIFIED +} diff --git a/libraries/src/test/java/com/baeldung/javapoet/test/person/Person.java b/libraries/src/test/java/com/baeldung/javapoet/test/person/Person.java new file mode 100644 index 0000000000..fae8b23075 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/javapoet/test/person/Person.java @@ -0,0 +1,13 @@ +package com.baeldung.javapoet.test.person; + +import java.lang.String; + +public interface Person { + String DEFAULT_NAME = "Alice"; + + String getName(); + + default String getDefaultName() { + return DEFAULT_NAME; + } +} diff --git a/libraries/src/test/java/com/baeldung/javapoet/test/person/Student.java b/libraries/src/test/java/com/baeldung/javapoet/test/person/Student.java new file mode 100644 index 0000000000..1c7d5cc096 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/javapoet/test/person/Student.java @@ -0,0 +1,37 @@ +package com.baeldung.javapoet.test.person; + +import java.lang.Override; +import java.lang.String; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.stream.IntStream; + +public class Student implements Person { + private String name; + + @Override + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public void printNameMultipleTimes() { + List names = new ArrayList<>(); + IntStream.range(0, 10).forEach(i -> names.add(name)); + names.forEach(System.out::println); + } + + public static void sortByLength(List strings) { + Collections.sort(strings, new Comparator() { + @Override + public int compare(String a, String b) { + return a.length() - b.length(); + } + }); + } +} diff --git a/libraries/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java b/libraries/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java new file mode 100644 index 0000000000..3cf4f739e8 --- /dev/null +++ b/libraries/src/test/java/com/baeldung/jodatime/JodaTimeUnitTest.java @@ -0,0 +1,190 @@ +package com.baeldung.jodatime; + +import org.joda.time.*; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.DateTimeFormatter; +import org.junit.Test; + +import java.util.Date; +import java.util.TimeZone; + +import static org.junit.Assert.*; + +public class JodaTimeUnitTest { + + @Test + public void testDateTimeRepresentation() { + + DateTimeZone.setDefault(DateTimeZone.forID("Europe/Bucharest")); + + // representing current date and time + LocalDate currentDate = LocalDate.now(); + LocalTime currentTime = LocalTime.now(); + LocalDateTime currentLocalDateTime = LocalDateTime.now(); + + LocalDateTime currentDateTimeFromJavaDate = new LocalDateTime(new Date()); + Date currentJavaDate = currentDateTimeFromJavaDate.toDate(); + + // representing custom date and time + Date oneMinuteAgoDate = new Date(System.currentTimeMillis() - (60 * 1000)); + Instant oneMinutesAgoInstant = new Instant(oneMinuteAgoDate); + + DateTime customDateTimeFromInstant = new DateTime(oneMinutesAgoInstant); + DateTime customDateTimeFromJavaDate = new DateTime(oneMinuteAgoDate); + DateTime customDateTimeFromString = new DateTime("2018-05-05T10:11:12.123"); + DateTime customDateTimeFromParts = new DateTime(2018, 5, 5, 10, 11, 12, 123); + + // parsing + DateTime parsedDateTime = DateTime.parse("2018-05-05T10:11:12.123"); + assertEquals("2018-05-05T10:11:12.123+03:00", parsedDateTime.toString()); + + DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss"); + DateTime parsedDateTimeUsingFormatter = DateTime.parse("05/05/2018 10:11:12", dateTimeFormatter); + assertEquals("2018-05-05T10:11:12.000+03:00", parsedDateTimeUsingFormatter.toString()); + + // Instant + Instant instant = new Instant(); + Instant.now(); + + Instant instantFromString = new Instant("2018-05-05T10:11:12"); + Instant instantFromDate = new Instant(oneMinuteAgoDate); + Instant instantFromTimestamp = new Instant(System.currentTimeMillis() - (60 * 1000)); + Instant parsedInstant = Instant.parse("05/05/2018 10:11:12", dateTimeFormatter); + + Instant instantNow = Instant.now(); + Instant oneMinuteAgoInstant = new Instant(oneMinuteAgoDate); + + // epochMilli and epochSecond + long milliesFromEpochTime = System.currentTimeMillis(); + long secondsFromEpochTime = milliesFromEpochTime / 1000; + Instant instantFromEpochMilli = Instant.ofEpochMilli(milliesFromEpochTime); + Instant instantFromEpocSeconds = Instant.ofEpochSecond(secondsFromEpochTime); + + // convert Instants + DateTime dateTimeFromInstant = instant.toDateTime(); + Date javaDateFromInstant = instant.toDate(); + + int year = instant.get(DateTimeFieldType.year()); + int month = instant.get(DateTimeFieldType.monthOfYear()); + int day = instant.get(DateTimeFieldType.dayOfMonth()); + int hour = instant.get(DateTimeFieldType.hourOfDay()); + + // Duration, Period, Instant + long currentTimestamp = System.currentTimeMillis(); + long oneHourAgo = currentTimestamp - 24*60*1000; + + Duration duration = new Duration(oneHourAgo, currentTimestamp); + Instant.now().plus(duration); + + long durationInDays = duration.getStandardDays(); + long durationInHours = duration.getStandardHours(); + long durationInMinutes = duration.getStandardMinutes(); + long durationInSeconds = duration.getStandardSeconds(); + long durationInMilli = duration.getMillis(); + + // converting between classes + DateTimeUtils.setCurrentMillisFixed(currentTimestamp); + LocalDateTime currentDateAndTime = LocalDateTime.now(); + + assertEquals(currentTimestamp, currentDateAndTime.toDate().getTime()); + assertEquals(new DateTime(currentTimestamp), currentDateAndTime.toDateTime()); + assertEquals(new LocalDate(currentTimestamp), currentDateAndTime.toLocalDate()); + assertEquals(new LocalTime(currentTimestamp), currentDateAndTime.toLocalTime()); + } + + @Test + public void testJodaInstant() { + + Date oneMinuteAgoDate = new Date(System.currentTimeMillis() - (60 * 1000)); + + Instant instantNow = Instant.now(); + Instant oneMinuteAgoInstant = new Instant(oneMinuteAgoDate); + + assertTrue(instantNow.compareTo(oneMinuteAgoInstant) > 0); + assertTrue(instantNow.isAfter(oneMinuteAgoInstant)); + assertTrue(oneMinuteAgoInstant.isBefore(instantNow)); + assertTrue(oneMinuteAgoInstant.isBeforeNow()); + assertFalse(oneMinuteAgoInstant.isEqual(instantNow)); + + LocalDateTime localDateTime = new LocalDateTime("2018-02-01"); + Period period = new Period().withMonths(1); + LocalDateTime datePlusPeriod = localDateTime.plus(period); + + Instant startInterval1 = new Instant("2018-05-05T09:00:00.000"); + Instant endInterval1 = new Instant("2018-05-05T11:00:00.000"); + Interval interval1 = new Interval(startInterval1, endInterval1); + + Instant startInterval2 = new Instant("2018-05-05T10:00:00.000"); + Instant endInterval2 = new Instant("2018-05-05T11:00:00.000"); + Interval interval2 = new Interval(startInterval2, endInterval2); + + Instant startInterval3 = new Instant("2018-05-05T11:00:00.000"); + Instant endInterval3 = new Instant("2018-05-05T13:00:00.000"); + Interval interval3 = new Interval(startInterval3, endInterval3); + + Interval overlappingInterval = interval1.overlap(interval2); + Interval notOverlappingInterval = interval1.overlap(interval3); + + assertTrue(overlappingInterval.isEqual(new Interval(new Instant("2018-05-05T10:00:00.000"), new Instant("2018-05-05T11:00:00.000")))); + assertNotNull(overlappingInterval); + + interval1.abuts(interval3); + assertTrue(interval1.abuts(new Interval(new Instant("2018-05-05T11:00:00.000"), new Instant("2018-05-05T13:00:00.000")))); + + interval1.gap(interval2); + } + + + @Test + public void testDateTimeOperations() { + + DateTimeUtils.setCurrentMillisFixed(1529612783288L); + DateTimeZone.setDefault(DateTimeZone.UTC); + + LocalDateTime currentLocalDateTime = LocalDateTime.now(); + assertEquals("2018-06-21T20:26:23.288", currentLocalDateTime.toString()); + + LocalDateTime nextDayDateTime = currentLocalDateTime.plusDays(1); + assertEquals("2018-06-22T20:26:23.288", nextDayDateTime.toString()); + + Period oneMonth = new Period().withMonths(1); + LocalDateTime nextMonthDateTime = currentLocalDateTime.plus(oneMonth); + assertEquals("2018-07-21T20:26:23.288", nextMonthDateTime.toString()); + + LocalDateTime previousDayLocalDateTime = currentLocalDateTime.minusDays(1); + assertEquals("2018-06-20T20:26:23.288", previousDayLocalDateTime.toString()); + + LocalDateTime currentDateAtHour10 = currentLocalDateTime + .withHourOfDay(0) + .withMinuteOfHour(0) + .withSecondOfMinute(0) + .withMillisOfSecond(0); + assertEquals("2018-06-21T00:00:00.000", currentDateAtHour10.toString()); + } + + @Test + public void testTimezones() { + + System.getProperty("user.timezone"); + DateTimeZone.getAvailableIDs(); + // DateTimeZone.setDefault(DateTimeZone.forID("Europe/Bucharest")); + + DateTimeUtils.setCurrentMillisFixed(1529612783288L); + + DateTime dateTimeInChicago = new DateTime(DateTimeZone.forID("America/Chicago")); + assertEquals("2018-06-21T15:26:23.288-05:00", dateTimeInChicago.toString()); + + DateTime dateTimeInBucharest = new DateTime(DateTimeZone.forID("Europe/Bucharest")); + assertEquals("2018-06-21T23:26:23.288+03:00", dateTimeInBucharest.toString()); + + LocalDateTime localDateTimeInChicago = new LocalDateTime(DateTimeZone.forID("America/Chicago")); + assertEquals("2018-06-21T15:26:23.288", localDateTimeInChicago.toString()); + + DateTime convertedDateTime = localDateTimeInChicago.toDateTime(DateTimeZone.forID("Europe/Bucharest")); + assertEquals("2018-06-21T15:26:23.288+03:00", convertedDateTime.toString()); + + Date convertedDate = localDateTimeInChicago.toDate(TimeZone.getTimeZone("Europe/Bucharest")); + assertEquals("Thu Jun 21 15:26:23 EEST 2018", convertedDate.toString()); + } + +} diff --git a/libraries/src/test/resources/ftp/baz.txt b/libraries/src/test/resources/ftp/baz.txt new file mode 100644 index 0000000000..e69de29bb2 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-programmatic-configuration/modify-xml-configuration/pom.xml b/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/pom.xml deleted file mode 100644 index 74464a9631..0000000000 --- a/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/pom.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - 4.0.0 - - com.baeldung.log4j2 - log4j2-programmatic-configuration - 0.0.1-SNAPSHOT - - com.baeldung.log4j2 - modify-xml-configuration - 0.0.1-SNAPSHOT - modify-xml-configuration - http://maven.apache.org - - UTF-8 - - diff --git a/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/main/java/com/baeldung/log4j2/config/CustomXMLConfigurationFactory.java b/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/main/java/com/baeldung/log4j2/config/CustomXMLConfigurationFactory.java deleted file mode 100644 index e92c66f168..0000000000 --- a/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/main/java/com/baeldung/log4j2/config/CustomXMLConfigurationFactory.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - This class demonstrates on modifying the loaded xml configuration by - extending XMLConfigurationFactory as defined in section 4.4 of - "Programmatic Configuration with Log4j 2" -**/ -package com.baeldung.log4j2.config; - -import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.config.Configuration; -import org.apache.logging.log4j.core.config.ConfigurationFactory; -import org.apache.logging.log4j.core.config.ConfigurationSource; -import org.apache.logging.log4j.core.config.Order; -import org.apache.logging.log4j.core.config.plugins.Plugin; -import org.apache.logging.log4j.core.config.xml.XmlConfigurationFactory; - -@Plugin(name = "CustomConfigurationFactory", category = ConfigurationFactory.CATEGORY) -@Order(50) -public class CustomXMLConfigurationFactory extends XmlConfigurationFactory { - - @Override - public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) { - return new MyXMLConfiguration(loggerContext, source); - } - - @Override - public String[] getSupportedTypes() { - return new String[] { ".xml", "*" }; - } -} diff --git a/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/main/java/com/baeldung/log4j2/config/MyXMLConfiguration.java b/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/main/java/com/baeldung/log4j2/config/MyXMLConfiguration.java deleted file mode 100644 index 45ee421316..0000000000 --- a/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/main/java/com/baeldung/log4j2/config/MyXMLConfiguration.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - This class demonstrates on overriding the configuration loaded through xml - as defined in section 4.4 of "Programmatic Configuration with Log4j 2" -**/ -package com.baeldung.log4j2.config; - -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.core.Appender; -import org.apache.logging.log4j.core.Layout; -import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.appender.FileAppender; -import org.apache.logging.log4j.core.config.Configuration; -import org.apache.logging.log4j.core.config.ConfigurationSource; -import org.apache.logging.log4j.core.config.LoggerConfig; -import org.apache.logging.log4j.core.config.xml.XmlConfiguration; -import org.apache.logging.log4j.core.layout.PatternLayout; - -public class MyXMLConfiguration extends XmlConfiguration { - public MyXMLConfiguration(LoggerContext loggerContext, ConfigurationSource source) { - super(loggerContext, source); - } - - @Override - protected void doConfigure() { - super.doConfigure(); - final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); - Configuration config = ctx.getConfiguration(); - LoggerConfig loggerConfig = config.getLoggerConfig("com"); - final Layout layout = PatternLayout.createLayout("[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n", null, config, null, null, false, false, null, null); - Appender appender = FileAppender.createAppender("target/test.log", "false", "false", "File", "true", "false", "false", "4000", layout, null, "false", null, config); - loggerConfig.addAppender(appender, Level.DEBUG, null); - addAppender(appender); - } -} diff --git a/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/main/resources/log4j2.xml b/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/main/resources/log4j2.xml deleted file mode 100644 index 36823c8122..0000000000 --- a/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/main/resources/log4j2.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/test/java/com/baeldung/log4j2/logtest/LogTest.java b/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/test/java/com/baeldung/log4j2/logtest/LogTest.java deleted file mode 100644 index 993c0d0648..0000000000 --- a/logging-modules/log4j2-programmatic-configuration/modify-xml-configuration/src/test/java/com/baeldung/log4j2/logtest/LogTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.log4j2.logtest; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.config.plugins.util.PluginManager; -import org.junit.Test; - - -public class LogTest { - static{ - PluginManager.addPackage("com.baeldung.log4j2.config"); - } - - @Test - public void simpleProgrammaticConfiguration() { - Logger logger = LogManager.getLogger(); - LoggerContext ctx = (LoggerContext) LogManager.getContext(); - logger.debug("Debug log message"); - logger.info("Info log message"); - logger.error("Error log message"); - } -} diff --git a/logging-modules/log4j2-programmatic-configuration/pom.xml b/logging-modules/log4j2-programmatic-configuration/pom.xml deleted file mode 100644 index cd3aced397..0000000000 --- a/logging-modules/log4j2-programmatic-configuration/pom.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - 4.0.0 - com.baeldung.log4j2 - log4j2-programmatic-configuration - 0.0.1-SNAPSHOT - pom - - simple-configuration - set-configuration-factory - simple-configurator - simple-configuration-xml - modify-xml-configuration - - - - junit - junit - 4.12 - test - - - org.apache.logging.log4j - log4j-core - 2.11.0 - - - org.apache.logging.log4j - log4j-slf4j-impl - 2.11.0 - - - diff --git a/logging-modules/log4j2-programmatic-configuration/set-configuration-factory/pom.xml b/logging-modules/log4j2-programmatic-configuration/set-configuration-factory/pom.xml deleted file mode 100644 index f2a72563e9..0000000000 --- a/logging-modules/log4j2-programmatic-configuration/set-configuration-factory/pom.xml +++ /dev/null @@ -1,10 +0,0 @@ - - 4.0.0 - - com.baeldung.log4j2 - log4j2-programmatic-configuration - 0.0.1-SNAPSHOT - - set-configuration-factory - \ No newline at end of file diff --git a/logging-modules/log4j2-programmatic-configuration/set-configuration-factory/src/main/java/com/baeldung/log4j2/config/CustomConfigurationFactory.java b/logging-modules/log4j2-programmatic-configuration/set-configuration-factory/src/main/java/com/baeldung/log4j2/config/CustomConfigurationFactory.java deleted file mode 100644 index 9c48702ba0..0000000000 --- a/logging-modules/log4j2-programmatic-configuration/set-configuration-factory/src/main/java/com/baeldung/log4j2/config/CustomConfigurationFactory.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - This class demonstrates how to build the components of - the configuration factory, as described in Section 3 of - "Programmatic Configuration with Log4j 2" -**/ -package com.baeldung.log4j2.config; - -import java.io.IOException; -import java.net.URI; - -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.core.Filter; -import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.config.Configuration; -import org.apache.logging.log4j.core.config.ConfigurationFactory; -import org.apache.logging.log4j.core.config.ConfigurationSource; -import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder; -import org.apache.logging.log4j.core.config.builder.api.ComponentBuilder; -import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder; -import org.apache.logging.log4j.core.config.builder.api.FilterComponentBuilder; -import org.apache.logging.log4j.core.config.builder.api.LayoutComponentBuilder; -import org.apache.logging.log4j.core.config.builder.api.LoggerComponentBuilder; -import org.apache.logging.log4j.core.config.builder.api.RootLoggerComponentBuilder; -import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration; - -public class CustomConfigurationFactory extends ConfigurationFactory { - - static Configuration createConfiguration(final String name, ConfigurationBuilder builder) { - AppenderComponentBuilder console = builder.newAppender("Stdout", "Console"); - LayoutComponentBuilder layout = builder.newLayout("PatternLayout") - .addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable"); - console.add(layout); - FilterComponentBuilder filter = builder.newFilter("MarkerFilter", Filter.Result.ACCEPT, Filter.Result.DENY); - filter.addAttribute("marker", "FLOW"); - console.add(filter); - builder.add(console); - ComponentBuilder triggeringPolicies = builder.newComponent("Policies") - .addComponent(builder.newComponent("CronTriggeringPolicy") - .addAttribute("schedule", "0 0 0 * * ?")) - .addComponent(builder.newComponent("SizeBasedTriggeringPolicy") - .addAttribute("size", "100M")); - AppenderComponentBuilder rollingFile = builder.newAppender("rolling", "RollingFile"); - rollingFile.addAttribute("fileName", "target/rolling.log"); - rollingFile.addAttribute("filePattern", "target/archive/rolling-%d{MM-dd-yy}.log.gz"); - rollingFile.add(layout); - rollingFile.addComponent(triggeringPolicies); - builder.add(rollingFile); - AppenderComponentBuilder file = builder.newAppender("FileSystem", "File"); - file.addAttribute("fileName", "target/logging.log"); - file.add(layout); - builder.add(file); - LoggerComponentBuilder logger = builder.newLogger("com", Level.DEBUG); - logger.add(builder.newAppenderRef("Stdout")); - logger.add(builder.newAppenderRef("rolling")); - logger.add(builder.newAppenderRef("FileSystem")); - logger.addAttribute("additivity", false); - builder.add(logger); - RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.ERROR); - rootLogger.add(builder.newAppenderRef("Stdout")); - rootLogger.add(builder.newAppenderRef("rolling")); - rootLogger.add(builder.newAppenderRef("FileSystem")); - rootLogger.addAttribute("additivity", false); - builder.add(rootLogger); - try { - builder.writeXmlConfiguration(System.out); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return builder.build(); - } - - public Configuration getConfiguration(final LoggerContext loggerContext, final String name, final URI configLocation) { - ConfigurationBuilder builder = newConfigurationBuilder(); - return createConfiguration(name, builder); - } - - @Override - protected String[] getSupportedTypes() { - return new String[] { "*" }; - } - - @Override - public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) { - return getConfiguration(loggerContext, source.toString(), null); - } - -} diff --git a/logging-modules/log4j2-programmatic-configuration/simple-configuration-xml/pom.xml b/logging-modules/log4j2-programmatic-configuration/simple-configuration-xml/pom.xml deleted file mode 100644 index de8c1ff70b..0000000000 --- a/logging-modules/log4j2-programmatic-configuration/simple-configuration-xml/pom.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - 4.0.0 - - com.baeldung.log4j2 - log4j2-programmatic-configuration - 0.0.1-SNAPSHOT - - simple-configuration-xml - simple-configuration-xml - http://maven.apache.org - - UTF-8 - - diff --git a/logging-modules/log4j2-programmatic-configuration/simple-configuration-xml/src/main/resources/log4j2.xml b/logging-modules/log4j2-programmatic-configuration/simple-configuration-xml/src/main/resources/log4j2.xml deleted file mode 100644 index 4c49d85471..0000000000 --- a/logging-modules/log4j2-programmatic-configuration/simple-configuration-xml/src/main/resources/log4j2.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/logging-modules/log4j2-programmatic-configuration/simple-configuration-xml/src/test/java/com/baeldung/log4j2/logtest/LogTest.java b/logging-modules/log4j2-programmatic-configuration/simple-configuration-xml/src/test/java/com/baeldung/log4j2/logtest/LogTest.java deleted file mode 100644 index f32e0796b6..0000000000 --- a/logging-modules/log4j2-programmatic-configuration/simple-configuration-xml/src/test/java/com/baeldung/log4j2/logtest/LogTest.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - This class loads the logging configuration from the xml defined in - src/main/resources and uses the same configuration generated through - programmatic configuration as defined in simple-configuration example. -**/ - -package com.baeldung.log4j2.logtest; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.Marker; -import org.apache.logging.log4j.MarkerManager; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - - -@RunWith(JUnit4.class) -public class LogTest { - - @Test - public void simpleProgrammaticConfiguration(){ - Logger logger = LogManager.getLogger(); - Marker markerContent = MarkerManager.getMarker("FLOW"); - logger.debug(markerContent, "Debug log message"); - logger.info(markerContent, "Info log message"); - logger.error(markerContent, "Error log message"); - } - -} diff --git a/logging-modules/log4j2-programmatic-configuration/simple-configuration/pom.xml b/logging-modules/log4j2-programmatic-configuration/simple-configuration/pom.xml deleted file mode 100644 index 0f9e5be3ff..0000000000 --- a/logging-modules/log4j2-programmatic-configuration/simple-configuration/pom.xml +++ /dev/null @@ -1,10 +0,0 @@ - - 4.0.0 - - com.baeldung.log4j2 - log4j2-programmatic-configuration - 0.0.1-SNAPSHOT - - simple-configuration - \ No newline at end of file diff --git a/logging-modules/log4j2-programmatic-configuration/simple-configuration/src/test/java/com/baeldung/log4j2/logtest/LogTest.java b/logging-modules/log4j2-programmatic-configuration/simple-configuration/src/test/java/com/baeldung/log4j2/logtest/LogTest.java deleted file mode 100644 index 5637a16508..0000000000 --- a/logging-modules/log4j2-programmatic-configuration/simple-configuration/src/test/java/com/baeldung/log4j2/logtest/LogTest.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - This class invokes the configuration factory through the run time property, - as defined in section 4.2 of the "Programmatic Configuration with Log4j 2" -**/ -package com.baeldung.log4j2.logtest; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.Marker; -import org.apache.logging.log4j.MarkerManager; -import org.junit.Test; - -public class LogTest { - @Test - public void simpleProgrammaticConfiguration() { - Logger logger = LogManager.getLogger(); - Marker markerContent = MarkerManager.getMarker("FLOW"); - logger.debug(markerContent, "Debug log message"); - logger.info(markerContent, "Info log message"); - logger.error(markerContent, "Error log message"); - } -} diff --git a/logging-modules/log4j2-programmatic-configuration/simple-configurator/pom.xml b/logging-modules/log4j2-programmatic-configuration/simple-configurator/pom.xml deleted file mode 100644 index 4e7350f785..0000000000 --- a/logging-modules/log4j2-programmatic-configuration/simple-configurator/pom.xml +++ /dev/null @@ -1,10 +0,0 @@ - - 4.0.0 - - com.baeldung.log4j2 - log4j2-programmatic-configuration - 0.0.1-SNAPSHOT - - simple-configurator - \ No newline at end of file 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/pom.xml b/logging-modules/log4j2/pom.xml index 651e1e7d1f..e2ec67a5b5 100644 --- a/logging-modules/log4j2/pom.xml +++ b/logging-modules/log4j2/pom.xml @@ -53,13 +53,25 @@ test-jar test - + - 2.9.3 + 2.9.5 1.4.193 2.1.1 - 2.10.0 + 2.11.0 + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + none + + + + diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/Log4j2BaseIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/Log4j2BaseIntegrationTest.java new file mode 100644 index 0000000000..6b68977fd6 --- /dev/null +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/Log4j2BaseIntegrationTest.java @@ -0,0 +1,18 @@ +package com.baeldung.logging.log4j2; + +import org.apache.logging.log4j.core.config.ConfigurationFactory; +import org.apache.logging.log4j.spi.LoggerContextFactory; +import org.junit.AfterClass; + +import java.lang.reflect.Field; + +public class Log4j2BaseIntegrationTest { + @AfterClass + public static void tearDown() throws Exception { + Field factories = ConfigurationFactory.class.getDeclaredField("factories"); + factories.setAccessible(true); + factories.set(null, null); + ConfigurationFactory.resetConfigurationFactory(); + + } +} diff --git a/logging-modules/log4j2-programmatic-configuration/set-configuration-factory/src/test/java/com/baeldung/log4j2/logtest/LogTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/setconfigurationfactory/SetConfigurationFactoryIntegrationTest.java similarity index 64% rename from logging-modules/log4j2-programmatic-configuration/set-configuration-factory/src/test/java/com/baeldung/log4j2/logtest/LogTest.java rename to logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/setconfigurationfactory/SetConfigurationFactoryIntegrationTest.java index bf78a04dc4..db3b0780a2 100644 --- a/logging-modules/log4j2-programmatic-configuration/set-configuration-factory/src/test/java/com/baeldung/log4j2/logtest/LogTest.java +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/setconfigurationfactory/SetConfigurationFactoryIntegrationTest.java @@ -2,32 +2,34 @@ This class invokes the configuration factory with static initialization, as defined in section 4.1 of the "Programmatic Configuration with Log4j 2" **/ -package com.baeldung.log4j2.logtest; +package com.baeldung.logging.log4j2.setconfigurationfactory; +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; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; import org.apache.logging.log4j.core.config.ConfigurationFactory; +import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import com.baeldung.log4j2.config.CustomConfigurationFactory; - @RunWith(JUnit4.class) -public class LogTest { - static { +public class SetConfigurationFactoryIntegrationTest extends Log4j2BaseIntegrationTest { + @BeforeClass + public static void setUp() { CustomConfigurationFactory customConfigurationFactory = new CustomConfigurationFactory(); ConfigurationFactory.setConfigurationFactory(customConfigurationFactory); } @Test - public void simpleProgrammaticConfiguration() { - Logger logger = LogManager.getLogger(); + public void givenDirectConfiguration_whenUsingFlowMarkers_ThenLogsCorrectly() { + Logger logger = LogManager.getLogger(this.getClass()); Marker markerContent = MarkerManager.getMarker("FLOW"); logger.debug(markerContent, "Debug log message"); logger.info(markerContent, "Info log message"); logger.error(markerContent, "Error log message"); } -} +} \ No newline at end of file diff --git a/logging-modules/log4j2-programmatic-configuration/simple-configuration/src/main/java/com/baeldung/log4j2/config/CustomConfigurationFactory.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfiguration/CustomConfigurationFactory.java similarity index 97% rename from logging-modules/log4j2-programmatic-configuration/simple-configuration/src/main/java/com/baeldung/log4j2/config/CustomConfigurationFactory.java rename to logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfiguration/CustomConfigurationFactory.java index ca3cfa142d..6beb540115 100644 --- a/logging-modules/log4j2-programmatic-configuration/simple-configuration/src/main/java/com/baeldung/log4j2/config/CustomConfigurationFactory.java +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfiguration/CustomConfigurationFactory.java @@ -3,8 +3,7 @@ the configuration factory, as described in Section 3 of "Programmatic Configuration with Log4j 2" **/ - -package com.baeldung.log4j2.config; +package com.baeldung.logging.log4j2.simpleconfiguration; import java.io.IOException; import java.net.URI; @@ -26,7 +25,7 @@ import org.apache.logging.log4j.core.config.builder.api.RootLoggerComponentBuild import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration; import org.apache.logging.log4j.core.config.plugins.Plugin; -@Plugin(name = "CustomConfigurationFactory", category = ConfigurationFactory.CATEGORY) +@Plugin(name = "simple", category = ConfigurationFactory.CATEGORY) @Order(50) public class CustomConfigurationFactory extends ConfigurationFactory { @@ -92,3 +91,4 @@ public class CustomConfigurationFactory extends ConfigurationFactory { return new String[] { "*" }; } } + diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfiguration/SimpleConfigurationIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfiguration/SimpleConfigurationIntegrationTest.java new file mode 100644 index 0000000000..25f0736df5 --- /dev/null +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfiguration/SimpleConfigurationIntegrationTest.java @@ -0,0 +1,30 @@ +/** + This class invokes the configuration factory through the run time property, + as defined in section 4.2 of the "Programmatic Configuration with Log4j 2" +**/ +package com.baeldung.logging.log4j2.simpleconfiguration; + +import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; +import org.apache.logging.log4j.core.config.plugins.util.PluginManager; +import org.junit.BeforeClass; +import org.junit.Test; + +public class SimpleConfigurationIntegrationTest extends Log4j2BaseIntegrationTest { + @BeforeClass + public static void setUp() { + PluginManager.addPackage("com.baeldung.logging.log4j2.simpleconfiguration"); + } + + @Test + public void givenSimpleConfigurationPlugin_whenUsingFlowMarkers_thenLogsCorrectly() throws Exception { + Logger logger = LogManager.getLogger(this.getClass()); + Marker markerContent = MarkerManager.getMarker("FLOW"); + logger.debug(markerContent, "Debug log message"); + logger.info(markerContent, "Info log message"); + logger.error(markerContent, "Error log message"); + } +} \ No newline at end of file diff --git a/logging-modules/log4j2-programmatic-configuration/simple-configurator/src/test/java/com/baeldung/log4j2/logtest/LogPrinter.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfigurator/LogPrinter.java similarity index 84% rename from logging-modules/log4j2-programmatic-configuration/simple-configurator/src/test/java/com/baeldung/log4j2/logtest/LogPrinter.java rename to logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfigurator/LogPrinter.java index d96808c105..d13de25ab9 100644 --- a/logging-modules/log4j2-programmatic-configuration/simple-configurator/src/test/java/com/baeldung/log4j2/logtest/LogPrinter.java +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfigurator/LogPrinter.java @@ -1,4 +1,5 @@ -package com.baeldung.log4j2.logtest; +package com.baeldung.logging.log4j2.simpleconfigurator; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -12,4 +13,4 @@ public class LogPrinter { logger.info("Info log message"); logger.error("Error log message"); } -} +} \ No newline at end of file diff --git a/logging-modules/log4j2-programmatic-configuration/simple-configurator/src/test/java/com/baeldung/log4j2/configure/LogTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfigurator/SimpleConfiguratorIntegrationTest.java similarity index 59% rename from logging-modules/log4j2-programmatic-configuration/simple-configurator/src/test/java/com/baeldung/log4j2/configure/LogTest.java rename to logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfigurator/SimpleConfiguratorIntegrationTest.java index a5a10426ac..49cde67303 100644 --- a/logging-modules/log4j2-programmatic-configuration/simple-configurator/src/test/java/com/baeldung/log4j2/configure/LogTest.java +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/simpleconfigurator/SimpleConfiguratorIntegrationTest.java @@ -1,10 +1,11 @@ /** - This class demonstrates how to use ConfigurationBuilderFactory directly, - as described in Section 3 of "Programmatic Configuration with Log4j 2" -**/ + * This class demonstrates how to use ConfigurationBuilderFactory directly, + * as described in Section 3 of "Programmatic Configuration with Log4j 2" + **/ -package com.baeldung.log4j2.configure; +package com.baeldung.logging.log4j2.simpleconfigurator; +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; @@ -16,23 +17,22 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import com.baeldung.log4j2.logtest.LogPrinter; - @RunWith(JUnit4.class) -public class LogTest { +public class SimpleConfiguratorIntegrationTest extends Log4j2BaseIntegrationTest { + @Test - public void simpleProgrammaticConfiguration() { + public void givenDefaultLog4j2Environment_whenProgrammaticallyConfigured_thenLogsCorrectly() { ConfigurationBuilder builder = ConfigurationBuilderFactory.newConfigurationBuilder(); AppenderComponentBuilder console = builder.newAppender("Stdout", "CONSOLE") - .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT); + .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT); console.add(builder.newLayout("PatternLayout") - .addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable")); + .addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable")); builder.add(console); builder.add(builder.newLogger("com", Level.DEBUG) - .add(builder.newAppenderRef("Stdout")) - .addAttribute("additivity", false)); + .add(builder.newAppenderRef("Stdout")) + .addAttribute("additivity", false)); builder.add(builder.newRootLogger(Level.ERROR) - .add(builder.newAppenderRef("Stdout"))); + .add(builder.newAppenderRef("Stdout"))); Configurator.initialize(builder.build()); LogPrinter logPrinter = new LogPrinter(); logPrinter.printlog(); 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 9493c32094..53634002a0 100644 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutTest.java +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java @@ -6,14 +6,16 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; +import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Before; import org.junit.Test; + import com.fasterxml.jackson.databind.ObjectMapper; -public class JSONLayoutTest { +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/CustomXMLConfigurationFactory.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/CustomXMLConfigurationFactory.java new file mode 100644 index 0000000000..f2392d9f45 --- /dev/null +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/CustomXMLConfigurationFactory.java @@ -0,0 +1,24 @@ +package com.baeldung.logging.log4j2.xmlconfiguration; + +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.config.Configuration; +import org.apache.logging.log4j.core.config.ConfigurationFactory; +import org.apache.logging.log4j.core.config.ConfigurationSource; +import org.apache.logging.log4j.core.config.Order; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.config.xml.XmlConfigurationFactory; + +@Plugin(name = "xml", category = ConfigurationFactory.CATEGORY) +@Order(50) +public class CustomXMLConfigurationFactory extends XmlConfigurationFactory { + + @Override + public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) { + return new MyXMLConfiguration(loggerContext, source); + } + + @Override + public String[] getSupportedTypes() { + return new String[] { ".xml", "*" }; + } +} diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/MyXMLConfiguration.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/MyXMLConfiguration.java new file mode 100644 index 0000000000..25d2536694 --- /dev/null +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/MyXMLConfiguration.java @@ -0,0 +1,36 @@ +/** +This class demonstrates on overriding the configuration loaded through xml +as defined in section 4.4 of "Programmatic Configuration with Log4j 2" +**/ + +package com.baeldung.logging.log4j2.xmlconfiguration; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.core.Appender; +import org.apache.logging.log4j.core.Layout; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.appender.FileAppender; +import org.apache.logging.log4j.core.config.Configuration; +import org.apache.logging.log4j.core.config.ConfigurationSource; +import org.apache.logging.log4j.core.config.LoggerConfig; +import org.apache.logging.log4j.core.config.xml.XmlConfiguration; +import org.apache.logging.log4j.core.layout.PatternLayout; + +public class MyXMLConfiguration extends XmlConfiguration { + public MyXMLConfiguration(LoggerContext loggerContext, ConfigurationSource source) { + super(loggerContext, source); + } + + @Override + protected void doConfigure() { + super.doConfigure(); + final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); + Configuration config = ctx.getConfiguration(); + LoggerConfig loggerConfig = config.getLoggerConfig("com"); + final Layout layout = PatternLayout.createLayout("[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n", null, config, null, null, false, false, null, null); + Appender appender = FileAppender.createAppender("target/test.log", "false", "false", "File", "true", "false", "false", "4000", layout, null, "false", null, config); + loggerConfig.addAppender(appender, Level.DEBUG, null); + addAppender(appender); + } +} \ No newline at end of file diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/XMLConfigLogIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/XMLConfigLogIntegrationTest.java new file mode 100644 index 0000000000..d705b50b1a --- /dev/null +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/xmlconfiguration/XMLConfigLogIntegrationTest.java @@ -0,0 +1,44 @@ + +/** + This class loads the logging configuration from the xml defined in + src/main/resources and uses the same configuration generated through + programmatic configuration as defined in simple-configuration example. +**/ + +package com.baeldung.logging.log4j2.xmlconfiguration; + +import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.Marker; +import org.apache.logging.log4j.MarkerManager; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.config.plugins.util.PluginManager; +import org.junit.BeforeClass; +import org.junit.Test; + +public class XMLConfigLogIntegrationTest extends Log4j2BaseIntegrationTest { + + @BeforeClass + public static void setUp() { + PluginManager.addPackage("com.baeldung.logging.log4j2.xmlconfiguration"); + } + + @Test + public void givenXMLConfigurationPlugin_whenUsingFlowMarkers_ThenLogsCorrectly() throws Exception { + Logger logger = LogManager.getLogger(this.getClass()); + Marker markerContent = MarkerManager.getMarker("FLOW"); + logger.debug(markerContent, "Debug log message"); + logger.info(markerContent, "Info log message"); + logger.error(markerContent, "Error log message"); + } + + @Test + public void givenXMLConfigurationPlugin_whenSimpleLog_ThenLogsCorrectly() throws Exception { + Logger logger = LogManager.getLogger(this.getClass()); + LoggerContext ctx = (LoggerContext) LogManager.getContext(); + logger.debug("Debug log message"); + logger.info("Info log message"); + logger.error("Error log message"); + } +} 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/lombok/pom.xml b/lombok/pom.xml index d11cffb34b..e0b0426c58 100644 --- a/lombok/pom.xml +++ b/lombok/pom.xml @@ -27,6 +27,12 @@ hibernate-jpa-2.1-api ${hibernate-jpa-2.1-api.version} + + org.assertj + assertj-core + ${assertj-core.version} + test + @@ -76,6 +82,7 @@ 1.0.0.Final 1.16.10.0 + 3.8.0 diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/ClientBuilder.java b/lombok/src/main/java/com/baeldung/lombok/builder/ClientBuilder.java new file mode 100644 index 0000000000..32c3d4b8ce --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/ClientBuilder.java @@ -0,0 +1,11 @@ +package com.baeldung.lombok.builder; + +import lombok.Builder; + +class ClientBuilder { + + @Builder(builderMethodName = "builder") + public static ImmutableClient newClient(int id, String name) { + return new ImmutableClient(id, name); + } +} diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/ImmutableClient.java b/lombok/src/main/java/com/baeldung/lombok/builder/ImmutableClient.java new file mode 100644 index 0000000000..48782583e2 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/ImmutableClient.java @@ -0,0 +1,11 @@ +package com.baeldung.lombok.builder; + +import lombok.Value; + +@Value +final class ImmutableClient { + + private int id; + private String name; + +} diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/Widget.java b/lombok/src/main/java/com/baeldung/lombok/builder/Widget.java new file mode 100644 index 0000000000..dbb99f55a4 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/Widget.java @@ -0,0 +1,13 @@ +package com.baeldung.lombok.builder; + +import lombok.Builder; +import lombok.Getter; + +@Getter +@Builder(toBuilder = true) +public class Widget { + + private final String name; + private final int id; + +} diff --git a/lombok/src/main/java/com/baeldung/lombok/intro/ClientBuilder.java b/lombok/src/main/java/com/baeldung/lombok/intro/ClientBuilder.java new file mode 100644 index 0000000000..e7851760c5 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/intro/ClientBuilder.java @@ -0,0 +1,11 @@ +package com.baeldung.lombok.intro; + +import lombok.Builder; + +class ClientBuilder { + + @Builder(builderMethodName = "builder") + public static ImmutableClient newClient(int id, String name) { + return new ImmutableClient(id, name); + } +} diff --git a/lombok/src/main/java/com/baeldung/lombok/intro/ImmutableClient.java b/lombok/src/main/java/com/baeldung/lombok/intro/ImmutableClient.java new file mode 100644 index 0000000000..86be75ecd0 --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/intro/ImmutableClient.java @@ -0,0 +1,11 @@ +package com.baeldung.lombok.intro; + +import lombok.Value; + +@Value +final class ImmutableClient { + + private int id; + private String name; + +} diff --git a/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java b/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java new file mode 100644 index 0000000000..acad7d6c04 --- /dev/null +++ b/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.lombok.builder; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.*; + +public class BuilderUnitTest +{ + + @Test + public void givenBuilder_WidgetIsBuilt() { + Widget testWidget = Widget.builder().name("foo").id(1).build(); + assertThat(testWidget.getName()) + .isEqualTo("foo"); + assertThat(testWidget.getId()) + .isEqualTo(1); + } + + @Test + public void givenToBuilder_whenToBuilder_BuilderIsCreated() { + + Widget testWidget = Widget.builder().name("foo").id(1).build(); + Widget.WidgetBuilder widgetBuilder = testWidget.toBuilder(); + + Widget newWidget = widgetBuilder.id(2).build(); + assertThat(newWidget.getName()) + .isEqualTo("foo"); + assertThat(newWidget.getId()) + .isEqualTo(2); + } + + + + @Test + public void givenBuilderMethod_ClientIsBuilt() { + ImmutableClient testImmutableClient = ClientBuilder.builder().name("foo").id(1).build(); + assertThat(testImmutableClient.getName()) + .isEqualTo("foo"); + assertThat(testImmutableClient.getId()) + .isEqualTo(1); + } +} diff --git a/lombok/src/test/java/com/baeldung/lombok/intro/BuilderMethodUnitTest.java b/lombok/src/test/java/com/baeldung/lombok/intro/BuilderMethodUnitTest.java new file mode 100644 index 0000000000..52ecc49c45 --- /dev/null +++ b/lombok/src/test/java/com/baeldung/lombok/intro/BuilderMethodUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.lombok.intro; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.*; + +public class BuilderMethodUnitTest +{ + + @Test + public void givenBuilderMethod_ClientIsBuilt() { + ImmutableClient testImmutableClient = ClientBuilder.builder().name("foo").id(1).build(); + assertThat(testImmutableClient.getName()) + .isEqualTo("foo"); + assertThat(testImmutableClient.getId()) + .isEqualTo(1); + } +} 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-archetype/pom.xml b/maven-archetype/pom.xml new file mode 100644 index 0000000000..df0aa768d8 --- /dev/null +++ b/maven-archetype/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + + com.baeldung.archetypes + maven-archetype + 1.0-SNAPSHOT + maven-archetype + Archetype used to generate rest application based on jaxrs 2.1 + + + 1.8 + 1.8 + + + + + + org.apache.maven.archetype + archetype-packaging + 3.0.1 + + + + + + diff --git a/maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml b/maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml new file mode 100644 index 0000000000..85e1b92d12 --- /dev/null +++ b/maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml @@ -0,0 +1,35 @@ + + + + + resources + + + Hi, I was generated from an archetype! + + + 2.4.2 + + + + + + src/main/java + + **/*.java + + + + src/main/liberty/config + + server.xml + + + + + diff --git a/maven-archetype/src/main/resources/archetype-resources/pom.xml b/maven-archetype/src/main/resources/archetype-resources/pom.xml new file mode 100644 index 0000000000..eb69f64626 --- /dev/null +++ b/maven-archetype/src/main/resources/archetype-resources/pom.xml @@ -0,0 +1,82 @@ + + 4.0.0 + + ${groupId} + ${artifactId} + ${version} + war + + + UTF-8 + 1.8 + 1.8 + false + ${liberty-plugin-version} + 9080 + 9443 + + + + ${artifactId} + + + 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-06-18_1442/openliberty-all-20180618-1300.zip + + + true + project + src/main/liberty/config/server.xml + true + + ${defaultHttpPort} + ${defaultHttpsPort} + + + + + install-server + prepare-package + + install-server + create-server + install-feature + + + + install-apps + package + + install-apps + + + + + + + + + + + javax.enterprise + cdi-api + 2.0 + provided + + + + javax.ws.rs + javax.ws.rs-api + 2.1 + provided + + + + + diff --git a/maven-archetype/src/main/resources/archetype-resources/src/main/java/AppConfig.java b/maven-archetype/src/main/resources/archetype-resources/src/main/java/AppConfig.java new file mode 100644 index 0000000000..7e17ab6aac --- /dev/null +++ b/maven-archetype/src/main/resources/archetype-resources/src/main/java/AppConfig.java @@ -0,0 +1,8 @@ +package ${package}; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("${app-path}") +public class AppConfig extends Application { +} diff --git a/maven-archetype/src/main/resources/archetype-resources/src/main/java/PingResource.java b/maven-archetype/src/main/resources/archetype-resources/src/main/java/PingResource.java new file mode 100644 index 0000000000..a2f34a7ac3 --- /dev/null +++ b/maven-archetype/src/main/resources/archetype-resources/src/main/java/PingResource.java @@ -0,0 +1,18 @@ +package ${package}; + +import javax.enterprise.context.RequestScoped; +import javax.inject.Inject; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; + +@Path("ping") +public class PingResource { + + @GET + public Response get() { + return Response.ok("${greeting-msg}").build(); + } + +} \ No newline at end of file diff --git a/maven-archetype/src/main/resources/archetype-resources/src/main/liberty/config/server.xml b/maven-archetype/src/main/resources/archetype-resources/src/main/liberty/config/server.xml new file mode 100644 index 0000000000..c316868b4f --- /dev/null +++ b/maven-archetype/src/main/resources/archetype-resources/src/main/liberty/config/server.xml @@ -0,0 +1,8 @@ + + + cdi-2.0 + jaxrs-2.1 + + + \ No newline at end of file diff --git a/maven/src/test/java/com/baeldung/maven/plugins/DataTest.java b/maven/src/test/java/com/baeldung/maven/plugins/DataUnitTest.java similarity index 90% rename from maven/src/test/java/com/baeldung/maven/plugins/DataTest.java rename to maven/src/test/java/com/baeldung/maven/plugins/DataUnitTest.java index 3f03b6f5d6..197f977fec 100644 --- a/maven/src/test/java/com/baeldung/maven/plugins/DataTest.java +++ b/maven/src/test/java/com/baeldung/maven/plugins/DataUnitTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import com.baeldung.maven.plugins.Data; -public class DataTest { +public class DataUnitTest { @Test public void whenDataObjectIsNotCreated_thenItIsNull() { Data data = null; diff --git a/mesos-marathon/pom.xml b/mesos-marathon/pom.xml index 2b7a238ee8..77d13cd5c6 100644 --- a/mesos-marathon/pom.xml +++ b/mesos-marathon/pom.xml @@ -7,10 +7,10 @@ 0.0.1-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java b/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasIntegrationTest.java similarity index 99% rename from metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java rename to metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasIntegrationTest.java index b76dc40ba0..e7f3d7ec72 100644 --- a/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasTest.java +++ b/metrics/src/test/java/com/baeldung/metrics/micrometer/MicrometerAtlasIntegrationTest.java @@ -39,7 +39,7 @@ import com.netflix.spectator.atlas.AtlasConfig; /** * @author aiet */ -public class MicrometerAtlasTest { +public class MicrometerAtlasIntegrationTest { private AtlasConfig atlasConfig; diff --git a/msf4j/README.md b/msf4j/README.md new file mode 100644 index 0000000000..7c66b8dc5f --- /dev/null +++ b/msf4j/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to Java Microservices with MSF4J](http://www.baeldung.com/msf4j) diff --git a/msf4j/pom.xml b/msf4j/pom.xml new file mode 100644 index 0000000000..f691d746b7 --- /dev/null +++ b/msf4j/pom.xml @@ -0,0 +1,32 @@ + + + + org.wso2.msf4j + msf4j-service + 2.6.0 + + 4.0.0 + + com.baeldung.msf4j + msf4j + 0.0.1-SNAPSHOT + WSO2 MSF4J Microservice + + + com.baeldung.msf4j.msf4jintro.Application + + + + org.wso2.msf4j + msf4j-spring + 2.6.1 + + + org.wso2.msf4j + msf4j-mustache-template + 2.6.1 + + + + \ No newline at end of file diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Application.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Application.java new file mode 100644 index 0000000000..c4cf136536 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Application.java @@ -0,0 +1,11 @@ +package com.baeldung.msf4j.msf4japi; + +import org.wso2.msf4j.MicroservicesRunner; + +public class Application { + public static void main(String[] args) { + new MicroservicesRunner() + .deploy(new MenuService()) + .start(); + } +} \ No newline at end of file diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Meal.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Meal.java new file mode 100644 index 0000000000..d17a7a1034 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/Meal.java @@ -0,0 +1,20 @@ +package com.baeldung.msf4j.msf4japi; + +public class Meal { + private String name; + private Float price; + + public Meal(String name, Float price) { + this.name = name; + this.price = price; + } + + public String getName() { + return name; + } + + public Float getPrice() { + return price; + } + +} diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/MenuService.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/MenuService.java new file mode 100644 index 0000000000..4f880a1393 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4japi/MenuService.java @@ -0,0 +1,78 @@ +package com.baeldung.msf4j.msf4japi; + +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; + +import com.google.gson.Gson; + +@Path("/menu") +public class MenuService { + + private List meals = new ArrayList(); + + public MenuService() { + meals.add(new Meal("Java beans",42.0f)); + } + + @GET + @Path("/") + @Produces({ "application/json" }) + public Response index() { + return Response.ok() + .entity(meals) + .build(); + } + + @GET + @Path("/{id}") + @Produces({ "application/json" }) + public Response meal(@PathParam("id") int id) { + return Response.ok() + .entity(meals.get(id)) + .build(); + } + + + @POST + @Path("/") + @Consumes("application/json") + @Produces({ "application/json" }) + public Response create(Meal meal) { + meals.add(meal); + return Response.ok() + .entity(meal) + .build(); + } + + @PUT + @Path("/{id}") + @Consumes("application/json") + @Produces({ "application/json" }) + public Response update(@PathParam("id") int id, Meal meal) { + meals.set(id, meal); + return Response.ok() + .entity(meal) + .build(); + } + + @DELETE + @Path("/{id}") + @Produces({ "application/json" }) + public Response delete(@PathParam("id") int id) { + Meal meal = meals.get(id); + meals.remove(id); + return Response.ok() + .entity(meal) + .build(); + } +} diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/Application.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/Application.java new file mode 100644 index 0000000000..dc4a060056 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/Application.java @@ -0,0 +1,11 @@ +package com.baeldung.msf4j.msf4jintro; + +import org.wso2.msf4j.MicroservicesRunner; + +public class Application { + public static void main(String[] args) { + new MicroservicesRunner() + .deploy(new SimpleService()) + .start(); + } +} \ No newline at end of file diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/SimpleService.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/SimpleService.java new file mode 100644 index 0000000000..bcb52859b5 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jintro/SimpleService.java @@ -0,0 +1,21 @@ +package com.baeldung.msf4j.msf4jintro; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; + +@Path("/") +public class SimpleService { + + @GET + public String index() { + return "Default content"; + } + + @GET + @Path("/say/{name}") + public String say(@PathParam("name") String name) { + return "Hello " + name; + } + +} diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/Application.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/Application.java new file mode 100644 index 0000000000..2a5232a7e6 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/Application.java @@ -0,0 +1,10 @@ +package com.baeldung.msf4j.msf4jspring; + +import org.wso2.msf4j.spring.MSF4JSpringApplication; + +public class Application { + + public static void main(String[] args) { + MSF4JSpringApplication.run(Application.class, args); + } +} \ No newline at end of file diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/configuration/PortConfiguration.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/configuration/PortConfiguration.java new file mode 100644 index 0000000000..c3313fc3b1 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/configuration/PortConfiguration.java @@ -0,0 +1,15 @@ +package com.baeldung.msf4j.msf4jspring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.wso2.msf4j.spring.transport.HTTPTransportConfig; + +@Configuration +public class PortConfiguration { + + @Bean + public HTTPTransportConfig http() { + return new HTTPTransportConfig(9090); + } + +} \ No newline at end of file diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/domain/Meal.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/domain/Meal.java new file mode 100644 index 0000000000..99de0abc4c --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/domain/Meal.java @@ -0,0 +1,20 @@ +package com.baeldung.msf4j.msf4jspring.domain; + +public class Meal { + private String name; + private Float price; + + public Meal(String name, Float price) { + this.name = name; + this.price = price; + } + + public String getName() { + return name; + } + + public Float getPrice() { + return price; + } + +} diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/repositories/MealRepository.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/repositories/MealRepository.java new file mode 100644 index 0000000000..4d9e54348e --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/repositories/MealRepository.java @@ -0,0 +1,37 @@ +package com.baeldung.msf4j.msf4jspring.repositories; + +import java.util.ArrayList; +import java.util.List; +import org.springframework.stereotype.Component; +import com.baeldung.msf4j.msf4jspring.domain.Meal; + +@Component +public class MealRepository { + + private List meals = new ArrayList(); + + public MealRepository() { + meals.add(new Meal("Salad", 4.2f)); + meals.add(new Meal("Litre of cola", 2.99f)); + } + + public void create(Meal meal) { + meals.add(meal); + } + + public void remove(Meal meal) { + meals.remove(meal); + } + + public Meal find(int id) { + return meals.get(id); + } + + public List findAll() { + return meals; + } + + public void update(int id, Meal meal) { + meals.set(id, meal); + } +} \ No newline at end of file diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/resources/MealResource.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/resources/MealResource.java new file mode 100644 index 0000000000..9c617257cb --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/resources/MealResource.java @@ -0,0 +1,47 @@ +package com.baeldung.msf4j.msf4jspring.resources; + +import java.util.Collections; +import java.util.Map; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.wso2.msf4j.template.MustacheTemplateEngine; + +import com.baeldung.msf4j.msf4jspring.services.MealService; + +@Component +@Path("/meal") +public class MealResource { + + @Autowired + private MealService mealService; + + @GET + @Path("/") + public Response all() { + Map map = Collections.singletonMap("meals", mealService.findAll()); + String html = MustacheTemplateEngine.instance() + .render("meals.mustache", map); + return Response.ok() + .type(MediaType.TEXT_HTML) + .entity(html) + .build(); + } + + @GET + @Path("/{id}") + @Produces({ "text/xml" }) + public Response meal(@PathParam("id") int id) { + return Response.ok() + .entity(mealService.find(id)) + .build(); + } + +} diff --git a/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/services/MealService.java b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/services/MealService.java new file mode 100644 index 0000000000..fd6a519999 --- /dev/null +++ b/msf4j/src/main/java/com/baeldung/msf4j/msf4jspring/services/MealService.java @@ -0,0 +1,27 @@ +package com.baeldung.msf4j.msf4jspring.services; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.baeldung.msf4j.msf4jspring.domain.Meal; +import com.baeldung.msf4j.msf4jspring.repositories.MealRepository; + +@Service +public class MealService { + @Autowired + private MealRepository mealRepository; + + public Meal find(int id) { + return mealRepository.find(id); + } + + public List findAll() { + return mealRepository.findAll(); + } + + public void create(Meal meal) { + mealRepository.create(meal); + } +} diff --git a/msf4j/src/main/resources/application.properties b/msf4j/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/msf4j/src/main/resources/templates/meals.mustache b/msf4j/src/main/resources/templates/meals.mustache new file mode 100644 index 0000000000..f4bdfaccf9 --- /dev/null +++ b/msf4j/src/main/resources/templates/meals.mustache @@ -0,0 +1,13 @@ + + + Meals + + +
+

Today's Meals

+ {{#meals}} +
{{name}}: {{price}}$
+ {{/meals}} +
+ + \ No newline at end of file diff --git a/mustache/pom.xml b/mustache/pom.xml index 88d87758cd..40fcecc4f8 100644 --- a/mustache/pom.xml +++ b/mustache/pom.xml @@ -95,6 +95,7 @@ **/*IntegrationTest.java + **/*IntTest.java @@ -125,6 +126,7 @@ **/*LiveTest.java **/*IntegrationTest.java + **/*IntTest.java **/AutoconfigurationTest.java diff --git a/mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceTest.java b/mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceUnitTest.java similarity index 98% rename from mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceTest.java rename to mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceUnitTest.java index 0df2f7f8a4..0c192b30bc 100644 --- a/mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceTest.java +++ b/mustache/src/test/java/com/baeldung/mustache/TodoMustacheServiceUnitTest.java @@ -15,7 +15,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -public class TodoMustacheServiceTest { +public class TodoMustacheServiceUnitTest { private String executeTemplate(Mustache m, Map context) throws IOException { StringWriter writer = new StringWriter(); diff --git a/mvn-wrapper/pom.xml b/mvn-wrapper/pom.xml index 6fb9bfeffc..e26df81139 100644 --- a/mvn-wrapper/pom.xml +++ b/mvn-wrapper/pom.xml @@ -9,10 +9,10 @@ Setting up the Maven Wrapper - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBDocumentAPITest.java b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBDocumentAPILiveTest.java similarity index 97% rename from orientdb/src/test/java/com/baeldung/orientdb/OrientDBDocumentAPITest.java rename to orientdb/src/test/java/com/baeldung/orientdb/OrientDBDocumentAPILiveTest.java index c51ff6928f..be79394292 100644 --- a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBDocumentAPITest.java +++ b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBDocumentAPILiveTest.java @@ -11,7 +11,7 @@ import java.util.List; import static junit.framework.Assert.assertEquals; -public class OrientDBDocumentAPITest { +public class OrientDBDocumentAPILiveTest { private static ODatabaseDocumentTx db = null; // @BeforeClass diff --git a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBGraphAPITest.java b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBGraphAPILiveTest.java similarity index 98% rename from orientdb/src/test/java/com/baeldung/orientdb/OrientDBGraphAPITest.java rename to orientdb/src/test/java/com/baeldung/orientdb/OrientDBGraphAPILiveTest.java index fe16564755..69926e5ed6 100644 --- a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBGraphAPITest.java +++ b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBGraphAPILiveTest.java @@ -10,7 +10,7 @@ import org.junit.Test; import static junit.framework.Assert.assertEquals; -public class OrientDBGraphAPITest { +public class OrientDBGraphAPILiveTest { private static OrientGraphNoTx graph = null; // @BeforeClass diff --git a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBObjectAPITest.java b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBObjectAPILiveTest.java similarity index 97% rename from orientdb/src/test/java/com/baeldung/orientdb/OrientDBObjectAPITest.java rename to orientdb/src/test/java/com/baeldung/orientdb/OrientDBObjectAPILiveTest.java index 71be159107..61dad39050 100644 --- a/orientdb/src/test/java/com/baeldung/orientdb/OrientDBObjectAPITest.java +++ b/orientdb/src/test/java/com/baeldung/orientdb/OrientDBObjectAPILiveTest.java @@ -10,7 +10,7 @@ import java.util.List; import static junit.framework.Assert.assertEquals; -public class OrientDBObjectAPITest { +public class OrientDBObjectAPILiveTest { private static OObjectDatabaseTx db = null; // @BeforeClass diff --git a/parent-boot-5/README.md b/parent-boot-1/README.md similarity index 100% rename from parent-boot-5/README.md rename to parent-boot-1/README.md diff --git a/parent-boot-5/pom.xml b/parent-boot-1/pom.xml similarity index 96% rename from parent-boot-5/pom.xml rename to parent-boot-1/pom.xml index 32bb2eab04..bd28f7c5e2 100644 --- a/parent-boot-5/pom.xml +++ b/parent-boot-1/pom.xml @@ -2,16 +2,15 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - parent-boot-5 + parent-boot-1 0.0.1-SNAPSHOT pom - Parent Boot 5 - Parent for all spring boot 1.5 modules + Parent for all Spring Boot 1.x modules org.springframework.boot spring-boot-starter-parent - 1.5.10.RELEASE + 1.5.13.RELEASE @@ -48,6 +47,7 @@ true **/*IntegrationTest.java + **/*IntTest.java **/*LongRunningUnitTest.java **/*ManualTest.java **/*LiveTest.java @@ -89,8 +89,8 @@ **/*IntegrationTest.java - */EthControllerTestOne.java **/*IntTest.java + */EthControllerTestOne.java **/*EntryPointsTest.java diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index a9c54dece9..b62d37b3f0 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -48,6 +48,7 @@ true **/*IntegrationTest.java + **/*IntTest.java **/*LongRunningUnitTest.java **/*ManualTest.java **/*LiveTest.java @@ -89,8 +90,8 @@ **/*IntegrationTest.java - */EthControllerTestOne.java **/*IntTest.java + */EthControllerTestOne.java **/*EntryPointsTest.java @@ -105,6 +106,25 @@
+ + thin-jar + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.springframework.boot.experimental + spring-boot-thin-layout + ${thin.version} + + + + + + @@ -115,6 +135,7 @@ 1.8 1.8 + 1.0.11.RELEASE \ No newline at end of file diff --git a/parent-spring/README.md b/parent-spring-4/README.md similarity index 100% rename from parent-spring/README.md rename to parent-spring-4/README.md diff --git a/parent-spring-4/pom.xml b/parent-spring-4/pom.xml new file mode 100644 index 0000000000..b2b8295f01 --- /dev/null +++ b/parent-spring-4/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + com.baeldung + parent-spring-4 + 0.0.1-SNAPSHOT + pom + parent-spring-4 + Parent for all spring 4 core modules + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.springframework + spring-core + ${spring.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + + + 4.3.17.RELEASE + 5.0.2 + + + \ No newline at end of file diff --git a/parent-spring-5/README.md b/parent-spring-5/README.md new file mode 100644 index 0000000000..ff12555376 --- /dev/null +++ b/parent-spring-5/README.md @@ -0,0 +1 @@ +## Relevant articles: diff --git a/parent-spring/pom.xml b/parent-spring-5/pom.xml similarity index 84% 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/README.md b/patterns/design-patterns/README.md index cb44bf4bc4..77ead0b317 100644 --- a/patterns/design-patterns/README.md +++ b/patterns/design-patterns/README.md @@ -1,2 +1,11 @@ ### Relevant Articles: - [Facade Design Pattern in Java](http://www.baeldung.com/java-facade-pattern) +- [Singletons in Java](http://www.baeldung.com/java-singleton) +- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns) +- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns) +- [The Observer Pattern in Java](http://www.baeldung.com/java-observer-pattern) +- [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight) +- [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern) +- [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking) +- [Composite Design Pattern in Java](http://www.baeldung.com/java-composite-pattern) +- [Visitor Design Pattern in Java](http://www.baeldung.com/java-visitor-pattern) diff --git a/patterns/design-patterns/pom.xml b/patterns/design-patterns/pom.xml index 87db08ab32..dd1c5abced 100644 --- a/patterns/design-patterns/pom.xml +++ b/patterns/design-patterns/pom.xml @@ -12,41 +12,63 @@ .. - + junit junit 4.12 test - - org.hamcrest - hamcrest-core - 1.3 - test + + org.hamcrest + hamcrest-core + 1.3 + test org.assertj assertj-core - 3.8.0 + 3.9.1 test - - log4j - log4j - ${log4j.version} + + org.mockito + mockito-core + 2.18.3 + test - + + javax + javaee-api + 8.0 + + + org.hibernate + hibernate-core + 5.2.16.Final + + + mysql + mysql-connector-java + 6.0.6 + jar + + + log4j + log4j + ${log4j.version} + + com.googlecode.grep4j - grep4j - ${grep4j.version} - + grep4j + ${grep4j.version} + UTF-8 1.8 1.8 1.2.17 - 1.8.7 + 1.8.7 - \ No newline at end of file + 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 new file mode 100644 index 0000000000..3a5c049992 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/application/UserApplication.java @@ -0,0 +1,53 @@ +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; +import java.util.List; +import java.util.Optional; +import javax.persistence.EntityManager; +import javax.persistence.Persistence; + +public class UserApplication { + + private static JpaUserDao jpaUserDao; + + public static void main(String[] args) { + User user1 = getUser(1); + System.out.println(user1); + updateUser(user1, new String[]{"John", "john@domain.com"}); + saveUser(new User("Monica", "monica@domain.com")); + deleteUser(getUser(2)); + 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() { + return JpaUserDaoHolder.jpaUserDao; + } + + public static User getUser(long id) { + Optional user = getJpaUserDao().get(id); + return user.orElseGet(()-> {return new User("non-existing user", "no-email");}); + } + + public static List getAllUsers() { + return getJpaUserDao().getAll(); + } + + public static void updateUser(User user, String[] params){ + getJpaUserDao().update(user, params); + } + + public static void saveUser(User user) { + getJpaUserDao().save(user); + } + + public static void deleteUser(User user) { + getJpaUserDao().delete(user); + } +} 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/daopattern/daos/Dao.java b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/daos/Dao.java new file mode 100644 index 0000000000..35aa763097 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/daos/Dao.java @@ -0,0 +1,17 @@ +package com.baeldung.daopattern.daos; + +import java.util.List; +import java.util.Optional; + +public interface Dao { + + Optional get(long id); + + List getAll(); + + void save(T t); + + void update(T t, String[] params); + + void delete(T t); +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/daopattern/daos/JpaUserDao.java b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/daos/JpaUserDao.java new file mode 100644 index 0000000000..f4d80c0ee9 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/daos/JpaUserDao.java @@ -0,0 +1,60 @@ +package com.baeldung.daopattern.daos; + +import com.baeldung.daopattern.entities.User; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Consumer; +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.persistence.Query; + +public class JpaUserDao implements Dao { + + private final EntityManager entityManager; + + public JpaUserDao(EntityManager entityManager) { + this.entityManager = entityManager; + } + + @Override + public Optional get(long id) { + return Optional.ofNullable(entityManager.find(User.class, id)); + } + + @Override + public List getAll() { + Query query = entityManager.createQuery("SELECT e FROM User e"); + return query.getResultList(); + } + + @Override + public void save(User user) { + executeInsideTransaction(entityManager -> entityManager.persist(user)); + } + + @Override + public void update(User user, String[] params) { + user.setName(Objects.requireNonNull(params[0], "Name cannot be null")); + user.setEmail(Objects.requireNonNull(params[1], "Email cannot be null")); + executeInsideTransaction(entityManager -> entityManager.merge(user)); + } + + @Override + public void delete(User user) { + executeInsideTransaction(entityManager -> entityManager.remove(user)); + } + + private void executeInsideTransaction(Consumer action) { + final EntityTransaction tx = entityManager.getTransaction(); + try { + tx.begin(); + action.accept(entityManager); + tx.commit(); + } + catch (RuntimeException e) { + tx.rollback(); + throw e; + } + } +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/daopattern/daos/UserDao.java b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/daos/UserDao.java new file mode 100644 index 0000000000..2fd4047772 --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/daos/UserDao.java @@ -0,0 +1,44 @@ +package com.baeldung.daopattern.daos; + +import com.baeldung.daopattern.entities.User; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +public class UserDao implements Dao { + + private List users = new ArrayList<>(); + + public UserDao() { + users.add(new User("John", "john@domain.com")); + users.add(new User("Susan", "susan@domain.com")); + } + + @Override + public Optional get(long id) { + return Optional.ofNullable(users.get((int) id)); + } + + @Override + public List getAll() { + return users; + } + + @Override + public void save(User user) { + users.add(user); + } + + @Override + public void update(User user, String[] params) { + user.setName(Objects.requireNonNull(params[0], "Name cannot be null")); + user.setEmail(Objects.requireNonNull(params[1], "Email cannot be null")); + users.add(user); + } + + @Override + public void delete(User user) { + users.remove(user); + } +} diff --git a/patterns/design-patterns/src/main/java/com/baeldung/daopattern/entities/User.java b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/entities/User.java new file mode 100644 index 0000000000..58d8ffb28b --- /dev/null +++ b/patterns/design-patterns/src/main/java/com/baeldung/daopattern/entities/User.java @@ -0,0 +1,45 @@ +package com.baeldung.daopattern.entities; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + private String name; + private String email; + + public User(){} + + public User(String name, String email) { + this.name = name; + this.email = email; + } + + public void setName(String name) { + this.name = name; + } + + public void setEmail(String email) { + this.email = email; + } + + public long getId() { + return id; + } + + public String getName() { + return name; + } + + public String getEmail() { + return email; + } +} \ No newline at end of file diff --git a/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 new file mode 100644 index 0000000000..e67a25e467 --- /dev/null +++ b/patterns/design-patterns/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,17 @@ + + + + org.hibernate.jpa.HibernatePersistenceProvider + com.baeldung.pattern.daopattern.entities.User + + + + + + + + + + + + diff --git a/patterns/design-patterns/src/main/resources/log4jstructuraldp.properties b/patterns/design-patterns/src/main/resources/log4jstructuraldp.properties new file mode 100644 index 0000000000..5bc2bfe4b9 --- /dev/null +++ b/patterns/design-patterns/src/main/resources/log4jstructuraldp.properties @@ -0,0 +1,9 @@ + +# Root logger +log4j.rootLogger=INFO, file, stdout + +# Write to console +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n \ No newline at end of file diff --git a/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityTest.java b/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java similarity index 69% rename from patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityTest.java rename to patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java index a84f9dd8e5..824b104f81 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/chainofresponsibility/ChainOfResponsibilityIntegrationTest.java @@ -1,10 +1,15 @@ -package com.baeldung.pattern.chainofresponsibility; +package com.baeldung.chainofresponsibility; import org.junit.Test; - +import com.baeldung.pattern.chainofresponsibility.AuthenticationProcessor; +import com.baeldung.pattern.chainofresponsibility.OAuthAuthenticationProcessor; +import com.baeldung.pattern.chainofresponsibility.OAuthTokenProvider; +import com.baeldung.pattern.chainofresponsibility.UsernamePasswordProvider; +import com.baeldung.pattern.chainofresponsibility.SamlAuthenticationProvider; +import com.baeldung.pattern.chainofresponsibility.UsernamePasswordAuthenticationProcessor; import static org.junit.Assert.assertTrue; -public class ChainOfResponsibilityTest { +public class ChainOfResponsibilityIntegrationTest { private static AuthenticationProcessor getChainOfAuthProcessor() { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/daopattern/test/UserDaoUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/daopattern/test/UserDaoUnitTest.java new file mode 100644 index 0000000000..683e626600 --- /dev/null +++ b/patterns/design-patterns/src/test/java/com/baeldung/daopattern/test/UserDaoUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.daopattern.test; + +import com.baeldung.daopattern.daos.UserDao; +import com.baeldung.daopattern.entities.User; +import java.util.List; +import java.util.Optional; +import static org.assertj.core.api.Assertions.assertThat; +import org.junit.BeforeClass; +import org.junit.Test; + +public class UserDaoUnitTest { + + private static UserDao userDao; + + + @BeforeClass + public static void setUpUserDaoInstance() { + userDao = new UserDao(); + } + + @Test + public void givenUserDaoInstance_whenCalledget_thenOneAssertion() { + assertThat(userDao.get(0)).isInstanceOf(Optional.class); + } + + @Test + public void givenUserDaoInstance_whenCalledgetAll_thenOneAssertion() { + assertThat(userDao.getAll()).isInstanceOf(List.class); + } + + @Test + public void givenUserDaoInstance_whenCalledupdate_thenTwoAssertions() { + User user = new User("Julie", "julie@domain.com"); + userDao.update(user, new String[] {"Julie", "julie@domain.com"}); + assertThat(userDao.get(2).get().getName()).isEqualTo("Julie"); + assertThat(userDao.get(2).get().getEmail()).isEqualTo("julie@domain.com"); + } + + @Test + public void givenUserDaoInstance_whenCalledsave_thenTwoAssertions() { + User user = new User("Julie", "julie@domain.com"); + userDao.save(user); + assertThat(userDao.get(2).get().getName()).isEqualTo("Julie"); + assertThat(userDao.get(2).get().getEmail()).isEqualTo("julie@domain.com"); + } + + @Test + public void givenUserDaoInstance_whenCalleddelete_thenOneAssertion() { + User user = new User("Julie", "julie@domain.com"); + userDao.delete(user); + assertThat(userDao.getAll().size()).isEqualTo(2); + } +} diff --git a/patterns/design-patterns/src/test/java/com/baeldung/facade/CarEngineFacadeTest.java b/patterns/design-patterns/src/test/java/com/baeldung/facade/CarEngineFacadeIntegrationTest.java similarity index 98% rename from patterns/design-patterns/src/test/java/com/baeldung/facade/CarEngineFacadeTest.java rename to patterns/design-patterns/src/test/java/com/baeldung/facade/CarEngineFacadeIntegrationTest.java index 88c5d3c9bc..ab4c0717d9 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/facade/CarEngineFacadeTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/facade/CarEngineFacadeIntegrationTest.java @@ -13,7 +13,7 @@ import java.util.List; import static org.junit.Assert.*; -public class CarEngineFacadeTest { +public class CarEngineFacadeIntegrationTest { private InMemoryCustomTestAppender appender; diff --git a/patterns/design-patterns/src/test/java/com/baeldung/singleton/synchronization/SingletonSynchronizationUnitTest.java b/patterns/design-patterns/src/test/java/com/baeldung/singleton/synchronization/SingletonSynchronizationIntegrationTest.java similarity index 94% rename from patterns/design-patterns/src/test/java/com/baeldung/singleton/synchronization/SingletonSynchronizationUnitTest.java rename to patterns/design-patterns/src/test/java/com/baeldung/singleton/synchronization/SingletonSynchronizationIntegrationTest.java index 08a70f6056..de3d31ed9f 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/singleton/synchronization/SingletonSynchronizationUnitTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/singleton/synchronization/SingletonSynchronizationIntegrationTest.java @@ -15,7 +15,7 @@ import org.junit.Test; * @author Donato Rimenti * */ -public class SingletonSynchronizationUnitTest { +public class SingletonSynchronizationIntegrationTest { /** * Size of the thread pools used. @@ -33,7 +33,7 @@ public class SingletonSynchronizationUnitTest { @Test public void givenDraconianSingleton_whenMultithreadInstancesEquals_thenTrue() { ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); - Set resultSet = Collections.synchronizedSet(new HashSet()); + Set resultSet = Collections.synchronizedSet(new HashSet<>()); // Submits the instantiation tasks. for (int i = 0; i < TASKS_TO_SUBMIT; i++) { @@ -51,7 +51,7 @@ public class SingletonSynchronizationUnitTest { @Test public void givenDclSingleton_whenMultithreadInstancesEquals_thenTrue() { ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); - Set resultSet = Collections.synchronizedSet(new HashSet()); + Set resultSet = Collections.synchronizedSet(new HashSet<>()); // Submits the instantiation tasks. for (int i = 0; i < TASKS_TO_SUBMIT; i++) { @@ -69,7 +69,7 @@ public class SingletonSynchronizationUnitTest { @Test public void givenEarlyInitSingleton_whenMultithreadInstancesEquals_thenTrue() { ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); - Set resultSet = Collections.synchronizedSet(new HashSet()); + Set resultSet = Collections.synchronizedSet(new HashSet<>()); // Submits the instantiation tasks. for (int i = 0; i < TASKS_TO_SUBMIT; i++) { @@ -87,7 +87,7 @@ public class SingletonSynchronizationUnitTest { @Test public void givenInitOnDemandSingleton_whenMultithreadInstancesEquals_thenTrue() { ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); - Set resultSet = Collections.synchronizedSet(new HashSet()); + Set resultSet = Collections.synchronizedSet(new HashSet<>()); // Submits the instantiation tasks. for (int i = 0; i < TASKS_TO_SUBMIT; i++) { @@ -105,7 +105,7 @@ public class SingletonSynchronizationUnitTest { @Test public void givenEnumSingleton_whenMultithreadInstancesEquals_thenTrue() { ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); - Set resultSet = Collections.synchronizedSet(new HashSet()); + Set resultSet = Collections.synchronizedSet(new HashSet<>()); // Submits the instantiation tasks. for (int i = 0; i < TASKS_TO_SUBMIT; i++) { diff --git a/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternTest.java b/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java similarity index 97% rename from patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternTest.java rename to patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java index 679559af9f..4ad4debb27 100644 --- a/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternTest.java +++ b/patterns/design-patterns/src/test/java/com/baeldung/templatemethod/test/TemplateMethodPatternIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.pattern.templatemethod.test; +package com.baeldung.templatemethod.test; import com.baeldung.pattern.templatemethod.model.Computer; import com.baeldung.pattern.templatemethod.model.HighEndComputerBuilder; @@ -10,7 +10,7 @@ import org.junit.Test; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; -public class TemplateMethodPatternTest { +public class TemplateMethodPatternIntegrationTest { private static StandardComputerBuilder standardComputerBuilder; private static HighEndComputerBuilder highEndComputerBuilder; diff --git a/performance-tests/README.md b/performance-tests/README.md new file mode 100644 index 0000000000..5af735b708 --- /dev/null +++ b/performance-tests/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Performance of Java Mapping Frameworks](http://www.baeldung.com/java-performance-mapping-frameworks) diff --git a/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java b/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java index 9a45f032a6..e781f1fca1 100644 --- a/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java +++ b/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java @@ -4,13 +4,32 @@ import com.baeldung.performancetests.dozer.DozerConverter; import com.baeldung.performancetests.jmapper.JMapperConverter; import com.baeldung.performancetests.mapstruct.MapStructConverter; import com.baeldung.performancetests.model.destination.DestinationCode; -import com.baeldung.performancetests.model.source.*; import com.baeldung.performancetests.model.destination.Order; +import com.baeldung.performancetests.model.source.AccountStatus; +import com.baeldung.performancetests.model.source.Address; +import com.baeldung.performancetests.model.source.DeliveryData; +import com.baeldung.performancetests.model.source.Discount; +import com.baeldung.performancetests.model.source.OrderStatus; +import com.baeldung.performancetests.model.source.PaymentType; +import com.baeldung.performancetests.model.source.Product; +import com.baeldung.performancetests.model.source.RefundPolicy; +import com.baeldung.performancetests.model.source.Review; +import com.baeldung.performancetests.model.source.Shop; +import com.baeldung.performancetests.model.source.SourceCode; +import com.baeldung.performancetests.model.source.SourceOrder; +import com.baeldung.performancetests.model.source.User; import com.baeldung.performancetests.modelmapper.ModelMapperConverter; import com.baeldung.performancetests.orika.OrikaConverter; -import org.junit.Assert; -import org.junit.Test; -import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Group; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.runner.RunnerException; import java.io.IOException; @@ -21,14 +40,24 @@ import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; +@Fork(value = 1, warmups = 5) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@BenchmarkMode(Mode.All) +@Measurement(iterations = 5) @State(Scope.Group) public class MappingFrameworksPerformance { - SourceOrder sourceOrder = null; - SourceCode sourceCode = null; + private SourceOrder sourceOrder = null; + private SourceCode sourceCode = null; + private static final OrikaConverter ORIKA_CONVERTER = new OrikaConverter(); + private static final JMapperConverter JMAPPER_CONVERTER = new JMapperConverter(); + private static final ModelMapperConverter MODEL_MAPPER_CONVERTER = new ModelMapperConverter(); + private static final DozerConverter DOZER_CONVERTER = new DozerConverter(); + @Setup public void setUp() { User user = new User("John", "John@doe.com", AccountStatus.ACTIVE); - RefundPolicy refundPolicy = new RefundPolicy(true, 30, Collections.singletonList("Refundable only if not used!")); + RefundPolicy refundPolicy = new RefundPolicy(true, 30, Collections + .singletonList("Refundable only if not used!")); Product product = new Product(BigDecimal.valueOf(10.99), 100, @@ -51,7 +80,7 @@ public class MappingFrameworksPerformance { List reviewList = new ArrayList<>(); reviewList.add(review); reviewList.add(negativeReview); - Shop shop = new Shop("Super Shop", shopAddress,"www.super-shop.com",reviewList); + Shop shop = new Shop("Super Shop", shopAddress, "www.super-shop.com", reviewList); sourceOrder = new SourceOrder(OrderStatus.CONFIRMED, Instant.now().toString(), @@ -68,126 +97,67 @@ public class MappingFrameworksPerformance { sourceCode = new SourceCode("This is source code!"); } - public void main(String[] args) throws IOException, RunnerException { org.openjdk.jmh.Main.main(args); } - @Benchmark @Group("realLifeTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void orikaMapperRealLifeBenchmark() { - OrikaConverter orikaConverter = new OrikaConverter(); - Order mappedOrder = orikaConverter.convert(sourceOrder); - Assert.assertEquals(mappedOrder, sourceOrder); - + public Order orikaMapperRealLifeBenchmark() { + return ORIKA_CONVERTER.convert(sourceOrder); } @Benchmark @Group("realLifeTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void jmapperRealLifeBenchmark() { - JMapperConverter jmapperConverter = new JMapperConverter(); - Order mappedOrder = jmapperConverter.convert(sourceOrder); - Assert.assertEquals(mappedOrder, sourceOrder); + public Order jmapperRealLifeBenchmark() { + return JMAPPER_CONVERTER.convert(sourceOrder); } @Benchmark @Group("realLifeTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void modelMapperRealLifeBenchmark() { - ModelMapperConverter modelMapperConverter = new ModelMapperConverter(); - Order mappedOrder = modelMapperConverter.convert(sourceOrder); - Assert.assertEquals(mappedOrder, sourceOrder); - } - - - @Benchmark - @Group("realLifeTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void dozerMapperRealLifeBenchmark() { - DozerConverter dozerConverter = new DozerConverter(); - Order mappedOrder = dozerConverter.convert(sourceOrder); - Assert.assertEquals(mappedOrder, sourceOrder); - + public Order modelMapperRealLifeBenchmark() { + return MODEL_MAPPER_CONVERTER.convert(sourceOrder); } @Benchmark @Group("realLifeTest") - @Fork(value = 1, warmups = 1) - @BenchmarkMode(Mode.All) - public void mapStructRealLifeMapperBenchmark() { - MapStructConverter converter = MapStructConverter.MAPPER; - Order mappedOrder = converter.convert(sourceOrder); - Assert.assertEquals(mappedOrder, sourceOrder); + public Order dozerMapperRealLifeBenchmark() { + return DOZER_CONVERTER.convert(sourceOrder); + } + + @Benchmark + @Group("realLifeTest") + public Order mapStructRealLifeMapperBenchmark() { + return MapStructConverter.MAPPER.convert(sourceOrder); } @Benchmark @Group("simpleTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void orikaMapperSimpleBenchmark() { - OrikaConverter orikaConverter = new OrikaConverter(); - DestinationCode mappedCode = orikaConverter.convert(sourceCode); - Assert.assertEquals(mappedCode.getCode(), sourceCode.getCode()); - + public DestinationCode orikaMapperSimpleBenchmark() { + return ORIKA_CONVERTER.convert(sourceCode); } @Benchmark @Group("simpleTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void jmapperSimpleBenchmark() { - JMapperConverter jmapperConverter = new JMapperConverter(); - DestinationCode mappedCode = jmapperConverter.convert(sourceCode); - Assert.assertEquals(mappedCode.getCode(), sourceCode.getCode()); + public DestinationCode jmapperSimpleBenchmark() { + return JMAPPER_CONVERTER.convert(sourceCode); } @Benchmark @Group("simpleTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void modelMapperBenchmark() { - ModelMapperConverter modelMapperConverter = new ModelMapperConverter(); - DestinationCode mappedCode = modelMapperConverter.convert(sourceCode); - Assert.assertEquals(mappedCode.getCode(), sourceCode.getCode()); - } - - - @Benchmark - @Group("simpleTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void dozerMapperSimpleBenchmark() { - DozerConverter dozerConverter = new DozerConverter(); - Order mappedOrder = dozerConverter.convert(sourceOrder); - Assert.assertEquals(mappedOrder, sourceOrder); - + public DestinationCode modelMapperBenchmark() { + return MODEL_MAPPER_CONVERTER.convert(sourceCode); } @Benchmark @Group("simpleTest") - @Fork(value = 1, warmups = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - @BenchmarkMode(Mode.All) - public void mapStructMapperSimpleBenchmark() { - MapStructConverter converter = MapStructConverter.MAPPER; - DestinationCode mappedCode = converter.convert(sourceCode); - Assert.assertEquals(mappedCode.getCode(), sourceCode.getCode()); + public DestinationCode dozerMapperSimpleBenchmark() { + return DOZER_CONVERTER.convert(sourceCode); } - + @Benchmark + @Group("simpleTest") + public DestinationCode mapStructMapperSimpleBenchmark() { + return MapStructConverter.MAPPER.convert(sourceCode); + } } diff --git a/persistence-modules/README.md b/persistence-modules/README.md index dde4558387..8f8c3eb13d 100644 --- a/persistence-modules/README.md +++ b/persistence-modules/README.md @@ -9,3 +9,4 @@ - [Introduction to Lettuce – the Java Redis Client](http://www.baeldung.com/java-redis-lettuce) - [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging) - [A Guide to Jdbi](http://www.baeldung.com/jdbi) +- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) diff --git a/persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiTest.java b/persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiIntegrationTest.java similarity index 99% rename from persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiTest.java rename to persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiIntegrationTest.java index 503bf90fdb..dbc8a396ce 100644 --- a/persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiTest.java +++ b/persistence-modules/java-jdbi/src/test/java/com/baeldung/persistence/jdbi/JdbiIntegrationTest.java @@ -17,7 +17,7 @@ import java.util.stream.Stream; import static org.junit.Assert.*; -public class JdbiTest { +public class JdbiIntegrationTest { @Test public void whenJdbiCreated_thenSuccess() { diff --git a/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java index 1862d6b035..860ca0927a 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/RedissonConfigurationIntegrationTest.java @@ -27,7 +27,9 @@ public class RedissonConfigurationIntegrationTest { @AfterClass public static void destroy() { redisServer.stop(); - client.shutdown(); + if (client != null) { + client.shutdown(); + } } @Test diff --git a/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java b/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java index 766963e5cf..53d77c2699 100644 --- a/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java +++ b/persistence-modules/redis/src/test/java/com/baeldung/RedissonIntegrationTest.java @@ -37,7 +37,9 @@ public class RedissonIntegrationTest { @AfterClass public static void destroy() { redisServer.stop(); - client.shutdown(); + if (client != null) { + client.shutdown(); + } } @Test diff --git a/persistence-modules/spring-data-cassandra/pom.xml b/persistence-modules/spring-data-cassandra/pom.xml index 84165564ba..b11a1fd07b 100644 --- a/persistence-modules/spring-data-cassandra/pom.xml +++ b/persistence-modules/spring-data-cassandra/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../../parent-spring + ../../parent-spring-4 @@ -23,7 +23,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -34,7 +34,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -76,7 +76,6 @@ UTF-8 - 4.3.4.RELEASE 1.3.2.RELEASE 2.1.5 2.1.9.2 diff --git a/persistence-modules/spring-data-dynamodb/pom.xml b/persistence-modules/spring-data-dynamodb/pom.xml index b115c0e087..b1b7c8237b 100644 --- a/persistence-modules/spring-data-dynamodb/pom.xml +++ b/persistence-modules/spring-data-dynamodb/pom.xml @@ -9,10 +9,10 @@ This is simple boot application for Spring boot actuator test - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Address.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Address.java new file mode 100644 index 0000000000..b62889208c --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Address.java @@ -0,0 +1,34 @@ +package com.baeldung.eclipselink.springdata.pessimisticlocking; + +import javax.persistence.Embeddable; + +@Embeddable +public class Address { + + private String country; + private String city; + + public Address(String country, String city) { + this.country = country; + this.city = city; + } + + public Address() { + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } +} diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Course.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Course.java new file mode 100644 index 0000000000..8d90659f3e --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Course.java @@ -0,0 +1,50 @@ +package com.baeldung.eclipselink.springdata.pessimisticlocking; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinTable; +import javax.persistence.ManyToOne; + +@Entity +public class Course { + + @Id + private Long courseId; + private String name; + @ManyToOne + @JoinTable(name = "student_course") + private Student student; + + public Course(Long courseId, String name, Student student) { + this.courseId = courseId; + this.name = name; + this.student = student; + } + + public Course() { + } + + public Long getCourseId() { + return courseId; + } + + public void setCourseId(Long courseId) { + this.courseId = courseId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Student getStudent() { + return student; + } + + public void setStudent(Student students) { + this.student = students; + } +} diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Customer.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Customer.java new file mode 100644 index 0000000000..f06a676de8 --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Customer.java @@ -0,0 +1,61 @@ +package com.baeldung.eclipselink.springdata.pessimisticlocking; + +import javax.persistence.CollectionTable; +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.Id; +import java.util.List; + +@Entity +public class Customer { + + @Id + private Long customerId; + private String name; + private String lastName; + @ElementCollection + @CollectionTable(name = "customer_address") + private List
addressList; + + public Customer() { + } + + public Customer(Long customerId, String name, String lastName, List
addressList) { + this.customerId = customerId; + this.name = name; + this.lastName = lastName; + this.addressList = addressList; + } + + public Long getCustomerId() { + return customerId; + } + + public void setCustomerId(Long customerId) { + this.customerId = customerId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public List
getAddressList() { + return addressList; + } + + public void setAddressList(List
addressList) { + this.addressList = addressList; + } +} diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Employee.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Employee.java new file mode 100644 index 0000000000..d09b123225 --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Employee.java @@ -0,0 +1,27 @@ +package com.baeldung.eclipselink.springdata.pessimisticlocking; + +import javax.persistence.Entity; +import java.math.BigDecimal; + +@Entity +public class Employee extends Individual { + + private BigDecimal salary; + + public Employee(Long id, String name, String lastName, BigDecimal salary) { + super(id, name, lastName); + this.salary = salary; + } + + public Employee() { + super(); + } + + public BigDecimal getSalary() { + return salary; + } + + public void setSalary(BigDecimal average) { + this.salary = average; + } +} diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Individual.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Individual.java new file mode 100644 index 0000000000..7edaaace54 --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Individual.java @@ -0,0 +1,49 @@ +package com.baeldung.eclipselink.springdata.pessimisticlocking; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; + +@Entity +@Inheritance(strategy = InheritanceType.JOINED) +public class Individual { + + @Id + private Long id; + private String name; + private String lastName; + + public Individual(Long id, String name, String lastName) { + this.id = id; + this.name = name; + this.lastName = lastName; + } + + public Individual() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } +} diff --git a/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Student.java b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Student.java new file mode 100644 index 0000000000..f613aab0f6 --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/main/java/com/baeldung/eclipselink/springdata/pessimisticlocking/Student.java @@ -0,0 +1,48 @@ +package com.baeldung.eclipselink.springdata.pessimisticlocking; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import java.util.List; + +@Entity +public class Student { + + @Id + private Long id; + private String name; + @OneToMany(mappedBy = "student") + private List courses; + + public Student(Long id, String name) { + this.id = id; + this.name = name; + } + + public Student() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getCourses() { + return courses; + } + + public void setCourses(List courses) { + this.courses = courses; + } +} diff --git a/persistence-modules/spring-data-eclipselink/src/main/resources/application.properties b/persistence-modules/spring-data-eclipselink/src/main/resources/application.properties index 549c0b4ada..5874482e7a 100644 --- a/persistence-modules/spring-data-eclipselink/src/main/resources/application.properties +++ b/persistence-modules/spring-data-eclipselink/src/main/resources/application.properties @@ -1,2 +1,2 @@ -spring.datasource.url=jdbc:h2:mem:test +spring.datasource.url=jdbc:h2:mem:test;MVCC=FALSE;LOCK_TIMEOUT=100; spring.jpa.show-sql=true \ No newline at end of file diff --git a/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/pessimisticlocking/PessimisticLockScopesIntegrationTest.java b/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/pessimisticlocking/PessimisticLockScopesIntegrationTest.java new file mode 100644 index 0000000000..6ee40fac9a --- /dev/null +++ b/persistence-modules/spring-data-eclipselink/src/test/java/com/baeldung/eclipselink/springdata/pessimisticlocking/PessimisticLockScopesIntegrationTest.java @@ -0,0 +1,118 @@ +package com.baeldung.eclipselink.springdata.pessimisticlocking; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.persistence.*; +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class PessimisticLockScopesIntegrationTest { + + @Autowired + EntityManagerFactory entityManagerFactory; + + @Test + public void givenEntityWithJoinInheritance_whenLock_thenNormalAndExtendScopesLockParentAndChildEntity() { + EntityManager em = getEntityManagerWithOpenTransaction(); + Employee employee = new Employee(1L, "JOE", "DOE", new BigDecimal(4.5)); + em.persist(employee); + em.getTransaction() + .commit(); + em.close(); + + // NORMAL SCOPE + EntityManager em2 = getEntityManagerWithOpenTransaction(); + Employee foundEmployee = em2.find(Employee.class, 1L, LockModeType.PESSIMISTIC_WRITE); + em2.getTransaction() + .rollback(); + + // EXTENDED SCOPE + Map map = new HashMap<>(); + map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED); + + EntityManager em3 = getEntityManagerWithOpenTransaction(); + foundEmployee = em3.find(Employee.class, 1L, LockModeType.PESSIMISTIC_WRITE, map); + em3.getTransaction() + .rollback(); + + em2.close(); + em3.close(); + } + + @Test + public void givenEntityWithElementCollection_whenLock_thenExtendScopeLocksAlsoCollectionTable() { + EntityManager em = getEntityManagerWithOpenTransaction(); + Address address = new Address("Poland", "Warsaw"); + Customer customer = new Customer(1L, "JOHN", "SMITH", Arrays.asList(address)); + em.persist(customer); + em.getTransaction() + .commit(); + em.close(); + + // NORMAL SCOPE + EntityManager em2 = getEntityManagerWithOpenTransaction(); + Customer foundCustomer = em2.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE); + em2.getTransaction() + .rollback(); + + // EXTENDED SCOPE + Map map = new HashMap<>(); + map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED); + + EntityManager em3 = getEntityManagerWithOpenTransaction(); + foundCustomer = em3.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE, map); + em3.getTransaction() + .rollback(); + + em2.close(); + em3.close(); + } + + @Test + public void givenEclipseEntityWithOneToMany_whenLock_thenExtendedLockAlsoJoinTable() { + EntityManager em = getEntityManagerWithOpenTransaction(); + Student student = new Student(1L, "JOE"); + Course course = new Course(1L, "COURSE", student); + student.setCourses(Arrays.asList(course)); + em.persist(course); + em.persist(student); + em.getTransaction() + .commit(); + em.close(); + + // NORMAL SCOPE + EntityManager em2 = getEntityManagerWithOpenTransaction(); + Course foundCourse = em2.find(Course.class, 1L, LockModeType.PESSIMISTIC_WRITE); + em2.getTransaction() + .rollback(); + + // EXTENDED SCOPE + Map map = new HashMap<>(); + map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED); + + EntityManager em3 = getEntityManagerWithOpenTransaction(); + foundCourse = em3.find(Course.class, 1L, LockModeType.PESSIMISTIC_WRITE, map); + em3.getTransaction() + .rollback(); + + em2.close(); + em3.close(); + } + + protected EntityManager getEntityManagerWithOpenTransaction() { + EntityManager entityManager = entityManagerFactory.createEntityManager(); + entityManager.getTransaction() + .begin(); + return entityManager; + } +} diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index 26d5c6bddf..c5e0049e83 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-spring + parent-spring-5 0.0.1-SNAPSHOT - ../../parent-spring + ../../parent-spring-5 @@ -74,7 +74,6 @@ UTF-8 - 5.0.3.RELEASE 2.0.3.RELEASE 3.2.4 2.9.0 diff --git a/persistence-modules/spring-data-solr/pom.xml b/persistence-modules/spring-data-solr/pom.xml index f1c20344c1..036b40a7ed 100644 --- a/persistence-modules/spring-data-solr/pom.xml +++ b/persistence-modules/spring-data-solr/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../../parent-spring + ../../parent-spring-4 @@ -47,7 +47,6 @@ UTF-8 - 4.3.4.RELEASE 2.0.5.RELEASE diff --git a/persistence-modules/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md index cb71d386e2..02d4306ecb 100644 --- a/persistence-modules/spring-jpa/README.md +++ b/persistence-modules/spring-jpa/README.md @@ -22,6 +22,7 @@ - [Obtaining Auto-generated Keys in Spring JDBC](http://www.baeldung.com/spring-jdbc-autogenerated-keys) - [Transactions with Spring 4 and JPA](http://www.baeldung.com/transaction-configuration-with-jpa-and-spring) - [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) +- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/persistence-modules/spring-jpa/pom.xml b/persistence-modules/spring-jpa/pom.xml index 065b29b26b..c6762df54b 100644 --- a/persistence-modules/spring-jpa/pom.xml +++ b/persistence-modules/spring-jpa/pom.xml @@ -1,7 +1,6 @@ 4.0.0 - com.baeldung spring-jpa 0.1-SNAPSHOT war diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/MyUtilityRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/MyUtilityRepository.java new file mode 100644 index 0000000000..5fe54b80d9 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/MyUtilityRepository.java @@ -0,0 +1,14 @@ +package org.baeldung.annotations; + +import java.io.Serializable; +import java.util.Optional; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.NoRepositoryBean; + +@NoRepositoryBean +public interface MyUtilityRepository extends CrudRepository { + + Optional findById(ID id); + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/Person.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/Person.java new file mode 100644 index 0000000000..309a4f43e1 --- /dev/null +++ b/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/Person.java @@ -0,0 +1,54 @@ +package org.baeldung.annotations; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.NamedStoredProcedureQueries; +import javax.persistence.NamedStoredProcedureQuery; +import javax.persistence.ParameterMode; +import javax.persistence.StoredProcedureParameter; + +import org.baeldung.persistence.multiple.model.user.User; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.Transient; + +@Entity +@NamedStoredProcedureQueries({ + @NamedStoredProcedureQuery( + name = "count_by_name", + procedureName = "person.count_by_name", + parameters = { + @StoredProcedureParameter( + mode = ParameterMode.IN, + name = "name", + type = String.class), + @StoredProcedureParameter( + mode = ParameterMode.OUT, + name = "count", + type = Long.class) + }) +}) +public class Person { + + @Id + private Long id; + + @Transient + private int age; + + @CreatedBy + private User creator; + + @LastModifiedBy + private User modifier; + + @CreatedDate + private Date createdAt; + + @LastModifiedBy + private Date modifiedAt; + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/PersonRepository.java b/persistence-modules/spring-jpa/src/main/java/org/baeldung/annotations/PersonRepository.java new file mode 100644 index 0000000000..58558860ff --- /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) + int 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 bda4a760db..2076fbcff0 100644 --- a/pom.xml +++ b/pom.xml @@ -9,14 +9,16 @@ pom - parent-boot-5 + parent-boot-1 parent-boot-2 - parent-spring + parent-spring-4 + parent-spring-5 parent-java asm atomix apache-cayenne aws + aws-lambda akka-streams algorithms annotations @@ -30,6 +32,7 @@ apache-opennlp autovalue axon + azure bootique cdi @@ -59,7 +62,7 @@ guava-modules/guava-21 guice disruptor - handling-spring-static-resources + spring-static-resources hazelcast hbase @@ -95,13 +98,13 @@ logging-modules/log-mdc logging-modules/log4j logging-modules/log4j2 - logging-modules/log4j2-programmatic-configuration logging-modules/logback lombok mapstruct metrics maven mesos-marathon + msf4j testing-modules/mockito testing-modules/mockito-2 testing-modules/mocks @@ -142,7 +145,9 @@ spring-boot-keycloak spring-boot-bootstrap spring-boot-admin + spring-boot-ops spring-boot-security + spring-boot-mvc spring-cloud-data-flow spring-cloud spring-core @@ -153,6 +158,7 @@ spring-data-couchbase-2 persistence-modules/spring-data-dynamodb spring-data-elasticsearch + spring-data-keyvalue spring-data-mongodb persistence-modules/spring-data-neo4j persistence-modules/spring-data-redis @@ -180,7 +186,6 @@ spring-mvc-forms-jsp spring-mvc-forms-thymeleaf spring-mvc-java - spring-mvc-tiles spring-mvc-velocity spring-mvc-webflow spring-mvc-xml @@ -246,6 +251,7 @@ persistence-modules/liquibase spring-boot-property-exp testing-modules/mockserver + testing-modules/test-containers undertow vertx-and-rxjava saas @@ -258,6 +264,12 @@ jersey java-spi performance-tests + twilio + spring-boot-ctx-fluent + java-ee-8-security-api + spring-webflux-amqp + antlr + maven-archetype @@ -341,6 +353,7 @@ true **/*IntegrationTest.java + **/*IntTest.java **/*LongRunningUnitTest.java **/*ManualTest.java **/JdbcTest.java @@ -369,9 +382,9 @@ - 5 - true - false + 5 + false + true true true true @@ -466,6 +479,7 @@ **/*IntegrationTest.java + **/*IntTest.java @@ -529,5 +543,4 @@ 1.3 5.0.2 - - \ No newline at end of file + 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 99% 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/resteasy/pom.xml b/resteasy/pom.xml index 61c099f110..aca9fe3635 100644 --- a/resteasy/pom.xml +++ b/resteasy/pom.xml @@ -98,6 +98,7 @@ **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableTest.java b/rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableIntegrationTest.java similarity index 93% rename from rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableIntegrationTest.java index 031ff0c5bb..5c28c53d11 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/ConnectableObservableIntegrationTest.java @@ -10,7 +10,7 @@ import static com.jayway.awaitility.Awaitility.await; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; -public class ConnectableObservableTest { +public class ConnectableObservableIntegrationTest { @Test public void givenConnectableObservable_whenConnect_thenGetMessage() throws InterruptedException { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/FlowableTest.java b/rxjava/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java similarity index 99% rename from rxjava/src/test/java/com/baeldung/rxjava/FlowableTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java index b9d1d64c24..9fee2bc005 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/FlowableTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/FlowableIntegrationTest.java @@ -18,7 +18,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -public class FlowableTest { +public class FlowableIntegrationTest { @Test public void whenFlowableIsCreated_thenItIsProperlyInitialized() { Flowable integerFlowable = Flowable.just(1, 2, 3, 4); diff --git a/rxjava/src/test/java/com/baeldung/rxjava/MaybeTest.java b/rxjava/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java similarity index 97% rename from rxjava/src/test/java/com/baeldung/rxjava/MaybeTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java index 501ee1f196..d02fe990c0 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/MaybeTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/MaybeUnitTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import io.reactivex.Flowable; import io.reactivex.Maybe; -public class MaybeTest { +public class MaybeUnitTest { @Test public void whenEmitsSingleValue_thenItIsObserved() { Maybe maybe = Flowable.just(1, 2, 3, 4, 5) diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ObservableTest.java b/rxjava/src/test/java/com/baeldung/rxjava/ObservableUnitTest.java similarity index 99% rename from rxjava/src/test/java/com/baeldung/rxjava/ObservableTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/ObservableUnitTest.java index beb2cbeed3..22e52f73c4 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/ObservableTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/ObservableUnitTest.java @@ -6,7 +6,7 @@ import rx.Observable; import static com.baeldung.rxjava.ObservableImpl.getTitle; import static junit.framework.Assert.assertTrue; -public class ObservableTest { +public class ObservableUnitTest { private String result = ""; diff --git a/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementTest.java b/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementUnitTest.java similarity index 94% rename from rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementUnitTest.java index 81be84fd0d..145194d374 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/ResourceManagementUnitTest.java @@ -5,7 +5,7 @@ import rx.Observable; import static junit.framework.Assert.assertTrue; -public class ResourceManagementTest { +public class ResourceManagementUnitTest { @Test public void givenResource_whenUsingOberservable_thenCreatePrintDisposeResource() throws InterruptedException { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/RxRelayTest.java b/rxjava/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java similarity index 99% rename from rxjava/src/test/java/com/baeldung/rxjava/RxRelayTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java index 091e4df138..9fc5827d86 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/RxRelayTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/RxRelayIntegrationTest.java @@ -9,7 +9,7 @@ import org.junit.Test; import java.util.concurrent.TimeUnit; -public class RxRelayTest { +public class RxRelayIntegrationTest { @Test public void whenObserverSubscribedToPublishRelay_thenItReceivesEmittedEvents () { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SingleTest.java b/rxjava/src/test/java/com/baeldung/rxjava/SingleUnitTest.java similarity index 95% rename from rxjava/src/test/java/com/baeldung/rxjava/SingleTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/SingleUnitTest.java index 1352841ed9..8c39034cb9 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/SingleTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/SingleUnitTest.java @@ -6,7 +6,7 @@ import rx.Single; import static junit.framework.Assert.assertTrue; -public class SingleTest { +public class SingleUnitTest { @Test public void givenSingleObservable_whenSuccess_thenGetMessage() throws InterruptedException { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/SubjectTest.java b/rxjava/src/test/java/com/baeldung/rxjava/SubjectUnitTest.java similarity index 95% rename from rxjava/src/test/java/com/baeldung/rxjava/SubjectTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/SubjectUnitTest.java index 628b1e5476..a678d83667 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/SubjectTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/SubjectUnitTest.java @@ -5,7 +5,7 @@ import rx.subjects.PublishSubject; import static junit.framework.Assert.assertTrue; -public class SubjectTest { +public class SubjectUnitTest { @Test public void givenSubjectAndTwoSubscribers_whenSubscribeOnSubject_thenSubscriberBeginsToAdd() { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsIntegrationTest.java similarity index 99% rename from rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsIntegrationTest.java index 0b38f0387b..a11d0ff8c3 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/UtilityOperatorsIntegrationTest.java @@ -14,7 +14,7 @@ import java.util.concurrent.TimeUnit; import static com.jayway.awaitility.Awaitility.await; import static org.junit.Assert.assertTrue; -public class UtilityOperatorsTest { +public class UtilityOperatorsIntegrationTest { private int emittedTotal = 0; private int receivedTotal = 0; diff --git a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsIntegrationTest.java similarity index 99% rename from rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsIntegrationTest.java index be0f390b67..67f4c51cbe 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaFilterOperatorsIntegrationTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import rx.Observable; import rx.observers.TestSubscriber; -public class RxJavaFilterOperatorsTest { +public class RxJavaFilterOperatorsIntegrationTest { @Test public void givenRangeObservable_whenFilteringItems_thenOddItemsAreFiltered() { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsIntegrationTest.java similarity index 98% rename from rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsIntegrationTest.java index eca39b17bf..eca65e728e 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaSkipOperatorsIntegrationTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import rx.Observable; import rx.observers.TestSubscriber; -public class RxJavaSkipOperatorsTest { +public class RxJavaSkipOperatorsIntegrationTest { @Test public void givenRangeObservable_whenSkipping_thenFirstFourItemsAreSkipped() { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsIntegrationTest.java similarity index 99% rename from rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsIntegrationTest.java index 63076cbc4a..d9ec6c3798 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/filters/RxJavaTimeFilteringOperatorsIntegrationTest.java @@ -9,7 +9,7 @@ import rx.Observable; import rx.observers.TestSubscriber; import rx.schedulers.TestScheduler; -public class RxJavaTimeFilteringOperatorsTest { +public class RxJavaTimeFilteringOperatorsIntegrationTest { @Test public void givenTimedObservable_whenSampling_thenOnlySampleItemsAreEmitted() { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java index 477a2a1cb8..ec766ac7ac 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/AutomapInterfaceIntegrationTest.java @@ -18,26 +18,27 @@ public class AutomapInterfaceIntegrationTest { private ConnectionProvider connectionProvider = Connector.connectionProvider; private Database db = Database.from(connectionProvider); - private Observable create = null; + private Observable truncate = null; private Observable insert1, insert2 = null; @Before public void setup() { - create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))") + Observable create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))") .count(); + truncate = db.update("TRUNCATE TABLE EMPLOYEE") + .dependsOn(create) + .count(); insert1 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'Alan')") - .dependsOn(create) + .dependsOn(truncate) .count(); insert2 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(2, 'Sarah')") - .dependsOn(create) + .dependsOn(insert1) .count(); } @Test public void whenSelectFromTableAndAutomap_thenCorrect() { List employees = db.select("select id, name from EMPLOYEE") - .dependsOn(create) - .dependsOn(insert1) .dependsOn(insert2) .autoMap(Employee.class) .toList() @@ -57,7 +58,7 @@ public class AutomapInterfaceIntegrationTest { @After public void close() { db.update("DROP TABLE EMPLOYEE") - .dependsOn(create); + .dependsOn(truncate); connectionProvider.close(); } } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java index 5f445234d7..2fb3b3abd7 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/BasicQueryTypesIntegrationTest.java @@ -22,24 +22,24 @@ public class BasicQueryTypesIntegrationTest { @Test public void whenCreateTableAndInsertRecords_thenCorrect() { - create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))") + create = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE_TABLE(id int primary key, name varchar(255))") .count(); - Observable insert1 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'John')") + Observable insert1 = db.update("INSERT INTO EMPLOYEE_TABLE(id, name) VALUES(1, 'John')") .dependsOn(create) .count(); - Observable update = db.update("UPDATE EMPLOYEE SET name = 'Alan' WHERE id = 1") + Observable update = db.update("UPDATE EMPLOYEE_TABLE SET name = 'Alan' WHERE id = 1") .dependsOn(create) .count(); - Observable insert2 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(2, 'Sarah')") + Observable insert2 = db.update("INSERT INTO EMPLOYEE_TABLE(id, name) VALUES(2, 'Sarah')") .dependsOn(create) .count(); - Observable insert3 = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(3, 'Mike')") + Observable insert3 = db.update("INSERT INTO EMPLOYEE_TABLE(id, name) VALUES(3, 'Mike')") .dependsOn(create) .count(); - Observable delete = db.update("DELETE FROM EMPLOYEE WHERE id = 2") + Observable delete = db.update("DELETE FROM EMPLOYEE_TABLE WHERE id = 2") .dependsOn(create) .count(); - List names = db.select("select name from EMPLOYEE where id < ?") + List names = db.select("select name from EMPLOYEE_TABLE where id < ?") .parameter(3) .dependsOn(create) .dependsOn(insert1) @@ -57,7 +57,7 @@ public class BasicQueryTypesIntegrationTest { @After public void close() { - db.update("DROP TABLE EMPLOYEE") + db.update("DROP TABLE EMPLOYEE_TABLE") .dependsOn(create); connectionProvider.close(); } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java index 189bca4adb..284ecc4078 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/InsertClobIntegrationTest.java @@ -27,7 +27,7 @@ public class InsertClobIntegrationTest { @Before public void setup() throws IOException { - create = db.update("CREATE TABLE IF NOT EXISTS SERVERLOG (id int primary key, document CLOB)") + create = db.update("CREATE TABLE IF NOT EXISTS SERVERLOG_TABLE (id int primary key, document CLOB)") .count(); InputStream actualInputStream = new FileInputStream("src/test/resources/actual_clob"); @@ -35,7 +35,7 @@ public class InsertClobIntegrationTest { InputStream expectedInputStream = new FileInputStream("src/test/resources/expected_clob"); this.expectedDocument = Utils.getStringFromInputStream(expectedInputStream); - this.insert = db.update("insert into SERVERLOG(id,document) values(?,?)") + this.insert = db.update("insert into SERVERLOG_TABLE(id,document) values(?,?)") .parameter(1) .parameter(Database.toSentinelIfNull(actualDocument)) .dependsOn(create) @@ -44,7 +44,7 @@ public class InsertClobIntegrationTest { @Test public void whenSelectCLOB_thenCorrect() throws IOException { - db.select("select document from SERVERLOG where id = 1") + db.select("select document from SERVERLOG_TABLE where id = 1") .dependsOn(create) .dependsOn(insert) .getAs(String.class) @@ -56,7 +56,7 @@ public class InsertClobIntegrationTest { @After public void close() { - db.update("DROP TABLE SERVERLOG") + db.update("DROP TABLE SERVERLOG_TABLE") .dependsOn(create); connectionProvider.close(); } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java index 2018a9427c..c9e06a347f 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/ReturnKeysIntegrationTest.java @@ -22,14 +22,14 @@ public class ReturnKeysIntegrationTest { @Before public void setup() { begin = db.beginTransaction(); - createStatement = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int auto_increment primary key, name varchar(255))") + createStatement = db.update("CREATE TABLE IF NOT EXISTS EMPLOYEE_SAMPLE(id int auto_increment primary key, name varchar(255))") .dependsOn(begin) .count(); } @Test public void whenInsertAndReturnGeneratedKey_thenCorrect() { - Integer key = db.update("INSERT INTO EMPLOYEE(name) VALUES('John')") + Integer key = db.update("INSERT INTO EMPLOYEE_SAMPLE(name) VALUES('John')") .dependsOn(createStatement) .returnGeneratedKeys() .getAs(Integer.class) @@ -41,7 +41,7 @@ public class ReturnKeysIntegrationTest { @After public void close() { - db.update("DROP TABLE EMPLOYEE") + db.update("DROP TABLE EMPLOYEE_SAMPLE") .dependsOn(createStatement); connectionProvider.close(); } diff --git a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java index 4e24d7f10e..d5f09be23c 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/jdbc/TransactionIntegrationTest.java @@ -24,8 +24,11 @@ public class TransactionIntegrationTest { .update("CREATE TABLE IF NOT EXISTS EMPLOYEE(id int primary key, name varchar(255))") .dependsOn(begin) .count(); + Observable truncateStatement = db.update("TRUNCATE TABLE EMPLOYEE") + .dependsOn(createStatement) + .count(); Observable insertStatement = db.update("INSERT INTO EMPLOYEE(id, name) VALUES(1, 'John')") - .dependsOn(createStatement) + .dependsOn(truncateStatement) .count(); Observable updateStatement = db.update("UPDATE EMPLOYEE SET name = 'Tom' WHERE id = 1") .dependsOn(insertStatement) diff --git a/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingTest.java b/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java similarity index 98% rename from rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java index b1d711ab39..304dc98274 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/onerror/ExceptionHandlingIntegrationTest.java @@ -9,7 +9,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.assertTrue; -public class ExceptionHandlingTest { +public class ExceptionHandlingIntegrationTest { private Error UNKNOWN_ERROR = new Error("unknown error"); private Exception UNKNOWN_EXCEPTION = new Exception("unknown exception"); diff --git a/rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryTest.java b/rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java similarity index 99% rename from rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java index 3cc72056ba..746e3cfbf6 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/onerror/OnErrorRetryIntegrationTest.java @@ -9,7 +9,7 @@ import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertTrue; -public class OnErrorRetryTest { +public class OnErrorRetryIntegrationTest { private Error UNKNOWN_ERROR = new Error("unknown error"); diff --git a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsUnitTest.java similarity index 99% rename from rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsUnitTest.java index 6733aa08c5..f0d7a9a4e4 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxAggregateOperatorsUnitTest.java @@ -11,7 +11,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; -public class RxAggregateOperatorsTest { +public class RxAggregateOperatorsUnitTest { @Test public void givenTwoObservable_whenConcatenatingThem_thenSuccessfull() { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsUnitTest.java similarity index 98% rename from rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsUnitTest.java index cd212a2e18..9390792737 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxMathematicalOperatorsUnitTest.java @@ -9,7 +9,7 @@ import java.util.Arrays; import java.util.Comparator; import java.util.List; -public class RxMathematicalOperatorsTest { +public class RxMathematicalOperatorsUnitTest { @Test public void givenRangeNumericObservable_whenCalculatingAverage_ThenSuccessfull() { diff --git a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsTest.java b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsUnitTest.java similarity index 99% rename from rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsTest.java rename to rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsUnitTest.java index 5e58b32d8b..1ffc9b3ca2 100644 --- a/rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsTest.java +++ b/rxjava/src/test/java/com/baeldung/rxjava/operators/RxStringOperatorsUnitTest.java @@ -12,7 +12,7 @@ import rx.observables.StringObservable; import rx.observers.TestSubscriber; -public class RxStringOperatorsTest +public class RxStringOperatorsUnitTest { @Test diff --git a/spring-4/src/main/java/com/baeldung/flips/model/Foo.java b/spring-4/src/main/java/com/baeldung/flips/model/Foo.java index d98abb79a9..be15bee15c 100644 --- a/spring-4/src/main/java/com/baeldung/flips/model/Foo.java +++ b/spring-4/src/main/java/com/baeldung/flips/model/Foo.java @@ -1,11 +1,12 @@ package com.baeldung.flips.model; import lombok.Data; +import lombok.NonNull; import lombok.RequiredArgsConstructor; @Data @RequiredArgsConstructor public class Foo { - private final String name; - private final int id; + @NonNull private final String name; + @NonNull private final int id; } diff --git a/spring-4/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java b/spring-4/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java similarity index 96% rename from spring-4/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java rename to spring-4/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java index 1b8c78e2a4..9dd4ef064a 100644 --- a/spring-4/src/test/java/com/baeldung/flips/controller/FlipControllerTest.java +++ b/spring-4/src/test/java/com/baeldung/flips/controller/FlipControllerIntegrationTest.java @@ -20,10 +20,10 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; "first.active.after=2999-03-15T00:00:00Z", "logging.level.org.flips=info" -}) +}, webEnvironment = SpringBootTest.WebEnvironment.MOCK) @AutoConfigureMockMvc @ActiveProfiles("dev") -public class FlipControllerTest { +public class FlipControllerIntegrationTest { @Autowired private MockMvc mvc; diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 06ddfb82d9..ae9ceb990a 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 @@ -145,6 +145,7 @@ false **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java @@ -174,7 +175,7 @@ - 2.9.0 + 2.9.0 UTF-8 UTF-8 1.8 diff --git a/spring-5-reactive-client/README.md b/spring-5-reactive-client/README.md index 400e343263..f94bd0b0c1 100644 --- a/spring-5-reactive-client/README.md +++ b/spring-5-reactive-client/README.md @@ -4,12 +4,3 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles - -- [Concurrent Test Execution in Spring 5](http://www.baeldung.com/spring-5-concurrent-tests) -- [Introduction to the Functional Web Framework in Spring 5](http://www.baeldung.com/spring-5-functional-web) -- [Exploring the Spring 5 MVC URL Matching Improvements](http://www.baeldung.com/spring-5-mvc-url-matching) -- [Spring 5 WebClient](http://www.baeldung.com/spring-5-webclient) -- [Spring 5 Functional Bean Registration](http://www.baeldung.com/spring-5-functional-beans) -- [The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5](http://www.baeldung.com/spring-5-junit-config) -- [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive) -- [Spring 5 Testing with @EnabledIf Annotation](https://github.com/eugenp/tutorials/tree/master/spring-5) diff --git a/spring-5-reactive-client/pom.xml b/spring-5-reactive-client/pom.xml index e9e7c7c3e3..ca1cbc475a 100644 --- a/spring-5-reactive-client/pom.xml +++ b/spring-5-reactive-client/pom.xml @@ -155,6 +155,7 @@ true **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md index 9998dbf751..df96d933ba 100644 --- a/spring-5-reactive/README.md +++ b/spring-5-reactive/README.md @@ -17,3 +17,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Boot Actuator](http://www.baeldung.com/spring-boot-actuators) - [Spring Webflux Filters](http://www.baeldung.com/spring-webflux-filters) - [Reactive Flow with MongoDB, Kotlin, and Spring WebFlux](http://www.baeldung.com/kotlin-mongodb-spring-webflux) +- [Spring Data Reactive Repositories with MongoDB](http://www.baeldung.com/spring-data-mongodb-reactive) diff --git a/spring-5-reactive/pom.xml b/spring-5-reactive/pom.xml index d17026af47..6bec7f18cc 100644 --- a/spring-5-reactive/pom.xml +++ b/spring-5-reactive/pom.xml @@ -11,17 +11,13 @@ 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 - - org.springframework.boot - spring-boot-starter-data-jpa - org.springframework.boot spring-boot-starter-validation @@ -66,7 +62,6 @@ lombok compile - org.apache.geronimo.specs geronimo-json_1.1_spec @@ -89,12 +84,6 @@ spring-boot-devtools runtime - - com.h2database - h2 - runtime - - org.springframework spring-test @@ -133,16 +122,32 @@ ${junit.platform.version} test - - - org.projectlombok - lombok - org.apache.commons commons-lang3 + + org.springframework.boot + spring-boot-starter-data-mongodb-reactive + + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + test + + + io.reactivex.rxjava2 + rxjava + ${rxjava-version} + + + io.projectreactor + reactor-test + ${project-reactor-test} + test + + @@ -166,6 +171,7 @@ true **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java @@ -178,13 +184,15 @@ UTF-8 1.8 1.0.0 - 5.0.0 + 5.0.2 2.20 1.0.1.RELEASE + 2.1.12 1.1.3 1.0 1.0 4.1 + 3.1.6.RELEASE diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java index a9308124fa..e96767145e 100644 --- a/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/Spring5ReactiveApplication.java @@ -1,13 +1,25 @@ package com.baeldung.reactive; +import com.mongodb.reactivestreams.client.MongoClient; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.data.mongodb.core.ReactiveMongoTemplate; @SpringBootApplication -public class Spring5ReactiveApplication { +public class Spring5ReactiveApplication{ public static void main(String[] args) { SpringApplication.run(Spring5ReactiveApplication.class, args); } + @Autowired + MongoClient mongoClient; + + @Bean + public ReactiveMongoTemplate reactiveMongoTemplate() { + return new ReactiveMongoTemplate(mongoClient, "test"); + } + } diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/model/Account.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/model/Account.java new file mode 100644 index 0000000000..57abd80009 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/model/Account.java @@ -0,0 +1,21 @@ +package com.baeldung.reactive.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.ToString; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document +@Data +@ToString +@AllArgsConstructor +@NoArgsConstructor +public class Account { + + @Id + private String id; + private String owner; + private Double value; +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java new file mode 100644 index 0000000000..8798c13772 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountCrudRepository.java @@ -0,0 +1,15 @@ +package com.baeldung.reactive.repository; + +import com.baeldung.reactive.model.Account; +import org.springframework.data.repository.reactive.ReactiveCrudRepository; +import org.springframework.stereotype.Repository; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@Repository +public interface AccountCrudRepository extends ReactiveCrudRepository { + + public Flux findAllByValue(Double value); + + public Mono findFirstByOwner(Mono owner); +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java new file mode 100644 index 0000000000..5c09e4a264 --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountMongoRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.reactive.repository; + +import com.baeldung.reactive.model.Account; +import org.springframework.data.mongodb.repository.ReactiveMongoRepository; + +public interface AccountMongoRepository extends ReactiveMongoRepository { +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java new file mode 100644 index 0000000000..6afe92a21b --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/repository/AccountRxJavaRepository.java @@ -0,0 +1,15 @@ +package com.baeldung.reactive.repository; + +import com.baeldung.reactive.model.Account; +import io.reactivex.Observable; +import io.reactivex.Single; +import org.springframework.data.repository.reactive.RxJava2CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface AccountRxJavaRepository extends RxJava2CrudRepository{ + + public Observable findAllByValue(Double value); + + public Single findFirstByOwner(Single owner); +} diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java b/spring-5-reactive/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java new file mode 100644 index 0000000000..9d32f34e3b --- /dev/null +++ b/spring-5-reactive/src/main/java/com/baeldung/reactive/template/AccountTemplateOperations.java @@ -0,0 +1,33 @@ +package com.baeldung.reactive.template; + +import com.baeldung.reactive.model.Account; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.mongodb.core.ReactiveMongoTemplate; +import org.springframework.data.mongodb.core.ReactiveRemoveOperation; +import org.springframework.stereotype.Service; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +@Service +public class AccountTemplateOperations { + + @Autowired + ReactiveMongoTemplate template; + + public Mono findById(String id) { + return template.findById(id, Account.class); + } + + public Flux findAll() { + return template.findAll(Account.class); + } + + public Mono save(Mono account) { + return template.save(account); + } + + public ReactiveRemoveOperation.ReactiveRemove deleteAll() { + return template.remove(Account.class); + } + +} diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/FluxUnitTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/FluxUnitTest.java index bad5fc5f22..a63d2391a1 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/FluxUnitTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/FluxUnitTest.java @@ -14,11 +14,13 @@ import reactor.core.publisher.Flux; public class FluxUnitTest { + public static final Random RANDOM = new Random(); + @Test public void whenFluxIsConstructed_thenCorrect() { final Flux flux = Flux. create(fluxSink -> { - while (true) { - fluxSink.next(new Foo(new Random().nextLong(), randomAlphabetic(6))); + for (int i = 0 ; i < 100 ; i++) { + fluxSink.next(new Foo(RANDOM.nextLong(), randomAlphabetic(6))); } }).sample(Duration.ofSeconds(1)).log(); diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java similarity index 96% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerTest.java rename to spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java index 8189802248..bb2408ea79 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/PlayerHandlerIntegrationTest.java @@ -12,7 +12,7 @@ import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -public class PlayerHandlerTest { +public class PlayerHandlerIntegrationTest { @Autowired private WebTestClient webTestClient; diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java similarity index 96% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerTest.java rename to spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java index d32a9d478f..e7d289e5c4 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerTest.java +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/filters/UserControllerIntegrationTest.java @@ -12,7 +12,7 @@ import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -public class UserControllerTest { +public class UserControllerIntegrationTest { @Autowired private WebTestClient webTestClient; diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java new file mode 100644 index 0000000000..f425826dce --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountCrudRepositoryIntegrationTest.java @@ -0,0 +1,70 @@ +package com.baeldung.reactive.repository; + + +import com.baeldung.reactive.Spring5ReactiveApplication; +import com.baeldung.reactive.model.Account; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Spring5ReactiveApplication.class) +public class AccountCrudRepositoryIntegrationTest { + + @Autowired + AccountCrudRepository repository; + + @Test + public void givenValue_whenFindAllByValue_thenFindAccount() { + repository.save(new Account(null, "Bill", 12.3)).block(); + Flux accountFlux = repository.findAllByValue(12.3); + + StepVerifier.create(accountFlux) + .assertNext(account -> { + assertEquals("Bill", account.getOwner()); + assertEquals(Double.valueOf(12.3) , account.getValue()); + assertNotNull(account.getId()); + }) + .expectComplete() + .verify(); + } + + @Test + public void givenOwner_whenFindFirstByOwner_thenFindAccount() { + repository.save(new Account(null, "Bill", 12.3)).block(); + Mono accountMono = repository.findFirstByOwner(Mono.just("Bill")); + + StepVerifier.create(accountMono) + .assertNext(account -> { + assertEquals("Bill", account.getOwner()); + assertEquals(Double.valueOf(12.3) , account.getValue()); + assertNotNull(account.getId()); + }) + .expectComplete() + .verify(); + + + + } + + @Test + public void givenAccount_whenSave_thenSaveAccount() { + Mono accountMono = repository.save(new Account(null, "Bill", 12.3)); + + StepVerifier + .create(accountMono) + .assertNext(account -> assertNotNull(account.getId())) + .expectComplete() + .verify(); + } + + +} \ No newline at end of file diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java new file mode 100644 index 0000000000..bfa6a789b2 --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountMongoRepositoryIntegrationTest.java @@ -0,0 +1,67 @@ +package com.baeldung.reactive.repository; + +import com.baeldung.reactive.Spring5ReactiveApplication; +import com.baeldung.reactive.model.Account; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.domain.Example; +import org.springframework.data.domain.ExampleMatcher; +import org.springframework.test.context.junit4.SpringRunner; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.startsWith; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Spring5ReactiveApplication.class) +public class AccountMongoRepositoryIntegrationTest { + + @Autowired + AccountMongoRepository repository; + + @Test + public void givenExample_whenFindAllWithExample_thenFindAllMacthings() { + repository.save(new Account(null, "john", 12.3)).block(); + ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("owner", startsWith()); + Example example = Example.of(new Account(null, "jo", null), matcher); + Flux accountFlux = repository.findAll(example); + + StepVerifier + .create(accountFlux) + .assertNext(account -> assertEquals("john", account.getOwner())) + .expectComplete() + .verify(); + } + + @Test + public void givenAccount_whenSave_thenSave() { + Mono accountMono = repository.save(new Account(null, "john", 12.3)); + + StepVerifier + .create(accountMono) + .assertNext(account -> assertNotNull(account.getId())) + .expectComplete() + .verify(); + } + + @Test + public void givenId_whenFindById_thenFindAccount() { + Account inserted = repository.save(new Account(null, "john", 12.3)).block(); + Mono accountMono = repository.findById(inserted.getId()); + + StepVerifier + .create(accountMono) + .assertNext(account -> { + assertEquals("john", account.getOwner()); + assertEquals(Double.valueOf(12.3), account.getValue()); + assertNotNull(account.getId()); + }) + .expectComplete() + .verify(); + } +} \ No newline at end of file diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java new file mode 100644 index 0000000000..e9b3eb1c40 --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/repository/AccountRxJavaRepositoryIntegrationTest.java @@ -0,0 +1,58 @@ +package com.baeldung.reactive.repository; + +import com.baeldung.reactive.Spring5ReactiveApplication; +import com.baeldung.reactive.model.Account; +import io.reactivex.Observable; +import io.reactivex.Single; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Spring5ReactiveApplication.class) +public class AccountRxJavaRepositoryIntegrationTest { + + @Autowired + AccountRxJavaRepository repository; + + @Test + public void givenValue_whenFindAllByValue_thenFindAccounts() throws InterruptedException { + repository.save(new Account(null, "bruno", 12.3)).blockingGet(); + Observable accountObservable = repository.findAllByValue(12.3); + + accountObservable + .test() + .await() + .assertComplete() + .assertValueAt(0, account -> { + assertEquals("bruno", account.getOwner()); + assertEquals(Double.valueOf(12.3), account.getValue()); + return true; + }); + + } + + @Test + public void givenOwner_whenFindFirstByOwner_thenFindAccount() throws InterruptedException { + repository.save(new Account(null, "bruno", 12.3)).blockingGet(); + Single accountSingle = repository.findFirstByOwner(Single.just("bruno")); + + accountSingle + .test() + .await() + .assertComplete() + .assertValueAt(0, account -> { + assertEquals("bruno", account.getOwner()); + assertEquals(Double.valueOf(12.3), account.getValue()); + assertNotNull(account.getId()); + return true; + }); + + } + +} \ No newline at end of file diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java b/spring-5-reactive/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java new file mode 100644 index 0000000000..373da0e393 --- /dev/null +++ b/spring-5-reactive/src/test/java/com/baeldung/reactive/template/AccountTemplateOperationsIntegrationTest.java @@ -0,0 +1,48 @@ +package com.baeldung.reactive.template; + +import com.baeldung.reactive.Spring5ReactiveApplication; +import com.baeldung.reactive.model.Account; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Spring5ReactiveApplication.class) +public class AccountTemplateOperationsIntegrationTest { + + @Autowired + AccountTemplateOperations accountTemplate; + + @Test + public void givenAccount_whenSave_thenSave() { + Account account = accountTemplate.save(Mono.just(new Account(null, "Raul", 12.3))).block(); + assertNotNull( account.getId() ); + } + + @Test + public void givenId_whenFindById_thenFindAccount() { + Mono accountMono = accountTemplate.save(Mono.just(new Account(null, "Raul", 12.3))); + Mono accountMonoResult = accountTemplate.findById(accountMono.block().getId()); + assertNotNull(accountMonoResult.block().getId()); + assertEquals(accountMonoResult.block().getOwner(), "Raul"); + } + + @Test + public void whenFindAll_thenFindAllAccounts() { + Account account1 = accountTemplate.save(Mono.just(new Account(null, "Raul", 12.3))).block(); + Account account2 = accountTemplate.save(Mono.just(new Account(null, "Raul Torres", 13.3))).block(); + Flux accountFlux = accountTemplate.findAll(); + List accounts = accountFlux.collectList().block(); + assertTrue(accounts.stream().anyMatch(x -> account1.getId().equals(x.getId()) )); + assertTrue(accounts.stream().anyMatch(x -> account2.getId().equals(x.getId()) )); + } + +} \ No newline at end of file diff --git a/spring-5-security/pom.xml b/spring-5-security/pom.xml index c9b16f8b88..f6d0ef8b4a 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 @@ -81,6 +81,7 @@ true **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java 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..6e66fe1e99 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 @@ -175,6 +175,7 @@ true **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java diff --git a/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java b/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java index 3e91a0354b..551ea6c84b 100644 --- a/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java +++ b/spring-5/src/main/java/com/baeldung/functional/IndexRewriteFilter.java @@ -16,8 +16,6 @@ class IndexRewriteFilter implements WebFilter { .equals("/")) { return webFilterChain.filter(serverWebExchange.mutate() .request(builder -> builder.method(request.getMethod()) - .contextPath(request.getPath() - .toString()) .path("/test")) .build()); } diff --git a/spring-5/src/main/java/com/baeldung/persistence/FooRepository.java b/spring-5/src/main/java/com/baeldung/persistence/FooRepository.java index 1f1e071158..9270d58d35 100644 --- a/spring-5/src/main/java/com/baeldung/persistence/FooRepository.java +++ b/spring-5/src/main/java/com/baeldung/persistence/FooRepository.java @@ -1,10 +1,9 @@ package com.baeldung.persistence; +import com.baeldung.web.Foo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -import com.baeldung.web.Foo; - public interface FooRepository extends JpaRepository, JpaSpecificationExecutor { } diff --git a/spring-5/src/main/java/com/baeldung/web/FooController.java b/spring-5/src/main/java/com/baeldung/web/FooController.java index 925f2b49f4..a09e628421 100644 --- a/spring-5/src/main/java/com/baeldung/web/FooController.java +++ b/spring-5/src/main/java/com/baeldung/web/FooController.java @@ -7,6 +7,7 @@ import org.springframework.http.HttpStatus; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import javax.annotation.PostConstruct; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import java.util.List; @@ -14,6 +15,11 @@ import java.util.List; @RestController("/foos") public class FooController { + @PostConstruct + public void init(){ + System.out.println("test"); + } + @Autowired private FooRepository repo; diff --git a/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java b/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java index 8b9e66213f..ecc677465e 100644 --- a/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/Example1IntegrationTest.java @@ -3,10 +3,12 @@ package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest +@EnableJpaRepositories("com.baeldung.persistence") public class Example1IntegrationTest { @Test diff --git a/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java b/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java index 6ed53ca4e9..e1d56c2fc3 100644 --- a/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/Example2IntegrationTest.java @@ -3,10 +3,12 @@ package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest +@EnableJpaRepositories("com.baeldung.persistence") public class Example2IntegrationTest { @Test diff --git a/spring-5/src/test/java/com/baeldung/Spring5ApplicationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/Spring5ApplicationIntegrationTest.java index af288c3c2d..1bbf0e3775 100644 --- a/spring-5/src/test/java/com/baeldung/Spring5ApplicationIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/Spring5ApplicationIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; @@ -7,6 +8,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest +@Ignore public class Spring5ApplicationIntegrationTest { @Test diff --git a/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java index 5392a59343..fba01726f4 100644 --- a/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java @@ -6,6 +6,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.context.support.GenericWebApplicationContext; @@ -13,6 +14,7 @@ import com.baeldung.Spring5Application; @RunWith(SpringRunner.class) @SpringBootTest(classes = Spring5Application.class) +@EnableJpaRepositories("com.baeldung.persistence") public class BeanRegistrationIntegrationTest { @Autowired diff --git a/spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java b/spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java index c52e18ef7f..45012a95aa 100644 --- a/spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java +++ b/spring-5/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java @@ -2,6 +2,7 @@ package com.baeldung.jdbc.autogenkey; import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -15,6 +16,7 @@ import com.baeldung.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate; import com.baeldung.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert; @RunWith(SpringRunner.class) +@Ignore public class GetAutoGenKeyByJDBC { @Configuration diff --git a/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java index 756b303f3b..f4749c0d33 100644 --- a/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java @@ -5,6 +5,7 @@ import static org.junit.Assert.assertTrue; import java.math.BigDecimal; import java.time.LocalDate; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -16,18 +17,15 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = Spring5Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@Ignore public class JsonbIntegrationTest { - @Value("${security.user.name}") - private String username; - @Value("${security.user.password}") - private String password; @Autowired private TestRestTemplate template; @Test public void givenId_whenUriIsPerson_thenGetPerson() { - ResponseEntity response = template.withBasicAuth(username, password) + ResponseEntity response = template .getForEntity("/person/1", Person.class); Person person = response.getBody(); assertTrue(person.equals(new Person(2, "Jhon", "jhon1@test.com", 0, LocalDate.of(2019, 9, 9), BigDecimal.valueOf(1500.0)))); @@ -35,8 +33,8 @@ public class JsonbIntegrationTest { @Test public void whenSendPostAPerson_thenGetOkStatus() { - ResponseEntity response = template.withBasicAuth(username, password) - .postForEntity("/person", "{\"birthDate\":\"07-09-2017\",\"email\":\"jhon1@test.com\",\"person-name\":\"Jhon\",\"id\":10}", Boolean.class); + ResponseEntity response = template.withBasicAuth("user","password"). + postForEntity("/person", "{\"birthDate\":\"07-09-2017\",\"email\":\"jhon1@test.com\",\"person-name\":\"Jhon\",\"id\":10}", Boolean.class); assertTrue(response.getBody()); } diff --git a/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationTest.java b/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationIntegrationTest.java similarity index 91% rename from spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationTest.java rename to spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationIntegrationTest.java index ae058bc8ba..35363e0ea3 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/Spring5EnabledAnnotationIntegrationTest.java @@ -9,9 +9,9 @@ import org.springframework.test.context.junit.jupiter.DisabledIf; import org.springframework.test.context.junit.jupiter.EnabledIf; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; -@SpringJUnitConfig(Spring5EnabledAnnotationTest.Config.class) +@SpringJUnitConfig(Spring5EnabledAnnotationIntegrationTest.Config.class) @TestPropertySource(properties = { "tests.enabled=true" }) -public class Spring5EnabledAnnotationTest { +public class Spring5EnabledAnnotationIntegrationTest { @Configuration static class Config { diff --git a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigTest.java b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigIntegrationTest.java similarity index 87% rename from spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigTest.java rename to spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigIntegrationTest.java index 6b0a6f9808..5f81c94aa0 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigIntegrationTest.java @@ -15,8 +15,8 @@ import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; * @ContextConfiguration(classes = SpringJUnitConfigTest.Config.class ) * */ -@SpringJUnitConfig(SpringJUnitConfigTest.Config.class) -public class SpringJUnitConfigTest { +@SpringJUnitConfig(SpringJUnitConfigIntegrationTest.Config.class) +public class SpringJUnitConfigIntegrationTest { @Configuration static class Config { diff --git a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigTest.java b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigIntegrationTest.java similarity index 87% rename from spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigTest.java rename to spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigIntegrationTest.java index c679dce77f..4c3ffda203 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigTest.java +++ b/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigIntegrationTest.java @@ -16,8 +16,8 @@ import org.springframework.web.context.WebApplicationContext; * @ContextConfiguration(classes = SpringJUnitWebConfigTest.Config.class ) * */ -@SpringJUnitWebConfig(SpringJUnitWebConfigTest.Config.class) -public class SpringJUnitWebConfigTest { +@SpringJUnitWebConfig(SpringJUnitWebConfigIntegrationTest.Config.class) +public class SpringJUnitWebConfigIntegrationTest { @Configuration static class Config { diff --git a/spring-5/src/test/java/com/baeldung/security/SecurityIntegrationTest.java b/spring-5/src/test/java/com/baeldung/security/SecurityIntegrationTest.java index 5680625496..1f8bb549c7 100644 --- a/spring-5/src/test/java/com/baeldung/security/SecurityIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/security/SecurityIntegrationTest.java @@ -2,6 +2,7 @@ package com.baeldung.security; import com.baeldung.SpringSecurity5Application; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -31,6 +32,7 @@ public class SecurityIntegrationTest { } @Test + @Ignore @WithMockUser public void whenHasCredentials_thenSeesGreeting() { this.rest.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("Hello, user"); diff --git a/spring-5/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java b/spring-5/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java index 9a6e997ca1..f9472452ba 100644 --- a/spring-5/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/web/client/WebTestClientIntegrationTest.java @@ -5,6 +5,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.server.RequestPredicates; @@ -16,6 +17,7 @@ import reactor.core.publisher.Mono; @RunWith(SpringRunner.class) @SpringBootTest(classes = Spring5Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@EnableJpaRepositories("com.baeldung.persistence") public class WebTestClientIntegrationTest { @LocalServerPort diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml index 5b6911a450..edabb502dd 100644 --- a/spring-activiti/pom.xml +++ b/spring-activiti/pom.xml @@ -59,6 +59,7 @@ true **/*IntegrationTest.java + **/*IntTest.java **/*LongRunningUnitTest.java **/*ManualTest.java **/JdbcTest.java diff --git a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java index 2cfacdcf0d..a9cd1301eb 100644 --- a/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java +++ b/spring-activiti/src/main/java/com/example/activitiwithspring/ActivitiWithSpringApplication.java @@ -2,8 +2,9 @@ package com.example.activitiwithspring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration; -@SpringBootApplication +@SpringBootApplication(exclude = {SecurityAutoConfiguration.class}) public class ActivitiWithSpringApplication { public static void main(String[] args) { SpringApplication.run(ActivitiWithSpringApplication.class, args); 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-all/pom.xml b/spring-all/pom.xml index f9ced963e7..808d9ef585 100644 --- a/spring-all/pom.xml +++ b/spring-all/pom.xml @@ -8,10 +8,10 @@ war - parent-boot-5 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-2 @@ -39,7 +39,6 @@ org.springframework.retry spring-retry - ${springretry.version} org.springframework.shell @@ -55,11 +54,11 @@ org.hibernate hibernate-core - ${hibernate.version} org.javassist javassist + ${javassist.version} mysql @@ -74,6 +73,7 @@ org.hibernate hibernate-validator + ${hibernate.version} @@ -112,7 +112,6 @@ org.assertj assertj-core - ${assertj.version} test @@ -139,17 +138,14 @@ org.ehcache ehcache - ${ehcache.version} org.apache.logging.log4j log4j-api - ${log4j.version} org.apache.logging.log4j log4j-core - ${log4j.version} @@ -187,6 +183,7 @@ org.apache.maven.plugins maven-war-plugin + 3.2.2 false @@ -197,22 +194,23 @@ org.baeldung.sample.App - 4.3.4.RELEASE - 4.2.0.RELEASE - 1.1.5.RELEASE + 5.0.6.RELEASE + 5.0.6.RELEASE + 1.2.2.RELEASE 1.2.0.RELEASE 5.2.5.Final - 19.0 - 3.1.3 - 3.4 + 25.1-jre + 3.5.2 + 3.6 3.6.1 - 6.4.0 + 6.6.0 2.8.2 + 3.22.0-GA diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java b/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java index 4df1e2e73b..318dc5ea65 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationAndServletInitializer.java @@ -4,9 +4,11 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer; -public class AnnotationsBasedApplicationAndServletInitializer extends AbstractDispatcherServletInitializer { +public class AnnotationsBasedApplicationAndServletInitializer //extends AbstractDispatcherServletInitializer +{ - @Override + //uncomment to run the multiple contexts example + //@Override protected WebApplicationContext createRootApplicationContext() { //If this is not the only class declaring a root context, we return null because it would clash //with other classes, as there can only be a single root context. @@ -17,19 +19,19 @@ public class AnnotationsBasedApplicationAndServletInitializer extends AbstractDi return null; } - @Override + //@Override protected WebApplicationContext createServletApplicationContext() { AnnotationConfigWebApplicationContext normalWebAppContext = new AnnotationConfigWebApplicationContext(); normalWebAppContext.register(NormalWebAppConfig.class); return normalWebAppContext; } - @Override + //@Override protected String[] getServletMappings() { return new String[] { "/api/*" }; } - @Override + //@Override protected String getServletName() { return "normal-dispatcher"; } diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java b/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java index 0d2674d4f3..b685d2fa83 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/AnnotationsBasedApplicationInitializer.java @@ -4,9 +4,10 @@ import org.springframework.web.context.AbstractContextLoaderInitializer; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -public class AnnotationsBasedApplicationInitializer extends AbstractContextLoaderInitializer { - - @Override +public class AnnotationsBasedApplicationInitializer //extends AbstractContextLoaderInitializer +{ + //uncomment to run the multiple contexts example + // @Override protected WebApplicationContext createRootApplicationContext() { AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(RootApplicationConfig.class); diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java b/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java index 09e0742394..15a2631cbb 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/ApplicationInitializer.java @@ -12,9 +12,10 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon import org.springframework.web.context.support.XmlWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; -public class ApplicationInitializer implements WebApplicationInitializer { - - @Override +public class ApplicationInitializer //implements WebApplicationInitializer +{ + //uncomment to run the multiple contexts example + //@Override public void onStartup(ServletContext servletContext) throws ServletException { //Here, we can define a root context and register servlets, among other things. //However, since we've later defined other classes to do the same and they would clash, diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java b/spring-all/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java index c250cedc49..3da3d3beb1 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/NormalWebAppConfig.java @@ -5,14 +5,14 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.baeldung.contexts.normal" }) -public class NormalWebAppConfig extends WebMvcConfigurerAdapter { +public class NormalWebAppConfig implements WebMvcConfigurer { @Bean public ViewResolver viewResolver() { diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java b/spring-all/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java index 89ce0153f5..d74d4a6c63 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/SecureAnnotationsBasedApplicationAndServletInitializer.java @@ -4,27 +4,29 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer; -public class SecureAnnotationsBasedApplicationAndServletInitializer extends AbstractDispatcherServletInitializer { - - @Override +public class SecureAnnotationsBasedApplicationAndServletInitializer// extends AbstractDispatcherServletInitializer +{ + + //uncomment to run the multiple contexts example + //@Override protected WebApplicationContext createRootApplicationContext() { return null; } - @Override + //@Override protected WebApplicationContext createServletApplicationContext() { AnnotationConfigWebApplicationContext secureWebAppContext = new AnnotationConfigWebApplicationContext(); secureWebAppContext.register(SecureWebAppConfig.class); return secureWebAppContext; } - @Override + //@Override protected String[] getServletMappings() { return new String[] { "/s/api/*" }; } - @Override + //@Override protected String getServletName() { return "secure-dispatcher"; } diff --git a/spring-all/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java b/spring-all/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java index f499a4ceba..acc1e3092b 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java +++ b/spring-all/src/main/java/com/baeldung/contexts/config/SecureWebAppConfig.java @@ -5,14 +5,14 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.baeldung.contexts.secure" }) -public class SecureWebAppConfig extends WebMvcConfigurerAdapter { +public class SecureWebAppConfig implements WebMvcConfigurer { @Bean public ViewResolver viewResolver() { diff --git a/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java b/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java index fbe3dfb398..8b58c51eb3 100644 --- a/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java +++ b/spring-all/src/main/java/com/baeldung/contexts/normal/HelloWorldController.java @@ -3,14 +3,12 @@ package com.baeldung.contexts.normal; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.ModelAndView; -import com.baeldung.contexts.services.ApplicationContextUtilService; import com.baeldung.contexts.services.GreeterService; @Controller diff --git a/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java b/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java index 3dc4db53c0..85305e057f 100644 --- a/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java +++ b/spring-all/src/main/java/org/baeldung/controller/config/StudentControllerConfig.java @@ -4,29 +4,27 @@ import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; +import org.springframework.context.support.GenericApplicationContext; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; -public class StudentControllerConfig implements WebApplicationInitializer { +public class StudentControllerConfig //implements WebApplicationInitializer +{ - @Override + //uncomment to run the student controller example + //@Override public void onStartup(ServletContext sc) throws ServletException { AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); root.register(WebConfig.class); - root.setServletContext(sc); + sc.addListener(new ContextLoaderListener(root)); - //Manages the lifecycle of the root application context. - //Conflicts with other root contexts in the application, so we've manually set the parent below. - //sc.addListener(new ContextLoaderListener(root)); - - GenericWebApplicationContext webApplicationContext = new GenericWebApplicationContext(); - webApplicationContext.setParent(root); - DispatcherServlet dv = new DispatcherServlet(webApplicationContext); - + DispatcherServlet dv = new DispatcherServlet(root); + ServletRegistration.Dynamic appServlet = sc.addServlet("test-mvc", dv); appServlet.setLoadOnStartup(1); appServlet.addMapping("/test/*"); diff --git a/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java b/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java index 251a1affa1..a17210f3b8 100644 --- a/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java +++ b/spring-all/src/main/java/org/baeldung/controller/config/WebConfig.java @@ -6,13 +6,13 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "org.baeldung.controller.controller", "org.baeldung.controller.config" }) -public class WebConfig extends WebMvcConfigurerAdapter { +public class WebConfig implements WebMvcConfigurer { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); diff --git a/spring-all/src/main/java/org/baeldung/spring/config/CoreConfig.java b/spring-all/src/main/java/org/baeldung/spring/config/CoreConfig.java index 21b67933ef..0d753dc447 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/CoreConfig.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/CoreConfig.java @@ -8,11 +8,11 @@ import java.util.concurrent.TimeUnit; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @ComponentScan("org.baeldung.core") -public class CoreConfig extends WebMvcConfigurerAdapter { +public class CoreConfig implements WebMvcConfigurer { public CoreConfig() { super(); diff --git a/spring-all/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java b/spring-all/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java index a857783c60..9f4b73f609 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/MainWebAppInitializer.java @@ -6,13 +6,16 @@ import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; +import org.springframework.context.support.GenericApplicationContext; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; -public class MainWebAppInitializer implements WebApplicationInitializer { +public class MainWebAppInitializer implements WebApplicationInitializer +{ /** * Register and configure all Servlet container components necessary to power the web application. @@ -26,14 +29,11 @@ public class MainWebAppInitializer implements WebApplicationInitializer { root.scan("org.baeldung.spring.config"); // root.getEnvironment().setDefaultProfiles("embedded"); - //Manages the lifecycle of the root application context. - //Conflicts with other root contexts in the application, so we've manually set the parent below. - //sc.addListener(new ContextLoaderListener(root)); + sc.addListener(new ContextLoaderListener(root)); - // Handles requests into the application - GenericWebApplicationContext webApplicationContext = new GenericWebApplicationContext(); - webApplicationContext.setParent(root); - final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(webApplicationContext)); + DispatcherServlet dv = new DispatcherServlet(root); + + final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc",dv); appServlet.setLoadOnStartup(1); final Set mappingConflicts = appServlet.addMapping("/"); if (!mappingConflicts.isEmpty()) { diff --git a/spring-all/src/main/java/org/baeldung/spring/config/MvcConfig.java b/spring-all/src/main/java/org/baeldung/spring/config/MvcConfig.java index f87e400fce..e550733c47 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/MvcConfig.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/MvcConfig.java @@ -5,13 +5,13 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration -public class MvcConfig extends WebMvcConfigurerAdapter { +public class MvcConfig implements WebMvcConfigurer { public MvcConfig() { super(); @@ -21,8 +21,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/sample.html"); } diff --git a/spring-all/src/main/java/org/baeldung/spring/config/PersistenceConfig.java b/spring-all/src/main/java/org/baeldung/spring/config/PersistenceConfig.java index d57151e259..ffe88596fa 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/PersistenceConfig.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/PersistenceConfig.java @@ -11,8 +11,8 @@ import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.orm.hibernate5.HibernateTransactionManager; +import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.google.common.base.Preconditions; diff --git a/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java b/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java index a9bc298db3..fb34725508 100644 --- a/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java +++ b/spring-all/src/main/java/org/baeldung/spring/config/ScopesConfig.java @@ -38,7 +38,7 @@ public class ScopesConfig { } @Bean - @Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) + @Scope(value = WebApplicationContext.SCOPE_APPLICATION, proxyMode = ScopedProxyMode.TARGET_CLASS) public HelloMessageGenerator globalSessionMessage() { return new HelloMessageGenerator(); } diff --git a/spring-all/src/main/webapp/WEB-INF/web.xml b/spring-all/src/main/webapp/WEB-INF/web-old.xml similarity index 100% rename from spring-all/src/main/webapp/WEB-INF/web.xml rename to spring-all/src/main/webapp/WEB-INF/web-old.xml diff --git a/spring-all/src/test/java/org/baeldung/controller/PassParametersControllerTest.java b/spring-all/src/test/java/org/baeldung/controller/PassParametersControllerIntegrationTest.java similarity index 97% rename from spring-all/src/test/java/org/baeldung/controller/PassParametersControllerTest.java rename to spring-all/src/test/java/org/baeldung/controller/PassParametersControllerIntegrationTest.java index 76ac14f292..21084f44ce 100644 --- a/spring-all/src/test/java/org/baeldung/controller/PassParametersControllerTest.java +++ b/spring-all/src/test/java/org/baeldung/controller/PassParametersControllerIntegrationTest.java @@ -23,7 +23,7 @@ import org.springframework.web.servlet.ModelAndView; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration({"classpath:test-mvc.xml"}) -public class PassParametersControllerTest { +public class PassParametersControllerIntegrationTest { private MockMvc mockMvc; @Autowired diff --git a/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationConfiguration.java b/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationConfiguration.java index 97ae651473..347dd399e2 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationConfiguration.java +++ b/spring-all/src/test/java/org/baeldung/spring43/attributeannotations/AttributeAnnotationConfiguration.java @@ -6,13 +6,13 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @ComponentScan @EnableWebMvc -public class AttributeAnnotationConfiguration extends WebMvcConfigurerAdapter { +public class AttributeAnnotationConfiguration implements WebMvcConfigurer { @Bean public ViewResolver viewResolver() { diff --git a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalTest.java b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalUnitTest.java similarity index 80% rename from spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalTest.java rename to spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalUnitTest.java index c7b95bced4..3c180e91c8 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/ITransactionalUnitTest.java @@ -5,9 +5,9 @@ import org.slf4j.LoggerFactory; import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; -public interface ITransactionalTest { +public interface ITransactionalUnitTest { - Logger log = LoggerFactory.getLogger(ITransactionalTest.class); + Logger log = LoggerFactory.getLogger(ITransactionalUnitTest.class); @BeforeTransaction default void beforeTransaction() { diff --git a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java index b4ac7e8ccf..dde153487d 100644 --- a/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/spring43/defaultmethods/TransactionalIntegrationTest.java @@ -5,7 +5,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; @ContextConfiguration(classes = TransactionalTestConfiguration.class) -public class TransactionalIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests implements ITransactionalTest { +public class TransactionalIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests implements ITransactionalUnitTest { @Test public void whenDefaultMethodAnnotatedWithBeforeTransaction_thenDefaultMethodIsExecuted() { diff --git a/spring-amqp-simple/pom.xml b/spring-amqp-simple/pom.xml index f3dfbccaec..eb0f25d1a7 100644 --- a/spring-amqp-simple/pom.xml +++ b/spring-amqp-simple/pom.xml @@ -8,10 +8,10 @@ Spring AMQP Simple App - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-aop/pom.xml b/spring-aop/pom.xml index 7cdf9bd7cc..0f4e08baa3 100644 --- a/spring-aop/pom.xml +++ b/spring-aop/pom.xml @@ -8,10 +8,10 @@ spring-aop - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodTest.java b/spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodUnitTest.java similarity index 86% rename from spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodTest.java rename to spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodUnitTest.java index 7ecb2a3ee3..cbdb2db057 100644 --- a/spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodTest.java +++ b/spring-aop/src/test/java/org/baeldung/aspectj/SecuredMethodUnitTest.java @@ -2,7 +2,7 @@ package org.baeldung.aspectj; import org.junit.Test; -public class SecuredMethodTest { +public class SecuredMethodUnitTest { @Test public void testMethod() throws Exception { SecuredMethod service = new SecuredMethod(); diff --git a/spring-aop/src/test/java/org/baeldung/logger/CalculatorTest.java b/spring-aop/src/test/java/org/baeldung/logger/CalculatorIntegrationTest.java similarity index 92% rename from spring-aop/src/test/java/org/baeldung/logger/CalculatorTest.java rename to spring-aop/src/test/java/org/baeldung/logger/CalculatorIntegrationTest.java index b1c88c67df..8c31b7f892 100644 --- a/spring-aop/src/test/java/org/baeldung/logger/CalculatorTest.java +++ b/spring-aop/src/test/java/org/baeldung/logger/CalculatorIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(value = {"classpath:springAop-applicationContext.xml"}) -public class CalculatorTest { +public class CalculatorIntegrationTest { @Autowired private SampleAdder sampleAdder; diff --git a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksTest.java b/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java similarity index 96% rename from spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksTest.java rename to spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java index 2a71970637..eaf73e4a4a 100644 --- a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksTest.java +++ b/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = ChunksConfig.class) -public class ChunksTest { +public class ChunksIntegrationTest { @Autowired private JobLauncherTestUtils jobLauncherTestUtils; diff --git a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsTest.java b/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java similarity index 96% rename from spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsTest.java rename to spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java index 20379b58fe..322b17bd55 100644 --- a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsTest.java +++ b/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java @@ -13,7 +13,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = TaskletsConfig.class) -public class TaskletsTest { +public class TaskletsIntegrationTest { @Autowired private JobLauncherTestUtils jobLauncherTestUtils; diff --git a/spring-boot-autoconfiguration/pom.xml b/spring-boot-autoconfiguration/pom.xml index 2687fcd969..2a61b89b5d 100644 --- a/spring-boot-autoconfiguration/pom.xml +++ b/spring-boot-autoconfiguration/pom.xml @@ -79,6 +79,7 @@ **/*LiveTest.java **/*IntegrationTest.java + **/*IntTest.java **/AutoconfigurationTest.java diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index 03ce9b6906..9ba4d9a5eb 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -15,25 +15,6 @@ ../parent-boot-2 - - org.springframework.boot @@ -91,6 +72,7 @@ **/*LiveTest.java **/*IntegrationTest.java + **/*IntTest.java **/AutoconfigurationTest.java @@ -107,6 +89,28 @@ + + thin-jar + + + + org.springframework.boot.experimental + spring-boot-thin-maven-plugin + ${thin.version} + + + + resolve + + resolve + + false + + + + + + diff --git a/spring-boot-ctx-fluent/README.md b/spring-boot-ctx-fluent/README.md new file mode 100644 index 0000000000..0b4b9c1271 --- /dev/null +++ b/spring-boot-ctx-fluent/README.md @@ -0,0 +1,4 @@ + +### Relevant Articles: + +- [Context Hierarchy with the Spring Boot Fluent Builder API](http://www.baeldung.com/spring-boot-context-hierarchy) diff --git a/spring-boot-ctx-fluent/pom.xml b/spring-boot-ctx-fluent/pom.xml new file mode 100644 index 0000000000..6d767f9ef7 --- /dev/null +++ b/spring-boot-ctx-fluent/pom.xml @@ -0,0 +1,28 @@ + + 4.0.0 + + com.baeldung + spring-boot-ctx-fluent + 0.0.1-SNAPSHOT + jar + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + + UTF-8 + + + diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Config.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Config.java new file mode 100644 index 0000000000..0bacc5e8fe --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Config.java @@ -0,0 +1,22 @@ +package com.baeldung.ctx1; + +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; + +import com.baeldung.parent.IHomeService; + +@Configuration +@ComponentScan("com.baeldung.ctx1") +@PropertySource("classpath:ctx1.properties") +@EnableAutoConfiguration +public class Ctx1Config { + + @Bean + public IHomeService homeService() { + return new GreetingService(); + } + +} diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Controller.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Controller.java new file mode 100644 index 0000000000..9c7667db35 --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/Ctx1Controller.java @@ -0,0 +1,22 @@ +package com.baeldung.ctx1; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.baeldung.parent.IHomeService; + +@Controller +public class Ctx1Controller { + + @Autowired + IHomeService homeService; + + @GetMapping("/home") + @ResponseBody + public String greeting() { + + return homeService.getGreeting(); + } +} diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/GreetingService.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/GreetingService.java new file mode 100644 index 0000000000..a0f1f16288 --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx1/GreetingService.java @@ -0,0 +1,13 @@ +package com.baeldung.ctx1; + +import org.springframework.stereotype.Service; + +import com.baeldung.parent.IHomeService; + +@Service +public class GreetingService implements IHomeService { + + public String getGreeting() { + return "Greetings for the day"; + } +} diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Config.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Config.java new file mode 100644 index 0000000000..fc08b741f3 --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Config.java @@ -0,0 +1,14 @@ +package com.baeldung.ctx2; + +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; + +@Configuration +@ComponentScan("com.baeldung.ctx2") +@EnableAutoConfiguration +@PropertySource("classpath:ctx2.properties") +public class Ctx2Config { + +} diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Controller.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Controller.java new file mode 100644 index 0000000000..850fd8021c --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/ctx2/Ctx2Controller.java @@ -0,0 +1,19 @@ +package com.baeldung.ctx2; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.parent.IHomeService; + +@RestController +public class Ctx2Controller { + + @Autowired + IHomeService homeService; + + @GetMapping(value = "/greeting", produces = "application/json") + public String getGreeting() { + return homeService.getGreeting(); + } +} diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/App.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/App.java new file mode 100644 index 0000000000..609751bc0f --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/App.java @@ -0,0 +1,19 @@ +package com.baeldung.parent; + +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.builder.SpringApplicationBuilder; + +import com.baeldung.ctx1.Ctx1Config; +import com.baeldung.ctx2.Ctx2Config; + +public class App { + public static void main(String[] args) { + new SpringApplicationBuilder().parent(ParentConfig.class) + .web(WebApplicationType.NONE) + .child(Ctx1Config.class) + .web(WebApplicationType.SERVLET) + .sibling(Ctx2Config.class) + .web(WebApplicationType.SERVLET) + .run(args); + } +} diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/HomeService.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/HomeService.java new file mode 100644 index 0000000000..0d23e26cce --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/HomeService.java @@ -0,0 +1,11 @@ +package com.baeldung.parent; + +import org.springframework.stereotype.Service; + +@Service +public class HomeService implements IHomeService { + + public String getGreeting() { + return "Welcome User"; + } +} diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/IHomeService.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/IHomeService.java new file mode 100644 index 0000000000..264e49861a --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/IHomeService.java @@ -0,0 +1,6 @@ +package com.baeldung.parent; + +public interface IHomeService { + + String getGreeting(); +} diff --git a/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/ParentConfig.java b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/ParentConfig.java new file mode 100644 index 0000000000..484d020cc0 --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/java/com/baeldung/parent/ParentConfig.java @@ -0,0 +1,8 @@ +package com.baeldung.parent; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.parent") +public class ParentConfig {} diff --git a/spring-boot-ctx-fluent/src/main/resources/ctx1.properties b/spring-boot-ctx-fluent/src/main/resources/ctx1.properties new file mode 100644 index 0000000000..2b618d4177 --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/resources/ctx1.properties @@ -0,0 +1,5 @@ +server.port=8081 +server.servlet.context-path=/ctx1 +#logging.level=debug +spring.application.admin.enabled=false +spring.application.admin.jmx-name=org.springframework.boot:type=AdminRest,name=SpringRestApplication \ No newline at end of file diff --git a/spring-boot-ctx-fluent/src/main/resources/ctx2.properties b/spring-boot-ctx-fluent/src/main/resources/ctx2.properties new file mode 100644 index 0000000000..f3599e17e0 --- /dev/null +++ b/spring-boot-ctx-fluent/src/main/resources/ctx2.properties @@ -0,0 +1,5 @@ +server.port=8082 +server.servlet.context-path=/ctx2 + +spring.application.admin.enabled=false +spring.application.admin.jmx-name=org.springframework.boot:type=WebAdmin,name=SpringWebApplication \ No newline at end of file diff --git a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml index 6ae6572ca9..96647ea0f1 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml +++ b/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml @@ -6,10 +6,10 @@ greeter-spring-boot-autoconfigure 0.0.1-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 UTF-8 diff --git a/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml index 9db76759ec..a2c96a8555 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml +++ b/spring-boot-custom-starter/greeter-spring-boot-sample-app/pom.xml @@ -7,10 +7,10 @@ 0.0.1-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml b/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml index e771cbaa8d..7bf13eebc8 100644 --- a/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml +++ b/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml @@ -6,10 +6,10 @@ greeter-spring-boot-starter 0.0.1-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 UTF-8 diff --git a/spring-boot-custom-starter/greeter/pom.xml b/spring-boot-custom-starter/greeter/pom.xml index 6143992088..aa45b8e6a4 100644 --- a/spring-boot-custom-starter/greeter/pom.xml +++ b/spring-boot-custom-starter/greeter/pom.xml @@ -6,9 +6,9 @@ greeter 0.0.1-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 \ No newline at end of file diff --git a/spring-boot-gradle/.gitignore b/spring-boot-gradle/.gitignore new file mode 100644 index 0000000000..192221b47d --- /dev/null +++ b/spring-boot-gradle/.gitignore @@ -0,0 +1,2 @@ +.gradle/ +build/ \ No newline at end of file diff --git a/spring-boot-gradle/build.gradle b/spring-boot-gradle/build.gradle index e602c485a9..96055536c3 100644 --- a/spring-boot-gradle/build.gradle +++ b/spring-boot-gradle/build.gradle @@ -1,12 +1,16 @@ buildscript { ext { - springBootVersion = '2.0.0.RELEASE' + springBootPlugin = 'org.springframework.boot:spring-boot-gradle-plugin' + springBootVersion = '2.0.2.RELEASE' + thinPlugin = 'org.springframework.boot.experimental:spring-boot-thin-gradle-plugin' + thinVersion = '1.0.11.RELEASE' } repositories { mavenCentral() } dependencies { - classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") + classpath("${springBootPlugin}:${springBootVersion}") + classpath("${thinPlugin}:${thinVersion}") } } @@ -14,6 +18,8 @@ apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' +//add tasks thinJar and thinResolve for thin JAR deployments +apply plugin: 'org.springframework.boot.experimental.thin-launcher' group = 'org.baeldung' version = '0.0.1-SNAPSHOT' @@ -23,7 +29,6 @@ repositories { mavenCentral() } - dependencies { compile('org.springframework.boot:spring-boot-starter') testCompile('org.springframework.boot:spring-boot-starter-test') @@ -42,3 +47,21 @@ bootJar { // attributes 'Start-Class': 'org.baeldung.DemoApplication' // } } + +//Enable this to generate and use a pom.xml file +apply plugin: 'maven' + +//If you want to customize the generated pom.xml you can edit this task and add it as a dependency to the bootJar task +task createPom { + def basePath = 'build/resources/main/META-INF/maven' + doLast { + pom { + withXml(dependencyManagement.pomConfigurer) + }.writeTo("${basePath}/${project.group}/${project.name}/pom.xml") + } +} +//Uncomment the following to use your custom generated pom.xml +bootJar.dependsOn = [createPom] + +//Enable this to generate and use a thin.properties file +//bootJar.dependsOn = [thinProperties] \ No newline at end of file diff --git a/spring-boot-gradle/gradle/wrapper/gradle-wrapper.properties b/spring-boot-gradle/gradle/wrapper/gradle-wrapper.properties index 44d9d03d80..a8868a918a 100644 --- a/spring-boot-gradle/gradle/wrapper/gradle-wrapper.properties +++ b/spring-boot-gradle/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Tue Feb 06 12:27:20 CET 2018 +#Fri Jun 01 20:39:48 CEST 2018 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.5.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-4.5.1-all.zip diff --git a/spring-boot-jasypt/.gitignore b/spring-boot-jasypt/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/spring-boot-jasypt/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/spring-boot-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-jasypt/pom.xml b/spring-boot-jasypt/pom.xml new file mode 100644 index 0000000000..e094f0b061 --- /dev/null +++ b/spring-boot-jasypt/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + + com.example.jasypt + JasyptDemo + 0.0.1-SNAPSHOT + jar + + JasyptDemo + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.1.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-test + test + + + + com.github.ulisesbocchio + jasypt-spring-boot-starter + 2.0.0 + + + + com.github.ulisesbocchio + jasypt-spring-boot + 2.0.0 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/Main.java b/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/Main.java new file mode 100644 index 0000000000..0cdb5d4f1b --- /dev/null +++ b/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/Main.java @@ -0,0 +1,35 @@ +package com.baeldung.jasypt; + +import org.jasypt.encryption.StringEncryptor; +import org.jasypt.encryption.pbe.PooledPBEStringEncryptor; +import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; + +import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties; + +@SpringBootApplication +@ComponentScan(basePackages = { "com.baeldung.jasypt" }) +@EnableEncryptableProperties +public class Main { + public static void main(String[] args) { + new SpringApplicationBuilder().sources(Main.class).run(args); + } + + @Bean(name = "encryptorBean") + public StringEncryptor stringEncryptor() { + PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); + SimpleStringPBEConfig config = new SimpleStringPBEConfig(); + config.setPassword("password"); + config.setAlgorithm("PBEWithMD5AndDES"); + config.setKeyObtentionIterations("1000"); + config.setPoolSize("1"); + config.setProviderName("SunJCE"); + config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator"); + config.setStringOutputType("base64"); + encryptor.setConfig(config); + return encryptor; + } +} diff --git a/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/simple/AppConfigForJasyptSimple.java b/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/simple/AppConfigForJasyptSimple.java new file mode 100644 index 0000000000..41681cb8ca --- /dev/null +++ b/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/simple/AppConfigForJasyptSimple.java @@ -0,0 +1,10 @@ +package com.baeldung.jasypt.simple; + +import org.springframework.context.annotation.Configuration; + +import com.ulisesbocchio.jasyptspringboot.annotation.EncryptablePropertySource; + +@Configuration +@EncryptablePropertySource(value = "encryptedv2.properties") +public class AppConfigForJasyptSimple { +} diff --git a/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/simple/PropertyServiceForJasyptSimple.java b/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/simple/PropertyServiceForJasyptSimple.java new file mode 100644 index 0000000000..def4808b8e --- /dev/null +++ b/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/simple/PropertyServiceForJasyptSimple.java @@ -0,0 +1,15 @@ +package com.baeldung.jasypt.simple; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +@Service +public class PropertyServiceForJasyptSimple { + + @Value("${encryptedv2.property}") + private String property; + + public String getProperty() { + return property; + } +} diff --git a/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/starter/AppConfigForJasyptStarter.java b/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/starter/AppConfigForJasyptStarter.java new file mode 100644 index 0000000000..4db90ed5dc --- /dev/null +++ b/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/starter/AppConfigForJasyptStarter.java @@ -0,0 +1,9 @@ +package com.baeldung.jasypt.starter; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; + +@Configuration +@PropertySource(value = "encrypted.properties") +public class AppConfigForJasyptStarter { +} diff --git a/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/starter/PropertyServiceForJasyptStarter.java b/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/starter/PropertyServiceForJasyptStarter.java new file mode 100644 index 0000000000..725720ebff --- /dev/null +++ b/spring-boot-jasypt/src/main/java/com/baeldung/jasypt/starter/PropertyServiceForJasyptStarter.java @@ -0,0 +1,20 @@ +package com.baeldung.jasypt.starter; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + +@Service +public class PropertyServiceForJasyptStarter { + + @Value("${encrypted.property}") + private String property; + + public String getProperty() { + return property; + } + + public String getPasswordUsingEnvironment(Environment environment) { + return environment.getProperty("encrypted.property"); + } +} diff --git a/spring-boot-jasypt/src/main/resources/application.properties b/spring-boot-jasypt/src/main/resources/application.properties new file mode 100644 index 0000000000..ea61c4d846 --- /dev/null +++ b/spring-boot-jasypt/src/main/resources/application.properties @@ -0,0 +1,3 @@ +jasypt.encryptor.bean=encryptorBean +encryptedv3.property=ENC(askygdq8PHapYFnlX6WsTwZZOxWInq+i) + diff --git a/spring-boot-jasypt/src/main/resources/encrypted.properties b/spring-boot-jasypt/src/main/resources/encrypted.properties new file mode 100644 index 0000000000..0188fc392c --- /dev/null +++ b/spring-boot-jasypt/src/main/resources/encrypted.properties @@ -0,0 +1 @@ +encrypted.property=ENC(uTSqb9grs1+vUv3iN8lItC0kl65lMG+8) \ No newline at end of file diff --git a/spring-boot-jasypt/src/main/resources/encryptedv2.properties b/spring-boot-jasypt/src/main/resources/encryptedv2.properties new file mode 100644 index 0000000000..6785149718 --- /dev/null +++ b/spring-boot-jasypt/src/main/resources/encryptedv2.properties @@ -0,0 +1 @@ +encryptedv2.property=ENC(dQWokHUXXFe+OqXRZYWu22BpXoRZ0Drt) diff --git a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptTest.java b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptTest.java new file mode 100644 index 0000000000..58c2dc7bb2 --- /dev/null +++ b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/CustomJasyptTest.java @@ -0,0 +1,27 @@ +package com.baeldung.jasypt; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.jasypt.Main; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {Main.class}) +public class CustomJasyptTest { + + @Autowired + ApplicationContext appCtx; + + @Test + public void whenConfiguredExcryptorUsed_ReturnCustomEncryptor() { + Environment environment = appCtx.getBean(Environment.class); + assertEquals("Password@3", environment.getProperty("encryptedv3.property")); + } +} diff --git a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleTest.java b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleTest.java new file mode 100644 index 0000000000..f9b66b5044 --- /dev/null +++ b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptSimpleTest.java @@ -0,0 +1,28 @@ +package com.baeldung.jasypt; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.jasypt.simple.PropertyServiceForJasyptSimple; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class JasyptSimpleTest { + + @Autowired + ApplicationContext appCtx; + + @Test + public void whenDecryptedPasswordNeeded_GetFromService() { + System.setProperty("jasypt.encryptor.password", "password"); + PropertyServiceForJasyptSimple service = appCtx.getBean(PropertyServiceForJasyptSimple.class); + assertEquals("Password@2", service.getProperty()); + } + +} diff --git a/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterTest.java b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterTest.java new file mode 100644 index 0000000000..d246c21036 --- /dev/null +++ b/spring-boot-jasypt/src/test/java/com/baeldung/jasypt/JasyptWithStarterTest.java @@ -0,0 +1,30 @@ +package com.baeldung.jasypt; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.jasypt.starter.PropertyServiceForJasyptStarter; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class JasyptWithStarterTest { + + @Autowired + ApplicationContext appCtx; + + @Test + public void whenDecryptedPasswordNeeded_GetFromService() { + System.setProperty("jasypt.encryptor.password", "password"); + PropertyServiceForJasyptStarter service = appCtx.getBean(PropertyServiceForJasyptStarter.class); + assertEquals("Password@1", service.getProperty()); + Environment environment = appCtx.getBean(Environment.class); + assertEquals("Password@1", service.getPasswordUsingEnvironment(environment)); + } +} diff --git a/spring-boot-keycloak/pom.xml b/spring-boot-keycloak/pom.xml index d2df261b2f..b7b15935ec 100644 --- a/spring-boot-keycloak/pom.xml +++ b/spring-boot-keycloak/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-5 + parent-boot-1 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-boot-mvc/.gitignore b/spring-boot-mvc/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/spring-boot-mvc/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/spring-boot-mvc/pom.xml b/spring-boot-mvc/pom.xml new file mode 100644 index 0000000000..81968973f8 --- /dev/null +++ b/spring-boot-mvc/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + com.baeldung + spring-boot-mvc + 0.0.1-SNAPSHOT + jar + + spring-boot-mvc + Demo project for Spring Boot + + + org.springframework.boot + spring-boot-starter-parent + 2.0.2.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java new file mode 100644 index 0000000000..c4213af0a3 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/SpringBootMvcApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.springbootmvc; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; + +@SpringBootApplication +public class SpringBootMvcApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootMvcApplication.class, args); + } +} diff --git a/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/FaviconConfiguration.java b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/FaviconConfiguration.java new file mode 100644 index 0000000000..1ee13ccec2 --- /dev/null +++ b/spring-boot-mvc/src/main/java/com/baeldung/springbootmvc/config/FaviconConfiguration.java @@ -0,0 +1,43 @@ +package com.baeldung.springbootmvc.config; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; +import org.springframework.web.servlet.resource.ResourceHttpRequestHandler; + +@Configuration +public class FaviconConfiguration { + @Bean + public SimpleUrlHandlerMapping myFaviconHandlerMapping() { + SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); + mapping.setOrder(Integer.MIN_VALUE); + mapping.setUrlMap(Collections.singletonMap("/favicon.ico", faviconRequestHandler())); + return mapping; + } + + @Bean + protected ResourceHttpRequestHandler faviconRequestHandler() { + ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler(); + ClassPathResource classPathResource = new ClassPathResource("com/baeldung/images"); + List locations = Arrays.asList(classPathResource); + requestHandler.setLocations(locations); + return requestHandler; + } + + //@Controller + static class FaviconController { + + @RequestMapping(value="favicon.ico", method=RequestMethod.GET) + @ResponseBody + void favicon() {} + } +} diff --git a/spring-boot-mvc/src/main/resources/application.properties b/spring-boot-mvc/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-mvc/src/main/resources/com/baeldung/images/favicon.ico b/spring-boot-mvc/src/main/resources/com/baeldung/images/favicon.ico new file mode 100644 index 0000000000..64105ac11c Binary files /dev/null and b/spring-boot-mvc/src/main/resources/com/baeldung/images/favicon.ico differ diff --git a/spring-boot-mvc/src/main/resources/favicon.ico b/spring-boot-mvc/src/main/resources/favicon.ico new file mode 100644 index 0000000000..64105ac11c Binary files /dev/null and b/spring-boot-mvc/src/main/resources/favicon.ico differ diff --git a/spring-boot-mvc/src/main/resources/static/favicon.ico b/spring-boot-mvc/src/main/resources/static/favicon.ico new file mode 100644 index 0000000000..64105ac11c Binary files /dev/null and b/spring-boot-mvc/src/main/resources/static/favicon.ico differ diff --git a/spring-boot-mvc/src/main/resources/static/index.html b/spring-boot-mvc/src/main/resources/static/index.html new file mode 100644 index 0000000000..9f55d12685 --- /dev/null +++ b/spring-boot-mvc/src/main/resources/static/index.html @@ -0,0 +1 @@ +Welcome to Baeldung \ No newline at end of file diff --git a/spring-boot-mvc/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationTests.java b/spring-boot-mvc/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationTests.java new file mode 100644 index 0000000000..1add635ed8 --- /dev/null +++ b/spring-boot-mvc/src/test/java/com/baeldung/springbootmvc/SpringBootMvcApplicationTests.java @@ -0,0 +1,16 @@ +package com.baeldung.springbootmvc; + +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 SpringBootMvcApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-boot-ops/README.md b/spring-boot-ops/README.md new file mode 100644 index 0000000000..7eca307924 --- /dev/null +++ b/spring-boot-ops/README.md @@ -0,0 +1,10 @@ +### Relevant Articles: + +- [Deploy a Spring Boot WAR into a Tomcat Server](http://www.baeldung.com/spring-boot-war-tomcat-deploy) +- [Spring Boot Dependency Management with a Custom Parent](http://www.baeldung.com/spring-boot-dependency-management-custom-parent) +- [A Custom Data Binder in Spring MVC](http://www.baeldung.com/spring-mvc-custom-data-binder) +- [Create a Fat Jar App with Spring Boot](http://www.baeldung.com/deployable-fat-jar-spring-boot) +- [Introduction to WebJars](http://www.baeldung.com/maven-webjars) +- [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters) +- [A Quick Guide to Maven Wrapper](http://www.baeldung.com/maven-wrapper) +- [Shutdown a Spring Boot Application](http://www.baeldung.com/spring-boot-shutdown) diff --git a/spring-boot-ops/docker/Dockerfile b/spring-boot-ops/docker/Dockerfile new file mode 100644 index 0000000000..85db5c7bed --- /dev/null +++ b/spring-boot-ops/docker/Dockerfile @@ -0,0 +1,16 @@ +# Alpine Linux with OpenJDK JRE +FROM openjdk:8-jre-alpine +RUN apk add --no-cache bash + +# copy fat WAR +COPY spring-boot-ops.war /app.war + +# copy fat WAR +COPY logback.xml /logback.xml + +COPY run.sh /run.sh + +# runs application +#CMD ["/usr/bin/java", "-jar", "-Dspring.profiles.active=default", "-Dlogging.config=/logback.xml", "/app.war"] + +ENTRYPOINT ["/run.sh"] diff --git a/spring-boot-ops/docker/logback.xml b/spring-boot-ops/docker/logback.xml new file mode 100644 index 0000000000..aad6d3fcb3 --- /dev/null +++ b/spring-boot-ops/docker/logback.xml @@ -0,0 +1,15 @@ + + + + + /var/log/WebjarsdemoApplication/application.log + true + + %-7d{yyyy-MM-dd HH:mm:ss:SSS} %m%n + + + + + + + diff --git a/spring-boot-ops/docker/run.sh b/spring-boot-ops/docker/run.sh new file mode 100755 index 0000000000..aeecc29371 --- /dev/null +++ b/spring-boot-ops/docker/run.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +java -Dspring.profiles.active=$1 -Dlogging.config=/logback.xml -jar /app.war + diff --git a/spring-boot-ops/pom.xml b/spring-boot-ops/pom.xml new file mode 100644 index 0000000000..21a7d22077 --- /dev/null +++ b/spring-boot-ops/pom.xml @@ -0,0 +1,185 @@ + + + 4.0.0 + + com.baeldung + spring-boot-ops + 0.0.1-SNAPSHOT + war + + spring-boot-ops + Demo project for Spring Boot + + + 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 + + + + org.springframework.boot + spring-boot-starter-thymeleaf + provided + + + + org.springframework.boot + 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} + + + + + + ${artifactId} + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + com.baeldung.webjar.WebjarsdemoApplication + + + + + + + + + + autoconfiguration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*LiveTest.java + **/*IntegrationTest.java + **/*IntTest.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 99% 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 index 2225df8b34..03f16789dc 100644 --- a/spring-boot/src/main/java/com/baeldung/shutdown/Application.java +++ b/spring-boot-ops/src/main/java/com/baeldung/shutdown/Application.java @@ -9,7 +9,7 @@ import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class Application { - + public static void main(String[] args) { SpringApplication.run(Application.class, args); @@ -46,4 +46,5 @@ public class Application { app.build().addListeners(new ApplicationPidFileWriter("./bin/shutdown.pid")); app.run(); } + } 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-ops/src/main/java/com/baeldung/shutdown/shutdown/ShutdownController.java b/spring-boot-ops/src/main/java/com/baeldung/shutdown/shutdown/ShutdownController.java new file mode 100644 index 0000000000..6ebe053654 --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/shutdown/shutdown/ShutdownController.java @@ -0,0 +1,25 @@ +package com.baeldung.shutdown.shutdown; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class ShutdownController implements ApplicationContextAware { + + private ApplicationContext context; + + @PostMapping("/shutdownContext") + public void shutdownContext() { + ((ConfigurableApplicationContext) context).close(); + } + + @Override + public void setApplicationContext(ApplicationContext ctx) throws BeansException { + this.context = ctx; + + } +} diff --git a/spring-boot-ops/src/main/java/com/baeldung/springbootsimple/SpringBootTomcatApplication.java b/spring-boot-ops/src/main/java/com/baeldung/springbootsimple/SpringBootTomcatApplication.java new file mode 100644 index 0000000000..c9f90683ec --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/springbootsimple/SpringBootTomcatApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.springbootsimple; + +import org.springframework.boot.*; +import org.springframework.boot.autoconfigure.*; +import org.springframework.boot.web.servlet.support.*; + +@SpringBootApplication +public class SpringBootTomcatApplication extends SpringBootServletInitializer { + + public static void main(String[] args) { + SpringApplication.run(SpringBootTomcatApplication.class, args); + } +} diff --git a/spring-boot-ops/src/main/java/com/baeldung/springbootsimple/TomcatController.java b/spring-boot-ops/src/main/java/com/baeldung/springbootsimple/TomcatController.java new file mode 100644 index 0000000000..fcf7ecd6c0 --- /dev/null +++ b/spring-boot-ops/src/main/java/com/baeldung/springbootsimple/TomcatController.java @@ -0,0 +1,18 @@ +package com.baeldung.springbootsimple; + +import org.springframework.web.bind.annotation.*; + +import java.util.*; +import java.util.stream.*; + +@RestController +public class TomcatController { + + @GetMapping(value = "/hello") + public Collection sayHello() { + return IntStream.range(0, 10) + .mapToObj(i -> "Hello number " + i) + .collect(Collectors.toList()); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/webjar/TestController.java b/spring-boot-ops/src/main/java/com/baeldung/webjar/TestController.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/webjar/TestController.java rename to spring-boot-ops/src/main/java/com/baeldung/webjar/TestController.java diff --git a/spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java b/spring-boot-ops/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java similarity index 100% rename from spring-boot/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java rename to spring-boot-ops/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/Application.java b/spring-boot-ops/src/main/java/org/baeldung/boot/Application.java new file mode 100644 index 0000000000..c1b6558b26 --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/Application.java @@ -0,0 +1,14 @@ +package org.baeldung.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; + +@SpringBootApplication +public class Application { + private static ApplicationContext applicationContext; + + public static void main(String[] args) { + applicationContext = SpringApplication.run(Application.class, args); + } +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java b/spring-boot-ops/src/main/java/org/baeldung/boot/config/WebConfig.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/config/WebConfig.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/config/WebConfig.java diff --git a/spring-boot/src/main/java/org/baeldung/boot/controller/GenericEntityController.java b/spring-boot-ops/src/main/java/org/baeldung/boot/controller/GenericEntityController.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/controller/GenericEntityController.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/controller/GenericEntityController.java diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/converter/GenericBigDecimalConverter.java diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java similarity index 89% rename from spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java index b07e11e01a..e00d0ad312 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEmployeeConverter.java @@ -1,6 +1,6 @@ package org.baeldung.boot.converter; -import com.baeldung.toggle.Employee; +import org.baeldung.boot.domain.Employee; import org.springframework.core.convert.converter.Converter; public class StringToEmployeeConverter implements Converter { diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToEnumConverterFactory.java diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/StringToLocalDateTimeConverter.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToLocalDateTimeConverter.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/converter/StringToLocalDateTimeConverter.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/converter/StringToLocalDateTimeConverter.java diff --git a/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java similarity index 90% rename from spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java index a6e0400845..762d237156 100644 --- a/spring-boot/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/converter/controller/StringToEmployeeConverterController.java @@ -1,6 +1,6 @@ package org.baeldung.boot.converter.controller; -import com.baeldung.toggle.Employee; +import org.baeldung.boot.domain.Employee; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Employee.java b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Employee.java new file mode 100644 index 0000000000..8242e53200 --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Employee.java @@ -0,0 +1,37 @@ +package org.baeldung.boot.domain; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + + @Id + private long id; + private double salary; + + public Employee() { + } + + public Employee(long id, double salary) { + this.id = id; + this.salary = salary; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + +} diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/domain/GenericEntity.java b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/GenericEntity.java new file mode 100644 index 0000000000..f1c936e432 --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/GenericEntity.java @@ -0,0 +1,42 @@ +package org.baeldung.boot.domain; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class GenericEntity { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + private String value; + + public GenericEntity() { + } + + public GenericEntity(String value) { + this.value = value; + } + + public GenericEntity(Long id, String value) { + this.id = id; + this.value = value; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Modes.java b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Modes.java new file mode 100644 index 0000000000..dcba064e8c --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/domain/Modes.java @@ -0,0 +1,6 @@ +package org.baeldung.boot.domain; + +public enum Modes { + + ALPHA, BETA; +} diff --git a/spring-boot-ops/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java b/spring-boot-ops/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java new file mode 100644 index 0000000000..d897e17afe --- /dev/null +++ b/spring-boot-ops/src/main/java/org/baeldung/boot/repository/GenericEntityRepository.java @@ -0,0 +1,7 @@ +package org.baeldung.boot.repository; + +import org.baeldung.boot.domain.GenericEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface GenericEntityRepository extends JpaRepository { +} diff --git a/spring-boot/src/main/java/org/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java b/spring-boot-ops/src/main/java/org/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/web/resolver/HeaderVersionArgumentResolver.java diff --git a/spring-boot/src/main/java/org/baeldung/boot/web/resolver/Version.java b/spring-boot-ops/src/main/java/org/baeldung/boot/web/resolver/Version.java similarity index 100% rename from spring-boot/src/main/java/org/baeldung/boot/web/resolver/Version.java rename to spring-boot-ops/src/main/java/org/baeldung/boot/web/resolver/Version.java diff --git a/spring-boot/src/main/resources/templates/index.html b/spring-boot-ops/src/main/resources/templates/index.html similarity index 100% rename from spring-boot/src/main/resources/templates/index.html rename to spring-boot-ops/src/main/resources/templates/index.html diff --git a/spring-boot/src/test/java/com/baeldung/shutdown/ShutdownApplicationTest.java b/spring-boot-ops/src/test/java/com/baeldung/shutdown/ShutdownApplicationIntegrationTest.java similarity index 82% rename from spring-boot/src/test/java/com/baeldung/shutdown/ShutdownApplicationTest.java rename to spring-boot-ops/src/test/java/com/baeldung/shutdown/ShutdownApplicationIntegrationTest.java index 7896b9dc09..d9351b7203 100644 --- a/spring-boot/src/test/java/com/baeldung/shutdown/ShutdownApplicationTest.java +++ b/spring-boot-ops/src/test/java/com/baeldung/shutdown/ShutdownApplicationIntegrationTest.java @@ -1,5 +1,8 @@ package com.baeldung.shutdown; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import org.junit.Before; import org.junit.Ignore; import org.junit.Test; @@ -12,14 +15,10 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - - @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = Application.class) @AutoConfigureMockMvc -public class ShutdownApplicationTest { +public class ShutdownApplicationIntegrationTest { @Autowired private MockMvc mockMvc; @@ -36,8 +35,6 @@ public class ShutdownApplicationTest { @Ignore public void givenBootApp_whenShutdownEndpoint_thenExit() throws Exception { - mockMvc.perform( - post("/shutdown")) - .andExpect(status().isOk()); + mockMvc.perform(post("/shutdown")).andExpect(status().isOk()); } } diff --git a/spring-boot-ops/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationIntegrationTest.java b/spring-boot-ops/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationIntegrationTest.java new file mode 100644 index 0000000000..a10ebbbd35 --- /dev/null +++ b/spring-boot-ops/src/test/java/com/baeldung/springbootsimple/SpringBootTomcatApplicationIntegrationTest.java @@ -0,0 +1,16 @@ +package com.baeldung.springbootsimple; + +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 SpringBootTomcatApplicationIntegrationTest { + + @Test + public void contextLoads() { + } + +} diff --git a/spring-boot/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java b/spring-boot-ops/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java rename to spring-boot-ops/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java b/spring-boot-ops/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java rename to spring-boot-ops/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java b/spring-boot-ops/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java rename to spring-boot-ops/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java diff --git a/spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java b/spring-boot-ops/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java similarity index 100% rename from spring-boot/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java rename to spring-boot-ops/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java diff --git a/spring-boot-ops/src/test/resources/application-integrationtest.properties b/spring-boot-ops/src/test/resources/application-integrationtest.properties new file mode 100644 index 0000000000..bcd03226d3 --- /dev/null +++ b/spring-boot-ops/src/test/resources/application-integrationtest.properties @@ -0,0 +1,4 @@ +spring.datasource.url=jdbc:mysql://localhost:3306/employee_int_test +spring.datasource.username=root +spring.datasource.password=root + diff --git a/spring-boot-ops/src/test/resources/application.properties b/spring-boot-ops/src/test/resources/application.properties new file mode 100644 index 0000000000..2095a82a14 --- /dev/null +++ b/spring-boot-ops/src/test/resources/application.properties @@ -0,0 +1,7 @@ +spring.mail.host=localhost +spring.mail.port=8025 +spring.mail.properties.mail.smtp.auth=false + +management.endpoints.web.exposure.include=* +management.endpoint.shutdown.enabled=true +endpoints.shutdown.enabled=true \ No newline at end of file diff --git a/spring-boot-property-exp/property-exp-default-config/pom.xml b/spring-boot-property-exp/property-exp-default-config/pom.xml index e4cbaebf56..0ac4a31c7c 100644 --- a/spring-boot-property-exp/property-exp-default-config/pom.xml +++ b/spring-boot-property-exp/property-exp-default-config/pom.xml @@ -8,10 +8,10 @@ jar - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-boot/.factorypath b/spring-boot/.factorypath index 88c3910e93..68b2514aab 100644 --- a/spring-boot/.factorypath +++ b/spring-boot/.factorypath @@ -49,8 +49,6 @@ - - @@ -70,22 +68,11 @@ - - - - - - - - - - - @@ -98,22 +85,10 @@ - - - - - - - - - - - - - + @@ -149,7 +124,6 @@ - diff --git a/spring-boot/README.MD b/spring-boot/README.MD index 72da255b95..595e13cd9f 100644 --- a/spring-boot/README.MD +++ b/spring-boot/README.MD @@ -4,12 +4,8 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Quick Guide to @RestClientTest in Spring Boot](http://www.baeldung.com/restclienttest-in-spring-boot) -- [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters) - [A Guide to Spring in Eclipse STS](http://www.baeldung.com/eclipse-sts-spring) -- [Introduction to WebJars](http://www.baeldung.com/maven-webjars) -- [Create a Fat Jar App with Spring Boot](http://www.baeldung.com/deployable-fat-jar-spring-boot) - [The @ServletComponentScan Annotation in Spring Boot](http://www.baeldung.com/spring-servletcomponentscan) -- [A Custom Data Binder in Spring MVC](http://www.baeldung.com/spring-mvc-custom-data-binder) - [Intro to Building an Application with Spring Boot](http://www.baeldung.com/intro-to-spring-boot) - [How to Register a Servlet in a Java Web Application](http://www.baeldung.com/register-servlet) - [Guide to Spring WebUtils and ServletRequestUtils](http://www.baeldung.com/spring-webutils-servletrequestutils) @@ -29,9 +25,11 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Guide to Spring Type Conversions](http://www.baeldung.com/spring-type-conversions) - [Quick Guide on data.sql and schema.sql Files in Spring Boot](http://www.baeldung.com/spring-boot-data-sql-and-schema-sql) - [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8) -- [A Quick Guide to Maven Wrapper](http://www.baeldung.com/maven-wrapper) - [An Introduction to Kong](http://www.baeldung.com/kong) - [Spring Boot Customize Whitelabel Error Page](http://www.baeldung.com/spring-boot-custom-error-page) - [Spring Boot: Configuring a Main Class](http://www.baeldung.com/spring-boot-main-class) -- [Shutdown a Spring Boot Application](http://www.baeldung.com/spring-boot-shutdown) -- [A Quick Intro to the SpringBootServletInitializer](http://www.baeldung.com/spring-boot-servlet-initializer) \ No newline at end of file +- [A Quick Intro to the SpringBootServletInitializer](http://www.baeldung.com/spring-boot-servlet-initializer) +- [How to Define a Spring Boot Filter?](http://www.baeldung.com/spring-boot-add-filter) +- [How to Change the Default Port in Spring Boot](http://www.baeldung.com/spring-boot-change-port) +- [Spring Boot Exit Codes](http://www.baeldung.com/spring-boot-exit-codes) +- [Guide to the Favicon in Spring Boot](http://www.baeldung.com/spring-boot-favicon) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index afc80eb68b..d8ee3cc2d9 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 @@ -196,6 +170,7 @@ **/*LiveTest.java **/*IntegrationTest.java + **/*IntTest.java **/AutoconfigurationTest.java @@ -218,9 +193,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/java/com/baeldung/bootcustomfilters/FilterConfig.java b/spring-boot/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java new file mode 100644 index 0000000000..aa794182de --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/bootcustomfilters/FilterConfig.java @@ -0,0 +1,25 @@ +package com.baeldung.bootcustomfilters; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.bootcustomfilters.filters.RequestResponseLoggingFilter; + +@Configuration +public class FilterConfig { + + // uncomment this and comment the @Component in the filter class definition to register only for a url pattern + // @Bean + public FilterRegistrationBean loggingFilter() { + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + + registrationBean.setFilter(new RequestResponseLoggingFilter()); + + registrationBean.addUrlPatterns("/users/*"); + + return registrationBean; + + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java new file mode 100644 index 0000000000..7cce34a06c --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.shutdownhooks; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@EnableAutoConfiguration +public class ShutdownHookApplication { + + public static void main(String args[]) { + SpringApplication.run(ShutdownHookApplication.class, args); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java new file mode 100644 index 0000000000..e85b9395d3 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java @@ -0,0 +1,14 @@ +package com.baeldung.shutdownhooks.beans; + +import javax.annotation.PreDestroy; + +import org.springframework.stereotype.Component; + +@Component +public class Bean1 { + + @PreDestroy + public void destroy() { + System.out.println("Shutdown triggered using @PreDestroy."); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java new file mode 100644 index 0000000000..e85d12e791 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java @@ -0,0 +1,14 @@ +package com.baeldung.shutdownhooks.beans; + +import org.springframework.beans.factory.DisposableBean; +import org.springframework.stereotype.Component; + +@Component +public class Bean2 implements DisposableBean { + + @Override + public void destroy() throws Exception { + System.out.println("Shutdown triggered using DisposableBean."); + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java new file mode 100644 index 0000000000..bed1d50ee7 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java @@ -0,0 +1,8 @@ +package com.baeldung.shutdownhooks.beans; + +public class Bean3 { + + public void destroy() { + System.out.println("Shutdown triggered using bean destroy method."); + } +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java new file mode 100644 index 0000000000..07d729cb83 --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java @@ -0,0 +1,18 @@ +package com.baeldung.shutdownhooks.config; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +public class ExampleServletContextListener implements ServletContextListener { + + @Override + public void contextDestroyed(ServletContextEvent event) { + System.out.println("Shutdown triggered using ServletContextListener."); + } + + @Override + public void contextInitialized(ServletContextEvent event) { + // Triggers when context initializes + } + +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java b/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java new file mode 100644 index 0000000000..2d0712e19b --- /dev/null +++ b/spring-boot/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java @@ -0,0 +1,25 @@ +package com.baeldung.shutdownhooks.config; + +import javax.servlet.ServletContextListener; + +import org.springframework.boot.web.servlet.ServletListenerRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.shutdownhooks.beans.Bean3; + +@Configuration +public class ShutdownHookConfiguration { + + @Bean(destroyMethod = "destroy") + public Bean3 initializeBean3() { + return new Bean3(); + } + + @Bean + ServletListenerRegistrationBean servletListener() { + ServletListenerRegistrationBean srb = new ServletListenerRegistrationBean<>(); + srb.setListener(new ExampleServletContextListener()); + return srb; + } +} diff --git a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java index a5cf6a0c24..cba504b6c6 100644 --- a/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java +++ b/spring-boot/src/main/java/org/baeldung/repository/UserRepository.java @@ -10,8 +10,6 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; import java.util.Collection; import java.util.List; diff --git a/spring-boot/src/main/resources/application.properties b/spring-boot/src/main/resources/application.properties index 04a4fbf9de..8c02e528ab 100644 --- a/spring-boot/src/main/resources/application.properties +++ b/spring-boot/src/main/resources/application.properties @@ -9,6 +9,7 @@ spring.jpa.hibernate.ddl-auto = update management.endpoints.jmx.domain=Spring Sample Application management.endpoints.jmx.uniqueNames=true +management.endpoints.web.exposure.include=* management.endpoint.shutdown.enabled=true ##jolokia.config.debug=true @@ -27,8 +28,6 @@ info.app.description=This is my first spring boot application G1 info.app.version=1.0.0 info.java-vendor = ${java.specification.vendor} -management.security.role=SUPERUSER - logging.level.org.springframework=INFO #Servlet Configuration 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/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/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java index 6d958ea637..2c3ac2e159 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java @@ -20,7 +20,6 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class) -@AutoConfigureMockMvc @TestPropertySource(properties = { "security.basic.enabled=false" }) public class SpringBootWithServletComponentIntegrationTest { diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java index a13cd250a2..a30d3ed3f2 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java @@ -1,9 +1,15 @@ package com.baeldung.annotation.servletcomponentscan; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import javax.servlet.FilterRegistration; +import javax.servlet.ServletContext; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpStatus; @@ -11,16 +17,8 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; -import javax.servlet.FilterRegistration; -import javax.servlet.ServletContext; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class) -@AutoConfigureMockMvc @TestPropertySource(properties = { "security.basic.enabled=false" }) public class SpringBootWithoutServletComponentIntegrationTest { diff --git a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java index 2c0152b97f..83b893ae5c 100644 --- a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java +++ b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java @@ -16,7 +16,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) -@SpringBootTest +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) @AutoConfigureMockMvc @TestPropertySource(properties = { "security.basic.enabled=false" }) public class AppLiveTest { diff --git a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java index 471565b1c6..3213a10df9 100644 --- a/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java @@ -1,31 +1,27 @@ package com.baeldung.toggle; +import static org.junit.Assert.assertEquals; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import static org.junit.Assert.assertEquals; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = ToggleApplication.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = ToggleApplication.class) @AutoConfigureMockMvc public class ToggleIntegrationTest { @Autowired - SalaryService salaryService; - - @Autowired - EmployeeRepository employeeRepository; + private EmployeeRepository employeeRepository; @Autowired private MockMvc mockMvc; diff --git a/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java index 466d81e658..2afda7565a 100644 --- a/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/converter/controller/StringToEmployeeConverterControllerIntegrationTest.java @@ -17,7 +17,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import org.baeldung.boot.Application; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = Application.class) @AutoConfigureMockMvc public class StringToEmployeeConverterControllerIntegrationTest { diff --git a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java index da9df4db7d..d76dbfc803 100644 --- a/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java +++ b/spring-boot/src/test/java/org/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java @@ -1,23 +1,5 @@ package org.baeldung.demo.boottest; -import org.baeldung.demo.DemoApplication; -import org.baeldung.demo.boottest.Employee; -import org.baeldung.demo.boottest.EmployeeRepository; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; - -import java.io.IOException; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.greaterThanOrEqualTo; @@ -29,8 +11,23 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import java.io.IOException; +import java.util.List; + +import org.baeldung.demo.DemoApplication; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = DemoApplication.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = DemoApplication.class) @AutoConfigureMockMvc // @TestPropertySource(locations = "classpath:application-integrationtest.properties") @AutoConfigureTestDatabase @@ -58,14 +55,22 @@ public class EmployeeRestControllerIntegrationTest { @Test public void givenEmployees_whenGetEmployees_thenStatus200() throws Exception { - createTestEmployee("bob"); createTestEmployee("alex"); - mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2)))) - .andExpect(jsonPath("$[0].name", is("bob"))).andExpect(jsonPath("$[1].name", is("alex"))); + // @formatter:off + mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2)))) + .andExpect(jsonPath("$[0].name", is("bob"))) + .andExpect(jsonPath("$[1].name", is("alex"))); + // @formatter:on } + // + private void createTestEmployee(String name) { Employee emp = new Employee(name); repository.saveAndFlush(emp); diff --git a/spring-cloud-data-flow/batch-job/pom.xml b/spring-cloud-data-flow/batch-job/pom.xml index 123c4aeda6..08439065a4 100644 --- a/spring-cloud-data-flow/batch-job/pom.xml +++ b/spring-cloud-data-flow/batch-job/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-cloud-data-flow/data-flow-server/pom.xml b/spring-cloud-data-flow/data-flow-server/pom.xml index f0d513ce4d..1b81e1ba2d 100644 --- a/spring-cloud-data-flow/data-flow-server/pom.xml +++ b/spring-cloud-data-flow/data-flow-server/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-cloud-data-flow/data-flow-shell/pom.xml b/spring-cloud-data-flow/data-flow-shell/pom.xml index debbe44a4a..0166aa79c2 100644 --- a/spring-cloud-data-flow/data-flow-shell/pom.xml +++ b/spring-cloud-data-flow/data-flow-shell/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-cloud-data-flow/log-sink/pom.xml b/spring-cloud-data-flow/log-sink/pom.xml index 6e541ae3fa..ab367fadd7 100644 --- a/spring-cloud-data-flow/log-sink/pom.xml +++ b/spring-cloud-data-flow/log-sink/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-cloud-data-flow/time-processor/pom.xml b/spring-cloud-data-flow/time-processor/pom.xml index 42d0fa434f..79bae89857 100644 --- a/spring-cloud-data-flow/time-processor/pom.xml +++ b/spring-cloud-data-flow/time-processor/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-cloud-data-flow/time-source/pom.xml b/spring-cloud-data-flow/time-source/pom.xml index 2a50c9b0d0..17d2f5c693 100644 --- a/spring-cloud-data-flow/time-source/pom.xml +++ b/spring-cloud-data-flow/time-source/pom.xml @@ -12,10 +12,10 @@ Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-cloud/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-aws/pom.xml b/spring-cloud/spring-cloud-aws/pom.xml index 2d2c29e53e..d076dc5e8e 100644 --- a/spring-cloud/spring-cloud-aws/pom.xml +++ b/spring-cloud/spring-cloud-aws/pom.xml @@ -66,6 +66,7 @@ **/*IntegrationTest.java + **/*IntTest.java
diff --git a/spring-cloud/spring-cloud-bootstrap/config/pom.xml b/spring-cloud/spring-cloud-bootstrap/config/pom.xml index ace46395c0..14a926fc2c 100644 --- a/spring-cloud/spring-cloud-bootstrap/config/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/config/pom.xml @@ -6,10 +6,10 @@ 1.0.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml b/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml index 7a3ffd81cd..f94d8829f6 100644 --- a/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml @@ -7,10 +7,10 @@ 1.0.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml index 5001b35fb5..fc69c16738 100644 --- a/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml @@ -6,10 +6,10 @@ 1.0.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml b/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml index 2552752e29..c0d920d373 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml @@ -8,10 +8,10 @@ 1.0.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml b/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml index 857ee486c0..3aa2db8f65 100644 --- a/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/svc-rating/pom.xml @@ -8,10 +8,10 @@ 1.0.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml b/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml index 743281d346..8735e24d48 100644 --- a/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/zipkin/pom.xml @@ -6,10 +6,10 @@ 1.0.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-config/pom.xml b/spring-cloud/spring-cloud-config/pom.xml index 100b421a55..0a8f4f9dc3 100644 --- a/spring-cloud/spring-cloud-config/pom.xml +++ b/spring-cloud/spring-cloud-config/pom.xml @@ -9,10 +9,10 @@ pom - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-connectors-heroku/pom.xml b/spring-cloud/spring-cloud-connectors-heroku/pom.xml index 9b5d7c91d9..0363962c95 100644 --- a/spring-cloud/spring-cloud-connectors-heroku/pom.xml +++ b/spring-cloud/spring-cloud-connectors-heroku/pom.xml @@ -65,6 +65,7 @@ true **/*IntegrationTest.java + **/*IntTest.java **/*LongRunningUnitTest.java **/*ManualTest.java **/JdbcTest.java diff --git a/spring-cloud/spring-cloud-gateway/pom.xml b/spring-cloud/spring-cloud-gateway/pom.xml index 4cc45cc6b3..aa523ec604 100644 --- a/spring-cloud/spring-cloud-gateway/pom.xml +++ b/spring-cloud/spring-cloud-gateway/pom.xml @@ -14,21 +14,30 @@ .. + + + + org.springframework.cloud + spring-cloud-gateway + ${cloud.version} + pom + import + + + + + + org.springframework.cloud + spring-cloud-starter-gateway + org.springframework.boot - spring-boot-actuator - ${version} + spring-boot-starter-actuator org.springframework.boot spring-boot-starter-webflux - ${version} - - - org.springframework.cloud - spring-cloud-gateway-core - ${version} @@ -39,12 +48,10 @@ javax.validation validation-api - 2.0.0.Final io.projectreactor.ipc reactor-netty - 0.7.0.M1 @@ -70,8 +77,9 @@ UTF-8 3.7.0 - 1.4.2.RELEASE - 2.0.0.M6 + 2.0.0.RELEASE + 2.0.0.RELEASE + 2.0.0.RC2 diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/spring/cloud/GatewayApplication.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/spring/cloud/GatewayApplication.java index 4d5f61315f..ba384749df 100644 --- a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/spring/cloud/GatewayApplication.java +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/spring/cloud/GatewayApplication.java @@ -9,4 +9,5 @@ public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } + } \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/src/main/resources/application.yml b/spring-cloud/spring-cloud-gateway/src/main/resources/application.yml index 8b981f8071..2450638e46 100644 --- a/spring-cloud/spring-cloud-gateway/src/main/resources/application.yml +++ b/spring-cloud/spring-cloud-gateway/src/main/resources/application.yml @@ -8,6 +8,9 @@ spring: uri: http://www.baeldung.com predicates: - Path=/baeldung + management: - security: - enabled: false \ No newline at end of file + endpoints: + web: + exposure: + include: "*" diff --git a/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationTests.java b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationIntegrationTest.java similarity index 84% rename from spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationTests.java rename to spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationIntegrationTest.java index 5ccc49eaa7..2440b97aaf 100644 --- a/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationTests.java +++ b/spring-cloud/spring-cloud-kubernetes/demo-backend/src/test/java/com/baeldung/spring/cloud/kubernetes/backend/KubernetesBackendApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class KubernetesBackendApplicationTests { +public class KubernetesBackendApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationTests.java b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationIntegrationTest.java similarity index 84% rename from spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationTests.java rename to spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationIntegrationTest.java index 0e34eb45f8..19ad9676cb 100644 --- a/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationTests.java +++ b/spring-cloud/spring-cloud-kubernetes/demo-frontend/src/test/java/com/baeldung/spring/cloud/kubernetes/frontend/KubernetesFrontendApplicationIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest -public class KubernetesFrontendApplicationTests { +public class KubernetesFrontendApplicationIntegrationTest { @Test public void contextLoads() { diff --git a/spring-cloud/spring-cloud-kubernetes/pom.xml b/spring-cloud/spring-cloud-kubernetes/pom.xml index 96388c3672..61fd84ca27 100644 --- a/spring-cloud/spring-cloud-kubernetes/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/pom.xml @@ -14,10 +14,10 @@ - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 4.0.0 diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml index 8da8ef6141..664ab96576 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-books-api/pom.xml @@ -10,10 +10,10 @@ Simple books API - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml index e083986890..814f5edfcb 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-config-server/pom.xml @@ -12,10 +12,10 @@ Spring Cloud REST configuration server - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml index c7d647a154..f3ce213540 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-discovery-server/pom.xml @@ -10,10 +10,10 @@ Spring Cloud REST server - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml index d97ab43bfe..27e327110a 100644 --- a/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml +++ b/spring-cloud/spring-cloud-rest/spring-cloud-rest-reviews-api/pom.xml @@ -10,10 +10,10 @@ Simple reviews API - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../../parent-boot-5 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-ribbon-client/pom.xml b/spring-cloud/spring-cloud-ribbon-client/pom.xml index cada10ec35..64682c6173 100644 --- a/spring-cloud/spring-cloud-ribbon-client/pom.xml +++ b/spring-cloud/spring-cloud-ribbon-client/pom.xml @@ -9,10 +9,10 @@ Introduction to Spring Cloud Rest Client with Netflix Ribbon - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-core/README.md b/spring-core/README.md index 5f50b35553..3684c7f6e9 100644 --- a/spring-core/README.md +++ b/spring-core/README.md @@ -14,3 +14,5 @@ - [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) +- [Spring – Injecting Collections](http://www.baeldung.com/spring-injecting-collections) diff --git a/spring-core/pom.xml b/spring-core/pom.xml index 93ff73bb37..032f2214d2 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -86,7 +86,6 @@ 1.10.19 1.4.4.RELEASE - 4.3.4.RELEASE 1 20.0 2.6 diff --git a/spring-core/src/main/java/com/baeldung/collection/BaeldungBean.java b/spring-core/src/main/java/com/baeldung/collection/BaeldungBean.java new file mode 100644 index 0000000000..6d7351df02 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/collection/BaeldungBean.java @@ -0,0 +1,18 @@ +package com.baeldung.collection; + +/** + * Created by Gebruiker on 5/22/2018. + */ +public class BaeldungBean { + + private String name; + + public BaeldungBean(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } +} diff --git a/spring-core/src/main/java/com/baeldung/collection/CollectionConfig.java b/spring-core/src/main/java/com/baeldung/collection/CollectionConfig.java new file mode 100644 index 0000000000..fbae2963e5 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/collection/CollectionConfig.java @@ -0,0 +1,50 @@ +package com.baeldung.collection; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; + +import java.util.*; + +@Configuration +public class CollectionConfig { + + @Bean + public CollectionsBean getCollectionsBean() { + return new CollectionsBean(new HashSet<>(Arrays.asList("John", "Adam", "Harry"))); + } + + @Bean + public List nameList(){ + return Arrays.asList("John", "Adam", "Harry", null); + } + + @Bean + public Map nameMap(){ + Map nameMap = new HashMap<>(); + nameMap.put(1, "John"); + nameMap.put(2, "Adam"); + nameMap.put(3, "Harry"); + return nameMap; + } + + @Bean + @Qualifier("CollectionsBean") + @Order(2) + public BaeldungBean getElement() { + return new BaeldungBean("John"); + } + + @Bean + @Order(3) + public BaeldungBean getAnotherElement() { + return new BaeldungBean("Adam"); + } + + @Bean + @Order(1) + public BaeldungBean getOneMoreElement() { + return new BaeldungBean("Harry"); + } +} diff --git a/spring-core/src/main/java/com/baeldung/collection/CollectionInjectionDemo.java b/spring-core/src/main/java/com/baeldung/collection/CollectionInjectionDemo.java new file mode 100644 index 0000000000..2e0d9eb8d8 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/collection/CollectionInjectionDemo.java @@ -0,0 +1,20 @@ +package com.baeldung.collection; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +/** + * Created by Gebruiker on 5/18/2018. + */ +public class CollectionInjectionDemo { + + public static void main(String[] args) { + + ApplicationContext context = new AnnotationConfigApplicationContext(CollectionConfig.class); + CollectionsBean collectionsBean = context.getBean(CollectionsBean.class); + collectionsBean.printNameList(); + collectionsBean.printNameSet(); + collectionsBean.printNameMap(); + collectionsBean.printBeanList(); + } +} diff --git a/spring-core/src/main/java/com/baeldung/collection/CollectionsBean.java b/spring-core/src/main/java/com/baeldung/collection/CollectionsBean.java new file mode 100644 index 0000000000..a0e985267f --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/collection/CollectionsBean.java @@ -0,0 +1,54 @@ +package com.baeldung.collection; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Created by Gebruiker on 5/18/2018. + */ +public class CollectionsBean { + + @Autowired + private List nameList; + + private Set nameSet; + + private Map nameMap; + + @Autowired(required = false) + @Qualifier("CollectionsBean") + private List beanList = new ArrayList<>(); + + public CollectionsBean() { + } + + public CollectionsBean(Set strings) { + this.nameSet = strings; + } + + @Autowired + public void setNameMap(Map nameMap) { + this.nameMap = nameMap; + } + + public void printNameList() { + System.out.println(nameList); + } + + public void printNameSet() { + System.out.println(nameSet); + } + + public void printNameMap() { + System.out.println(nameMap); + } + + public void printBeanList() { + System.out.println(beanList); + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependson/DriverApplication.java b/spring-core/src/main/java/com/baeldung/dependson/DriverApplication.java new file mode 100644 index 0000000000..166f388aa3 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependson/DriverApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.dependson; + +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +import com.baeldung.dependson.config.Config; +import com.baeldung.dependson.file.processor.FileProcessor; + +public class DriverApplication { + public static void main(String[] args) { + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class); + ctx.getBean(FileProcessor.class); + ctx.close(); + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependson/config/Config.java b/spring-core/src/main/java/com/baeldung/dependson/config/Config.java new file mode 100644 index 0000000000..8d96707ba6 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependson/config/Config.java @@ -0,0 +1,38 @@ +package com.baeldung.dependson.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; +import org.springframework.context.annotation.Lazy; + +import com.baeldung.dependson.file.processor.FileProcessor; +import com.baeldung.dependson.file.reader.FileReader; +import com.baeldung.dependson.file.writer.FileWriter; +import com.baeldung.dependson.shared.File; + +@Configuration +@ComponentScan("com.baeldung.dependson") +public class Config { + + @Autowired + File file; + + @Bean("fileProcessor") + @DependsOn({"fileReader","fileWriter"}) + @Lazy + public FileProcessor fileProcessor(){ + return new FileProcessor(file); + } + + @Bean("fileReader") + public FileReader fileReader(){ + return new FileReader(file); + } + + @Bean("fileWriter") + public FileWriter fileWriter(){ + return new FileWriter(file); + } +} diff --git a/spring-core/src/main/java/com/baeldung/dependson/file/processor/FileProcessor.java b/spring-core/src/main/java/com/baeldung/dependson/file/processor/FileProcessor.java new file mode 100644 index 0000000000..f5d55dc032 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependson/file/processor/FileProcessor.java @@ -0,0 +1,19 @@ +package com.baeldung.dependson.file.processor; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.baeldung.dependson.file.reader.FileReader; +import com.baeldung.dependson.file.writer.FileWriter; +import com.baeldung.dependson.shared.File; + +public class FileProcessor { + + File file; + + public FileProcessor(File file){ + this.file = file; + if(file.getText().contains("write") && file.getText().contains("read")){ + file.setText("processed"); + } + } +} \ No newline at end of file diff --git a/spring-core/src/main/java/com/baeldung/dependson/file/reader/FileReader.java b/spring-core/src/main/java/com/baeldung/dependson/file/reader/FileReader.java new file mode 100644 index 0000000000..b6ff446534 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependson/file/reader/FileReader.java @@ -0,0 +1,12 @@ +package com.baeldung.dependson.file.reader; + +import com.baeldung.dependson.shared.File; + +public class FileReader { + + public FileReader(File file) { + file.setText("read"); + } + + public void readFile() {} +} diff --git a/spring-core/src/main/java/com/baeldung/dependson/file/writer/FileWriter.java b/spring-core/src/main/java/com/baeldung/dependson/file/writer/FileWriter.java new file mode 100644 index 0000000000..f251166c80 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependson/file/writer/FileWriter.java @@ -0,0 +1,13 @@ +package com.baeldung.dependson.file.writer; + +import com.baeldung.dependson.shared.File; + + +public class FileWriter { + + public FileWriter(File file){ + file.setText("write"); + } + + public void writeFile(){} +} diff --git a/spring-core/src/main/java/com/baeldung/dependson/shared/File.java b/spring-core/src/main/java/com/baeldung/dependson/shared/File.java new file mode 100644 index 0000000000..c1b1badc43 --- /dev/null +++ b/spring-core/src/main/java/com/baeldung/dependson/shared/File.java @@ -0,0 +1,17 @@ +package com.baeldung.dependson.shared; + +import org.springframework.stereotype.Service; + +@Service +public class File { + + private String text = ""; + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = this.text+text; + } +} diff --git a/spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionTest.java b/spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionIntegrationTest.java similarity index 96% rename from spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionTest.java rename to spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionIntegrationTest.java index 57c1927e58..faaadfcbc3 100644 --- a/spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionTest.java +++ b/spring-core/src/test/java/com/baeldung/dependencyinjectiontypes/DependencyInjectionIntegrationTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -public class DependencyInjectionTest { +public class DependencyInjectionIntegrationTest { @Test public void givenAutowiredAnnotation_WhenSetOnSetter_ThenDependencyValid() { diff --git a/spring-core/src/test/java/com/baeldung/dependson/config/TestConfig.java b/spring-core/src/test/java/com/baeldung/dependson/config/TestConfig.java new file mode 100644 index 0000000000..f4b2e39ebc --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/dependson/config/TestConfig.java @@ -0,0 +1,59 @@ +package com.baeldung.dependson.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; +import org.springframework.context.annotation.Lazy; + +import com.baeldung.dependson.file.processor.FileProcessor; +import com.baeldung.dependson.file.reader.FileReader; +import com.baeldung.dependson.file.writer.FileWriter; +import com.baeldung.dependson.shared.File; + +@Configuration +@ComponentScan("com.baeldung.dependson") +public class TestConfig { + + @Autowired + File file; + + @Bean("fileProcessor") + @DependsOn({"fileReader","fileWriter"}) + @Lazy + public FileProcessor fileProcessor(){ + return new FileProcessor(file); + } + + @Bean("fileReader") + public FileReader fileReader(){ + return new FileReader(file); + } + + @Bean("fileWriter") + public FileWriter fileWriter(){ + return new FileWriter(file); + } + + @Bean("dummyFileProcessor") + @DependsOn({"dummyfileWriter"}) + @Lazy + public FileProcessor dummyFileProcessor(){ + return new FileProcessor(file); + } + + @Bean("dummyFileProcessorCircular") + @DependsOn({"dummyFileReaderCircular"}) + @Lazy + public FileProcessor dummyFileProcessorCircular(){ + return new FileProcessor(file); + } + + @Bean("dummyFileReaderCircular") + @DependsOn({"dummyFileProcessorCircular"}) + @Lazy + public FileReader dummyFileReaderCircular(){ + return new FileReader(file); + } +} diff --git a/spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorIntegrationTest.java b/spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorIntegrationTest.java new file mode 100644 index 0000000000..11d9daf3bf --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/dependson/processor/FileProcessorIntegrationTest.java @@ -0,0 +1,42 @@ +package com.baeldung.dependson.processor; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.dependson.config.TestConfig; +import com.baeldung.dependson.shared.File; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = TestConfig.class) +public class FileProcessorIntegrationTest { + + @Autowired + ApplicationContext context; + + @Autowired + File file; + + @Test + public void whenAllBeansCreated_FileTextEndsWithProcessed() { + context.getBean("fileProcessor"); + assertTrue(file.getText().endsWith("processed")); + } + + @Test(expected=NoSuchBeanDefinitionException.class) + public void whenDependentBeanNotAvailable_ThrowsNoSuchBeanDefinitionException(){ + context.getBean("dummyFileProcessor"); + } + + @Test(expected=BeanCreationException.class) + public void whenCircularDependency_ThrowsBeanCreationException(){ + context.getBean("dummyFileReaderCircular"); + } +} diff --git a/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java b/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionIntegrationTest.java similarity index 92% rename from spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java rename to spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionIntegrationTest.java index 1660b99726..4bfb3c5de4 100644 --- a/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionTest.java +++ b/spring-core/src/test/java/com/baeldung/di/spring/BeanInjectionIntegrationTest.java @@ -6,7 +6,7 @@ import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -public class BeanInjectionTest { +public class BeanInjectionIntegrationTest { private ApplicationContext applicationContext; diff --git a/spring-core/src/test/java/com/baeldung/methodinjections/StudentTest.java b/spring-core/src/test/java/com/baeldung/methodinjections/StudentIntegrationTest.java similarity index 97% rename from spring-core/src/test/java/com/baeldung/methodinjections/StudentTest.java rename to spring-core/src/test/java/com/baeldung/methodinjections/StudentIntegrationTest.java index 8c04ef472e..5d326a99dd 100644 --- a/spring-core/src/test/java/com/baeldung/methodinjections/StudentTest.java +++ b/spring-core/src/test/java/com/baeldung/methodinjections/StudentIntegrationTest.java @@ -5,7 +5,7 @@ import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -public class StudentTest { +public class StudentIntegrationTest { @Test public void whenLookupMethodCalled_thenNewInstanceReturned() { diff --git a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java new file mode 100644 index 0000000000..38e8304f0f --- /dev/null +++ b/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java @@ -0,0 +1,101 @@ +package com.baeldung.resource; + +import static org.junit.Assert.assertEquals; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.util.stream.Collectors; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationContext; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.util.ResourceUtils; + +/** + * Test class illustrating various methods of accessing a file from the classpath using Resource. + * @author tritty + * + */ + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class) +public class SpringResourceIntegrationTest { + /** + * Resource loader instance for lazily loading resources. + */ + @Autowired + private ResourceLoader resourceLoader; + + @Autowired + private ApplicationContext appContext; + + /** + * Injecting resource + */ + @Value("classpath:data/employees.dat") + private Resource resourceFile; + + /** + * Data in data/employee.dat + */ + private static final String EMPLOYEES_EXPECTED = "Joe Employee,Jan Employee,James T. Employee"; + + @Test + public void whenResourceLoader_thenReadSuccessful() throws IOException { + final Resource resource = resourceLoader.getResource("classpath:data/employees.dat"); + final String employees = new String(Files.readAllBytes(resource.getFile() + .toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); + } + + @Test + public void whenApplicationContext_thenReadSuccessful() throws IOException { + final Resource resource = appContext.getResource("classpath:data/employees.dat"); + final String employees = new String(Files.readAllBytes(resource.getFile() + .toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); + } + + @Test + public void whenAutowired_thenReadSuccessful() throws IOException { + final String employees = new String(Files.readAllBytes(resourceFile.getFile() + .toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); + } + + @Test + public void whenResourceUtils_thenReadSuccessful() throws IOException { + final File employeeFile = ResourceUtils.getFile("classpath:data/employees.dat"); + final String employees = new String(Files.readAllBytes(employeeFile.toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); + } + + @Test + public void whenResourceAsStream_thenReadSuccessful() throws IOException { + final InputStream resource = new ClassPathResource("data/employees.dat").getInputStream(); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource))) { + final String employees = reader.lines() + .collect(Collectors.joining("\n")); + assertEquals(EMPLOYEES_EXPECTED, employees); + } + } + + @Test + public void whenResourceAsFile_thenReadSuccessful() throws IOException { + final File resource = new ClassPathResource("data/employees.dat").getFile(); + final String employees = new String(Files.readAllBytes(resource.toPath())); + assertEquals(EMPLOYEES_EXPECTED, employees); + } +} 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-core/src/test/resources/data/employees.dat b/spring-core/src/test/resources/data/employees.dat new file mode 100644 index 0000000000..9c28fdf82f --- /dev/null +++ b/spring-core/src/test/resources/data/employees.dat @@ -0,0 +1 @@ +Joe Employee,Jan Employee,James T. Employee \ No newline at end of file diff --git a/spring-cucumber/pom.xml b/spring-cucumber/pom.xml index cabd1a9020..1da4c8a124 100644 --- a/spring-cucumber/pom.xml +++ b/spring-cucumber/pom.xml @@ -10,10 +10,10 @@ Demo project for Spring Boot - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-custom-aop/spring-custom-aop/.gitignore b/spring-custom-aop/.gitignore similarity index 100% rename from spring-custom-aop/spring-custom-aop/.gitignore rename to spring-custom-aop/.gitignore diff --git a/spring-custom-aop/spring-custom-aop/README.MD b/spring-custom-aop/README.MD similarity index 100% rename from spring-custom-aop/spring-custom-aop/README.MD rename to spring-custom-aop/README.MD diff --git a/spring-custom-aop/spring-custom-aop/pom.xml b/spring-custom-aop/pom.xml similarity index 97% rename from spring-custom-aop/spring-custom-aop/pom.xml rename to spring-custom-aop/pom.xml index a1e498f65d..4e95d175e7 100644 --- a/spring-custom-aop/spring-custom-aop/pom.xml +++ b/spring-custom-aop/pom.xml @@ -9,10 +9,10 @@ This is simple boot application for Spring boot actuator test - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../parent-boot-1 diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/utils/controller/UtilsController.java b/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/utils/controller/UtilsController.java deleted file mode 100644 index 7b4827cdf2..0000000000 --- a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/utils/controller/UtilsController.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.utils.controller; - -import javax.servlet.http.HttpServletRequest; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.ServletRequestBindingException; -import org.springframework.web.bind.ServletRequestUtils; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.util.WebUtils; - -@Controller -public class UtilsController { - - @GetMapping("/utils") - public String webUtils(Model model) { - return "utils"; - } - - @PostMapping("/setParam") - public String post(HttpServletRequest request, Model model) { - String param = ServletRequestUtils.getStringParameter(request, "param", "DEFAULT"); - -// Long param = ServletRequestUtils.getLongParameter(request, "param",1L); -// boolean param = ServletRequestUtils.getBooleanParameter(request, "param", true); -// double param = ServletRequestUtils.getDoubleParameter(request, "param", 1000); -// float param = ServletRequestUtils.getFloatParameter(request, "param", (float) 1.00); -// int param = ServletRequestUtils.getIntParameter(request, "param", 100); - -// try { -// ServletRequestUtils.getRequiredStringParameter(request, "param"); -// } catch (ServletRequestBindingException e) { -// e.printStackTrace(); -// } - - WebUtils.setSessionAttribute(request, "parameter", param); - model.addAttribute("parameter", "You set: "+(String) WebUtils.getSessionAttribute(request, "parameter")); - return "utils"; - } - - @GetMapping("/other") - public String other(HttpServletRequest request, Model model) { - String param = (String) WebUtils.getSessionAttribute(request, "parameter"); - model.addAttribute("parameter", param); - return "other"; - } - -} diff --git a/spring-custom-aop/spring-custom-aop/src/main/resources/public/error/404.html b/spring-custom-aop/spring-custom-aop/src/main/resources/public/error/404.html deleted file mode 100644 index df83ce219b..0000000000 --- a/spring-custom-aop/spring-custom-aop/src/main/resources/public/error/404.html +++ /dev/null @@ -1,8 +0,0 @@ - - - RESOURCE NOT FOUND - - -

404 RESOURCE NOT FOUND

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

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

-

Set Parameter:

-

- - -

-
-Another Page - - \ No newline at end of file diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java b/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java rename to spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java b/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java rename to spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java b/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java similarity index 82% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java rename to spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java index bad39c52c4..b1bdc7d781 100644 --- a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java +++ b/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java @@ -9,9 +9,7 @@ public class AttrListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { - servletContextEvent - .getServletContext() - .setAttribute("servlet-context-attr", "test"); + servletContextEvent.getServletContext().setAttribute("servlet-context-attr", "test"); System.out.println("context init"); } diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java b/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java similarity index 89% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java rename to spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java index 3419cd0eaf..d8192c2cb1 100644 --- a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java +++ b/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java @@ -16,9 +16,7 @@ public class EchoServlet extends HttpServlet { @Override public void doPost(HttpServletRequest request, HttpServletResponse response) { try { - Path path = File - .createTempFile("echo", "tmp") - .toPath(); + Path path = File.createTempFile("echo", "tmp").toPath(); Files.copy(request.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); Files.copy(path, response.getOutputStream()); Files.delete(path); diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java b/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java similarity index 90% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java rename to spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java index dc2368c5b2..146e5ae386 100644 --- a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java +++ b/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java @@ -18,9 +18,7 @@ public class HelloFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { - servletResponse - .getOutputStream() - .print(filterConfig.getInitParameter("msg")); + servletResponse.getOutputStream().print(filterConfig.getInitParameter("msg")); filterChain.doFilter(servletRequest, servletResponse); } diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java b/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java similarity index 78% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java rename to spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java index aeae7aecc9..5269c1bf29 100644 --- a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java +++ b/spring-custom-aop/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java @@ -8,22 +8,20 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -@WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello")}) +@WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello") }) public class HelloServlet extends HttpServlet { private ServletConfig servletConfig; @Override - public void init(ServletConfig servletConfig){ + public void init(ServletConfig servletConfig) { this.servletConfig = servletConfig; } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) { try { - response - .getOutputStream() - .write(servletConfig.getInitParameter("msg").getBytes()); + response.getOutputStream().write(servletConfig.getInitParameter("msg").getBytes()); } catch (IOException e) { e.printStackTrace(); } diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/git/CommitIdApplication.java b/spring-custom-aop/src/main/java/com/baeldung/git/CommitIdApplication.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/git/CommitIdApplication.java rename to spring-custom-aop/src/main/java/com/baeldung/git/CommitIdApplication.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/git/CommitInfoController.java b/spring-custom-aop/src/main/java/com/baeldung/git/CommitInfoController.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/git/CommitInfoController.java rename to spring-custom-aop/src/main/java/com/baeldung/git/CommitInfoController.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/git/README.md b/spring-custom-aop/src/main/java/com/baeldung/git/README.md similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/git/README.md rename to spring-custom-aop/src/main/java/com/baeldung/git/README.md diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/internationalization/InternationalizationApp.java b/spring-custom-aop/src/main/java/com/baeldung/internationalization/InternationalizationApp.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/internationalization/InternationalizationApp.java rename to spring-custom-aop/src/main/java/com/baeldung/internationalization/InternationalizationApp.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/internationalization/config/MvcConfig.java b/spring-custom-aop/src/main/java/com/baeldung/internationalization/config/MvcConfig.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/internationalization/config/MvcConfig.java rename to spring-custom-aop/src/main/java/com/baeldung/internationalization/config/MvcConfig.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/internationalization/config/PageController.java b/spring-custom-aop/src/main/java/com/baeldung/internationalization/config/PageController.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/internationalization/config/PageController.java rename to spring-custom-aop/src/main/java/com/baeldung/internationalization/config/PageController.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/intro/App.java b/spring-custom-aop/src/main/java/com/baeldung/intro/App.java similarity index 76% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/intro/App.java rename to spring-custom-aop/src/main/java/com/baeldung/intro/App.java index 3db5d3256e..77cdf4ddb9 100644 --- a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/intro/App.java +++ b/spring-custom-aop/src/main/java/com/baeldung/intro/App.java @@ -4,10 +4,8 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication -public class App -{ - public static void main( String[] args ) - { +public class App { + public static void main(String[] args) { SpringApplication.run(App.class, args); } } diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/intro/controller/HomeController.java b/spring-custom-aop/src/main/java/com/baeldung/intro/controller/HomeController.java similarity index 85% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/intro/controller/HomeController.java rename to spring-custom-aop/src/main/java/com/baeldung/intro/controller/HomeController.java index 2a7111135c..5c0cb2d2de 100644 --- a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/intro/controller/HomeController.java +++ b/spring-custom-aop/src/main/java/com/baeldung/intro/controller/HomeController.java @@ -7,12 +7,12 @@ import org.springframework.web.bind.annotation.RestController; public class HomeController { @RequestMapping("/") - public String root(){ + public String root() { return "Index Page"; } - + @RequestMapping("/local") - public String local(){ + public String local() { return "/local"; } } diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/ApplicationMain.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/ApplicationMain.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/ApplicationMain.java rename to spring-custom-aop/src/main/java/com/baeldung/servlets/ApplicationMain.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java rename to spring-custom-aop/src/main/java/com/baeldung/servlets/configuration/WebAppInitializer.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java similarity index 99% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java rename to spring-custom-aop/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java index 3d6a10c2ac..8dea814bc7 100644 --- a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java +++ b/spring-custom-aop/src/main/java/com/baeldung/servlets/configuration/WebMvcConfigure.java @@ -26,7 +26,6 @@ public class WebMvcConfigure extends WebMvcConfigurerAdapter { configurer.enable(); } - @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver()); diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/props/Constants.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/props/Constants.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/props/Constants.java rename to spring-custom-aop/src/main/java/com/baeldung/servlets/props/Constants.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/props/PropertyLoader.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/props/PropertyLoader.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/props/PropertyLoader.java rename to spring-custom-aop/src/main/java/com/baeldung/servlets/props/PropertyLoader.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java similarity index 89% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java rename to spring-custom-aop/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java index 56a6751326..21e8949653 100644 --- a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java +++ b/spring-custom-aop/src/main/java/com/baeldung/servlets/props/PropertySourcesLoader.java @@ -10,7 +10,8 @@ import org.springframework.core.env.ConfigurableEnvironment; @Configuration @ComponentScan(basePackages = { "com.baeldung.*" }) -@PropertySource("classpath:custom.properties") public class PropertySourcesLoader { +@PropertySource("classpath:custom.properties") +public class PropertySourcesLoader { private static final Logger log = LoggerFactory.getLogger(PropertySourcesLoader.class); diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java rename to spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/GenericCustomServlet.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java similarity index 82% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java rename to spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java index b50a7d5454..992976ca0e 100644 --- a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java +++ b/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/javaee/AnnotationServlet.java @@ -7,9 +7,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -@WebServlet(name = "AnnotationServlet", - description = "Example Servlet Using Annotations", - urlPatterns = { "/annotationservlet" }) +@WebServlet(name = "AnnotationServlet", description = "Example Servlet Using Annotations", urlPatterns = { "/annotationservlet" }) public class AnnotationServlet extends HttpServlet { private static final long serialVersionUID = 1L; diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java rename to spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/javaee/EEWebXmlServlet.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java rename to spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/springboot/SpringRegistrationBeanServlet.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java b/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java rename to spring-custom-aop/src/main/java/com/baeldung/servlets/servlets/springboot/embedded/EmbeddedTomcatExample.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/utils/Application.java b/spring-custom-aop/src/main/java/com/baeldung/utils/Application.java similarity index 63% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/utils/Application.java rename to spring-custom-aop/src/main/java/com/baeldung/utils/Application.java index a3d9f9130c..46cf3fb4aa 100644 --- a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/utils/Application.java +++ b/spring-custom-aop/src/main/java/com/baeldung/utils/Application.java @@ -7,12 +7,12 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication -@ComponentScan(basePackages="com.baeldung.utils") +@ComponentScan(basePackages = "com.baeldung.utils") public class Application { - @RolesAllowed("*") - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } + @RolesAllowed("*") + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } } diff --git a/spring-custom-aop/src/main/java/com/baeldung/utils/controller/UtilsController.java b/spring-custom-aop/src/main/java/com/baeldung/utils/controller/UtilsController.java new file mode 100644 index 0000000000..8c7f2f932a --- /dev/null +++ b/spring-custom-aop/src/main/java/com/baeldung/utils/controller/UtilsController.java @@ -0,0 +1,48 @@ +package com.baeldung.utils.controller; + +import javax.servlet.http.HttpServletRequest; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.ServletRequestUtils; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.util.WebUtils; + +@Controller +public class UtilsController { + + @GetMapping("/utils") + public String webUtils(Model model) { + return "utils"; + } + + @PostMapping("/setParam") + public String post(HttpServletRequest request, Model model) { + String param = ServletRequestUtils.getStringParameter(request, "param", "DEFAULT"); + + // Long param = ServletRequestUtils.getLongParameter(request, "param",1L); + // boolean param = ServletRequestUtils.getBooleanParameter(request, "param", true); + // double param = ServletRequestUtils.getDoubleParameter(request, "param", 1000); + // float param = ServletRequestUtils.getFloatParameter(request, "param", (float) 1.00); + // int param = ServletRequestUtils.getIntParameter(request, "param", 100); + + // try { + // ServletRequestUtils.getRequiredStringParameter(request, "param"); + // } catch (ServletRequestBindingException e) { + // e.printStackTrace(); + // } + + WebUtils.setSessionAttribute(request, "parameter", param); + model.addAttribute("parameter", "You set: " + (String) WebUtils.getSessionAttribute(request, "parameter")); + return "utils"; + } + + @GetMapping("/other") + public String other(HttpServletRequest request, Model model) { + String param = (String) WebUtils.getSessionAttribute(request, "parameter"); + model.addAttribute("parameter", param); + return "other"; + } + +} diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/webjar/TestController.java b/spring-custom-aop/src/main/java/com/baeldung/webjar/TestController.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/webjar/TestController.java rename to spring-custom-aop/src/main/java/com/baeldung/webjar/TestController.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java b/spring-custom-aop/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java similarity index 84% rename from spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java rename to spring-custom-aop/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java index d2135754c9..2397861f1d 100644 --- a/spring-custom-aop/spring-custom-aop/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java +++ b/spring-custom-aop/src/main/java/com/baeldung/webjar/WebjarsdemoApplication.java @@ -2,7 +2,6 @@ package com.baeldung.webjar; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; @SpringBootApplication public class WebjarsdemoApplication { diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/Application.java b/spring-custom-aop/src/main/java/org/baeldung/Application.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/Application.java rename to spring-custom-aop/src/main/java/org/baeldung/Application.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/DemoApplication.java b/spring-custom-aop/src/main/java/org/baeldung/boot/DemoApplication.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/DemoApplication.java rename to spring-custom-aop/src/main/java/org/baeldung/boot/DemoApplication.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/components/FooService.java b/spring-custom-aop/src/main/java/org/baeldung/boot/components/FooService.java similarity index 98% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/components/FooService.java rename to spring-custom-aop/src/main/java/org/baeldung/boot/components/FooService.java index 235fd43299..4ff8e9fdd4 100644 --- a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/components/FooService.java +++ b/spring-custom-aop/src/main/java/org/baeldung/boot/components/FooService.java @@ -10,11 +10,11 @@ public class FooService { @Autowired private FooRepository fooRepository; - + public Foo getFooWithId(Integer id) throws Exception { return fooRepository.findOne(id); } - + public Foo getFooWithName(String name) { return fooRepository.findByName(name); } diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/exceptions/CommonException.java b/spring-custom-aop/src/main/java/org/baeldung/boot/exceptions/CommonException.java similarity index 62% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/exceptions/CommonException.java rename to spring-custom-aop/src/main/java/org/baeldung/boot/exceptions/CommonException.java index 1f008440e6..e03b859eab 100644 --- a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/exceptions/CommonException.java +++ b/spring-custom-aop/src/main/java/org/baeldung/boot/exceptions/CommonException.java @@ -1,13 +1,13 @@ package org.baeldung.boot.exceptions; -public class CommonException extends RuntimeException{ +public class CommonException extends RuntimeException { /** * */ private static final long serialVersionUID = 3080004140659213332L; - public CommonException(String message){ + public CommonException(String message) { super(message); } } diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java b/spring-custom-aop/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java similarity index 60% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java rename to spring-custom-aop/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java index 68ef3fa389..0b04bd2759 100644 --- a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java +++ b/spring-custom-aop/src/main/java/org/baeldung/boot/exceptions/FooNotFoundException.java @@ -1,13 +1,13 @@ package org.baeldung.boot.exceptions; -public class FooNotFoundException extends RuntimeException{ +public class FooNotFoundException extends RuntimeException { /** * */ private static final long serialVersionUID = 9042200028456133589L; - public FooNotFoundException(String message){ + public FooNotFoundException(String message) { super(message); } } diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/model/Foo.java b/spring-custom-aop/src/main/java/org/baeldung/boot/model/Foo.java similarity index 99% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/model/Foo.java rename to spring-custom-aop/src/main/java/org/baeldung/boot/model/Foo.java index ac8a8fe429..d373e25b85 100644 --- a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/model/Foo.java +++ b/spring-custom-aop/src/main/java/org/baeldung/boot/model/Foo.java @@ -21,7 +21,6 @@ public class Foo implements Serializable { this.name = name; } - public Foo(Integer id, String name) { super(); this.id = id; diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/repository/FooRepository.java b/spring-custom-aop/src/main/java/org/baeldung/boot/repository/FooRepository.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/repository/FooRepository.java rename to spring-custom-aop/src/main/java/org/baeldung/boot/repository/FooRepository.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/service/FooController.java b/spring-custom-aop/src/main/java/org/baeldung/boot/service/FooController.java similarity index 99% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/service/FooController.java rename to spring-custom-aop/src/main/java/org/baeldung/boot/service/FooController.java index 834fa342e2..d400c3bf9e 100644 --- a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/boot/service/FooController.java +++ b/spring-custom-aop/src/main/java/org/baeldung/boot/service/FooController.java @@ -18,7 +18,7 @@ public class FooController { public Foo getFooWithId(@PathVariable Integer id) throws Exception { return fooService.getFooWithId(id); } - + @GetMapping("/") public Foo getFooWithName(@RequestParam String name) throws Exception { return fooService.getFooWithName(name); diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/client/Details.java b/spring-custom-aop/src/main/java/org/baeldung/client/Details.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/client/Details.java rename to spring-custom-aop/src/main/java/org/baeldung/client/Details.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/client/DetailsServiceClient.java b/spring-custom-aop/src/main/java/org/baeldung/client/DetailsServiceClient.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/client/DetailsServiceClient.java rename to spring-custom-aop/src/main/java/org/baeldung/client/DetailsServiceClient.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/common/error/MyCustomErrorController.java b/spring-custom-aop/src/main/java/org/baeldung/common/error/MyCustomErrorController.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/common/error/MyCustomErrorController.java rename to spring-custom-aop/src/main/java/org/baeldung/common/error/MyCustomErrorController.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java b/spring-custom-aop/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java rename to spring-custom-aop/src/main/java/org/baeldung/common/error/SpringHelloServletRegistrationBean.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/common/error/controller/ErrorController.java b/spring-custom-aop/src/main/java/org/baeldung/common/error/controller/ErrorController.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/common/error/controller/ErrorController.java rename to spring-custom-aop/src/main/java/org/baeldung/common/error/controller/ErrorController.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java b/spring-custom-aop/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java rename to spring-custom-aop/src/main/java/org/baeldung/common/properties/MyServletContainerCustomizationBean.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java b/spring-custom-aop/src/main/java/org/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java rename to spring-custom-aop/src/main/java/org/baeldung/common/resources/ExecutorServiceExitCodeGenerator.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/config/WebConfig.java b/spring-custom-aop/src/main/java/org/baeldung/config/WebConfig.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/config/WebConfig.java rename to spring-custom-aop/src/main/java/org/baeldung/config/WebConfig.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/controller/GenericEntityController.java b/spring-custom-aop/src/main/java/org/baeldung/controller/GenericEntityController.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/controller/GenericEntityController.java rename to spring-custom-aop/src/main/java/org/baeldung/controller/GenericEntityController.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/controller/servlet/HelloWorldServlet.java b/spring-custom-aop/src/main/java/org/baeldung/controller/servlet/HelloWorldServlet.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/controller/servlet/HelloWorldServlet.java rename to spring-custom-aop/src/main/java/org/baeldung/controller/servlet/HelloWorldServlet.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/controller/servlet/SpringHelloWorldServlet.java b/spring-custom-aop/src/main/java/org/baeldung/controller/servlet/SpringHelloWorldServlet.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/controller/servlet/SpringHelloWorldServlet.java rename to spring-custom-aop/src/main/java/org/baeldung/controller/servlet/SpringHelloWorldServlet.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/converter/StringToEnumConverterFactory.java b/spring-custom-aop/src/main/java/org/baeldung/converter/StringToEnumConverterFactory.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/converter/StringToEnumConverterFactory.java rename to spring-custom-aop/src/main/java/org/baeldung/converter/StringToEnumConverterFactory.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/converter/StringToLocalDateTimeConverter.java b/spring-custom-aop/src/main/java/org/baeldung/converter/StringToLocalDateTimeConverter.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/converter/StringToLocalDateTimeConverter.java rename to spring-custom-aop/src/main/java/org/baeldung/converter/StringToLocalDateTimeConverter.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/domain/GenericEntity.java b/spring-custom-aop/src/main/java/org/baeldung/domain/GenericEntity.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/domain/GenericEntity.java rename to spring-custom-aop/src/main/java/org/baeldung/domain/GenericEntity.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/domain/Modes.java b/spring-custom-aop/src/main/java/org/baeldung/domain/Modes.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/domain/Modes.java rename to spring-custom-aop/src/main/java/org/baeldung/domain/Modes.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/endpoints/CustomEndpoint.java b/spring-custom-aop/src/main/java/org/baeldung/endpoints/CustomEndpoint.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/endpoints/CustomEndpoint.java rename to spring-custom-aop/src/main/java/org/baeldung/endpoints/CustomEndpoint.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/endpoints/EndpointDTO.java b/spring-custom-aop/src/main/java/org/baeldung/endpoints/EndpointDTO.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/endpoints/EndpointDTO.java rename to spring-custom-aop/src/main/java/org/baeldung/endpoints/EndpointDTO.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/endpoints/ListEndpoints.java b/spring-custom-aop/src/main/java/org/baeldung/endpoints/ListEndpoints.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/endpoints/ListEndpoints.java rename to spring-custom-aop/src/main/java/org/baeldung/endpoints/ListEndpoints.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/endpoints/MyHealthCheck.java b/spring-custom-aop/src/main/java/org/baeldung/endpoints/MyHealthCheck.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/endpoints/MyHealthCheck.java rename to spring-custom-aop/src/main/java/org/baeldung/endpoints/MyHealthCheck.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/main/SpringBootApplication.java b/spring-custom-aop/src/main/java/org/baeldung/main/SpringBootApplication.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/main/SpringBootApplication.java rename to spring-custom-aop/src/main/java/org/baeldung/main/SpringBootApplication.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java b/spring-custom-aop/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java rename to spring-custom-aop/src/main/java/org/baeldung/monitor/jmx/MonitoringConfig.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/repository/GenericEntityRepository.java b/spring-custom-aop/src/main/java/org/baeldung/repository/GenericEntityRepository.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/repository/GenericEntityRepository.java rename to spring-custom-aop/src/main/java/org/baeldung/repository/GenericEntityRepository.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/service/LoginService.java b/spring-custom-aop/src/main/java/org/baeldung/service/LoginService.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/service/LoginService.java rename to spring-custom-aop/src/main/java/org/baeldung/service/LoginService.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/service/LoginServiceImpl.java b/spring-custom-aop/src/main/java/org/baeldung/service/LoginServiceImpl.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/service/LoginServiceImpl.java rename to spring-custom-aop/src/main/java/org/baeldung/service/LoginServiceImpl.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/session/exception/Application.java b/spring-custom-aop/src/main/java/org/baeldung/session/exception/Application.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/session/exception/Application.java rename to spring-custom-aop/src/main/java/org/baeldung/session/exception/Application.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/session/exception/repository/FooRepository.java b/spring-custom-aop/src/main/java/org/baeldung/session/exception/repository/FooRepository.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/session/exception/repository/FooRepository.java rename to spring-custom-aop/src/main/java/org/baeldung/session/exception/repository/FooRepository.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java b/spring-custom-aop/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java rename to spring-custom-aop/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/web/resolver/HeaderVersionArgumentResolver.java b/spring-custom-aop/src/main/java/org/baeldung/web/resolver/HeaderVersionArgumentResolver.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/web/resolver/HeaderVersionArgumentResolver.java rename to spring-custom-aop/src/main/java/org/baeldung/web/resolver/HeaderVersionArgumentResolver.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/web/resolver/Version.java b/spring-custom-aop/src/main/java/org/baeldung/web/resolver/Version.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/java/org/baeldung/web/resolver/Version.java rename to spring-custom-aop/src/main/java/org/baeldung/web/resolver/Version.java diff --git a/spring-custom-aop/spring-custom-aop/src/main/resources/application.properties b/spring-custom-aop/src/main/resources/application.properties similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/resources/application.properties rename to spring-custom-aop/src/main/resources/application.properties diff --git a/spring-custom-aop/spring-custom-aop/src/main/resources/banner.txt b/spring-custom-aop/src/main/resources/banner.txt similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/resources/banner.txt rename to spring-custom-aop/src/main/resources/banner.txt diff --git a/spring-custom-aop/spring-custom-aop/src/main/resources/custom.properties b/spring-custom-aop/src/main/resources/custom.properties similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/resources/custom.properties rename to spring-custom-aop/src/main/resources/custom.properties diff --git a/spring-custom-aop/spring-custom-aop/src/main/resources/demo.properties b/spring-custom-aop/src/main/resources/demo.properties similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/resources/demo.properties rename to spring-custom-aop/src/main/resources/demo.properties diff --git a/handling-spring-static-resources/src/main/resources/logback.xml b/spring-custom-aop/src/main/resources/logback.xml similarity index 100% rename from handling-spring-static-resources/src/main/resources/logback.xml rename to spring-custom-aop/src/main/resources/logback.xml diff --git a/spring-custom-aop/spring-custom-aop/src/main/resources/messages.properties b/spring-custom-aop/src/main/resources/messages.properties similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/resources/messages.properties rename to spring-custom-aop/src/main/resources/messages.properties diff --git a/spring-custom-aop/spring-custom-aop/src/main/resources/messages_fr.properties b/spring-custom-aop/src/main/resources/messages_fr.properties similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/resources/messages_fr.properties rename to spring-custom-aop/src/main/resources/messages_fr.properties diff --git a/spring-boot/src/main/resources/templates/error/404.html b/spring-custom-aop/src/main/resources/public/error/404.html similarity index 100% rename from spring-boot/src/main/resources/templates/error/404.html rename to spring-custom-aop/src/main/resources/public/error/404.html diff --git a/spring-custom-aop/spring-custom-aop/src/main/resources/templates/index.html b/spring-custom-aop/src/main/resources/templates/index.html similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/resources/templates/index.html rename to spring-custom-aop/src/main/resources/templates/index.html diff --git a/spring-custom-aop/spring-custom-aop/src/main/resources/templates/international.html b/spring-custom-aop/src/main/resources/templates/international.html similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/resources/templates/international.html rename to spring-custom-aop/src/main/resources/templates/international.html diff --git a/spring-boot/src/main/resources/templates/other.html b/spring-custom-aop/src/main/resources/templates/other.html similarity index 100% rename from spring-boot/src/main/resources/templates/other.html rename to spring-custom-aop/src/main/resources/templates/other.html diff --git a/spring-boot/src/main/resources/templates/utils.html b/spring-custom-aop/src/main/resources/templates/utils.html similarity index 100% rename from spring-boot/src/main/resources/templates/utils.html rename to spring-custom-aop/src/main/resources/templates/utils.html diff --git a/spring-custom-aop/spring-custom-aop/src/main/webapp/WEB-INF/context.xml b/spring-custom-aop/src/main/webapp/WEB-INF/context.xml similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/webapp/WEB-INF/context.xml rename to spring-custom-aop/src/main/webapp/WEB-INF/context.xml diff --git a/spring-custom-aop/spring-custom-aop/src/main/webapp/WEB-INF/dispatcher.xml b/spring-custom-aop/src/main/webapp/WEB-INF/dispatcher.xml similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/webapp/WEB-INF/dispatcher.xml rename to spring-custom-aop/src/main/webapp/WEB-INF/dispatcher.xml diff --git a/spring-custom-aop/spring-custom-aop/src/main/webapp/WEB-INF/web.xml b/spring-custom-aop/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/webapp/WEB-INF/web.xml rename to spring-custom-aop/src/main/webapp/WEB-INF/web.xml diff --git a/spring-custom-aop/spring-custom-aop/src/main/webapp/annotationservlet.jsp b/spring-custom-aop/src/main/webapp/annotationservlet.jsp similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/webapp/annotationservlet.jsp rename to spring-custom-aop/src/main/webapp/annotationservlet.jsp diff --git a/spring-custom-aop/spring-custom-aop/src/main/webapp/index.jsp b/spring-custom-aop/src/main/webapp/index.jsp similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/webapp/index.jsp rename to spring-custom-aop/src/main/webapp/index.jsp diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java b/spring-custom-aop/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java similarity index 86% rename from spring-custom-aop/spring-custom-aop/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java rename to spring-custom-aop/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java index 8d5eb56bf4..f6d2a8c465 100644 --- a/spring-custom-aop/spring-custom-aop/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java +++ b/spring-custom-aop/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java @@ -17,12 +17,13 @@ import javax.servlet.ServletContext; import static org.junit.Assert.*; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = SpringBootAnnotatedApp.class) @AutoConfigureMockMvc @TestPropertySource(properties = { "security.basic.enabled=false" }) public class SpringBootWithServletComponentIntegrationTest { - @Autowired private ServletContext servletContext; + @Autowired + private ServletContext servletContext; @Test public void givenServletContext_whenAccessAttrs_thenFoundAttrsPutInServletListner() { @@ -37,12 +38,11 @@ public class SpringBootWithServletComponentIntegrationTest { FilterRegistration filterRegistration = servletContext.getFilterRegistration("hello filter"); assertNotNull(filterRegistration); - assertTrue(filterRegistration - .getServletNameMappings() - .contains("echo servlet")); + assertTrue(filterRegistration.getServletNameMappings().contains("echo servlet")); } - @Autowired private TestRestTemplate restTemplate; + @Autowired + private TestRestTemplate restTemplate; @Test public void givenServletFilter_whenGetHello_thenRequestFiltered() { @@ -58,8 +58,4 @@ public class SpringBootWithServletComponentIntegrationTest { assertEquals("filtering echo", responseEntity.getBody()); } - - } - - diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java b/spring-custom-aop/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java similarity index 81% rename from spring-custom-aop/spring-custom-aop/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java rename to spring-custom-aop/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java index 64507ad02c..e7e1d5486c 100644 --- a/spring-custom-aop/spring-custom-aop/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java +++ b/spring-custom-aop/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java @@ -1,5 +1,12 @@ package com.baeldung.annotation.servletcomponentscan; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import javax.servlet.FilterRegistration; +import javax.servlet.ServletContext; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -11,20 +18,17 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; -import javax.servlet.FilterRegistration; -import javax.servlet.ServletContext; - -import static org.junit.Assert.*; - @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = SpringBootPlainApp.class) @AutoConfigureMockMvc @TestPropertySource(properties = { "security.basic.enabled=false" }) public class SpringBootWithoutServletComponentIntegrationTest { - @Autowired private ServletContext servletContext; + @Autowired + private ServletContext servletContext; - @Autowired private TestRestTemplate restTemplate; + @Autowired + private TestRestTemplate restTemplate; @Test public void givenServletContext_whenAccessAttrs_thenNotFound() { @@ -46,5 +50,3 @@ public class SpringBootWithoutServletComponentIntegrationTest { } } - - diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java b/spring-custom-aop/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java rename to spring-custom-aop/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/com/baeldung/intro/AppLiveTest.java b/spring-custom-aop/src/test/java/com/baeldung/intro/AppLiveTest.java similarity index 81% rename from spring-custom-aop/spring-custom-aop/src/test/java/com/baeldung/intro/AppLiveTest.java rename to spring-custom-aop/src/test/java/com/baeldung/intro/AppLiveTest.java index af46fe0423..83b893ae5c 100644 --- a/spring-custom-aop/spring-custom-aop/src/test/java/com/baeldung/intro/AppLiveTest.java +++ b/spring-custom-aop/src/test/java/com/baeldung/intro/AppLiveTest.java @@ -16,7 +16,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) -@SpringBootTest +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) @AutoConfigureMockMvc @TestPropertySource(properties = { "security.basic.enabled=false" }) public class AppLiveTest { @@ -26,16 +26,12 @@ public class AppLiveTest { @Test public void getIndex() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(equalTo("Index Page"))); + mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("Index Page"))); } @Test public void getLocal() throws Exception { - mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().string(equalTo("/local"))); + mvc.perform(MockMvcRequestBuilders.get("/local").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("/local"))); } } \ No newline at end of file diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java b/spring-custom-aop/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java similarity index 77% rename from spring-custom-aop/spring-custom-aop/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java rename to spring-custom-aop/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java index 829c0a6ac4..99e719d7e9 100644 --- a/spring-custom-aop/spring-custom-aop/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java +++ b/spring-custom-aop/src/test/java/com/baeldung/utils/UtilsControllerIntegrationTest.java @@ -10,32 +10,26 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import com.baeldung.utils.controller.UtilsController; public class UtilsControllerIntegrationTest { - @InjectMocks + @InjectMocks private UtilsController utilsController; - + private MockMvc mockMvc; - + @Before public void setup() { MockitoAnnotations.initMocks(this); - this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController) - .build(); + this.mockMvc = MockMvcBuilders.standaloneSetup(utilsController).build(); } - + @Test public void givenParameter_setRequestParam_andSetSessionAttribute() throws Exception { - String param = "testparam"; - this.mockMvc.perform( - post("/setParam") - .param("param", param) - .sessionAttr("parameter", param)) - .andExpect(status().isOk()); + String param = "testparam"; + this.mockMvc.perform(post("/setParam").param("param", param).sessionAttr("parameter", param)).andExpect(status().isOk()); } - + } diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java b/spring-custom-aop/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java rename to spring-custom-aop/src/test/java/com/baeldung/webjar/WebjarsdemoApplicationIntegrationTest.java diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java rename to spring-custom-aop/src/test/java/org/baeldung/SpringBootApplicationIntegrationTest.java diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java rename to spring-custom-aop/src/test/java/org/baeldung/SpringBootJPAIntegrationTest.java diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java similarity index 95% rename from spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java rename to spring-custom-aop/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java index 10e3d6d60b..14386d73c1 100644 --- a/spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java +++ b/spring-custom-aop/src/test/java/org/baeldung/SpringBootMailIntegrationTest.java @@ -9,8 +9,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.web.context.WebApplicationContext; import org.subethamail.wiser.Wiser; import org.subethamail.wiser.WiserMessage; diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java rename to spring-custom-aop/src/test/java/org/baeldung/boot/ApplicationIntegrationTest.java diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java rename to spring-custom-aop/src/test/java/org/baeldung/boot/DemoApplicationIntegrationTest.java diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/FooComponentIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/boot/FooComponentIntegrationTest.java similarity index 96% rename from spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/FooComponentIntegrationTest.java rename to spring-custom-aop/src/test/java/org/baeldung/boot/FooComponentIntegrationTest.java index df975df0c1..07a5495e8a 100644 --- a/spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/FooComponentIntegrationTest.java +++ b/spring-custom-aop/src/test/java/org/baeldung/boot/FooComponentIntegrationTest.java @@ -23,9 +23,7 @@ import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.doReturn; @RunWith(SpringRunner.class) -@SpringBootTest( - classes = DemoApplication.class, - webEnvironment = WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = DemoApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class FooComponentIntegrationTest { @Autowired diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/FooIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/boot/FooIntegrationTest.java similarity index 76% rename from spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/FooIntegrationTest.java rename to spring-custom-aop/src/test/java/org/baeldung/boot/FooIntegrationTest.java index 932cce26d5..52728fbb5b 100644 --- a/spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/FooIntegrationTest.java +++ b/spring-custom-aop/src/test/java/org/baeldung/boot/FooIntegrationTest.java @@ -1,4 +1,5 @@ package org.baeldung.boot; + import java.util.HashMap; import java.util.Map; @@ -16,28 +17,27 @@ import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) -@SpringBootTest(classes=DemoApplication.class,webEnvironment = WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = DemoApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class FooIntegrationTest { @Autowired private TestRestTemplate testRestTemplate; - - + @Test - public void givenInquiryingFooWithId_whenIdIsValid_thenHttpStatusOK(){ - Map pathVariables = new HashMap(); + public void givenInquiryingFooWithId_whenIdIsValid_thenHttpStatusOK() { + Map pathVariables = new HashMap(); pathVariables.put("id", "1"); ResponseEntity fooResponse = testRestTemplate.getForEntity("/{id}", Foo.class, pathVariables); Assert.assertNotNull(fooResponse); - Assert.assertEquals(HttpStatus.OK,fooResponse.getStatusCode()); + Assert.assertEquals(HttpStatus.OK, fooResponse.getStatusCode()); } - + @Test - public void givenInquiryingFooWithName_whenNameIsValid_thenHttpStatusOK(){ - Map pathVariables = new HashMap(); + public void givenInquiryingFooWithName_whenNameIsValid_thenHttpStatusOK() { + Map pathVariables = new HashMap(); pathVariables.put("name", "Foo_Name"); ResponseEntity fooResponse = testRestTemplate.getForEntity("/?name={name}", Foo.class, pathVariables); Assert.assertNotNull(fooResponse); - Assert.assertEquals(HttpStatus.OK,fooResponse.getStatusCode()); + Assert.assertEquals(HttpStatus.OK, fooResponse.getStatusCode()); } } \ No newline at end of file diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/FooJPAIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/boot/FooJPAIntegrationTest.java similarity index 87% rename from spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/FooJPAIntegrationTest.java rename to spring-custom-aop/src/test/java/org/baeldung/boot/FooJPAIntegrationTest.java index 87afe565ee..40f1892be8 100644 --- a/spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/FooJPAIntegrationTest.java +++ b/spring-custom-aop/src/test/java/org/baeldung/boot/FooJPAIntegrationTest.java @@ -27,8 +27,8 @@ public class FooJPAIntegrationTest { this.entityManager.persist(new Foo("Foo_Name_2")); Foo foo = this.repository.findByName("Foo_Name_2"); assertNotNull(foo); - assertEquals("Foo_Name_2",foo.getName()); - // Due to having Insert query for Foo with Id 1, so TestEntityManager generates new Id of 2 - assertEquals(2l,foo.getId().longValue()); + assertEquals("Foo_Name_2", foo.getName()); + // Due to having Insert query for Foo with Id 1, so TestEntityManager generates new Id of 2 + assertEquals(2l, foo.getId().longValue()); } } \ No newline at end of file diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/FooJsonIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/boot/FooJsonIntegrationTest.java similarity index 94% rename from spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/FooJsonIntegrationTest.java rename to spring-custom-aop/src/test/java/org/baeldung/boot/FooJsonIntegrationTest.java index c74fd83e89..939e66f356 100644 --- a/spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/FooJsonIntegrationTest.java +++ b/spring-custom-aop/src/test/java/org/baeldung/boot/FooJsonIntegrationTest.java @@ -16,7 +16,6 @@ public class FooJsonIntegrationTest { @Autowired private JacksonTester json; - @Test public void testSerialize() throws Exception { @@ -30,6 +29,6 @@ public class FooJsonIntegrationTest { public void testDeserialize() throws Exception { String content = "{\"id\":4,\"name\":\"Foo_Name_4\"}"; assertThat(this.json.parseObject(content).getName()).isEqualTo("Foo_Name_4"); - assertThat(this.json.parseObject(content).getId()==4); + assertThat(this.json.parseObject(content).getId() == 4); } } \ No newline at end of file diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java rename to spring-custom-aop/src/test/java/org/baeldung/boot/repository/FooRepositoryIntegrationTest.java diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java rename to spring-custom-aop/src/test/java/org/baeldung/boot/repository/HibernateSessionIntegrationTest.java diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java rename to spring-custom-aop/src/test/java/org/baeldung/boot/repository/NoHibernateSessionIntegrationTest.java diff --git a/spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java b/spring-custom-aop/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java rename to spring-custom-aop/src/test/java/org/baeldung/client/DetailsServiceClientIntegrationTest.java diff --git a/spring-custom-aop/spring-custom-aop/src/test/resources/application.properties b/spring-custom-aop/src/test/resources/application.properties similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/test/resources/application.properties rename to spring-custom-aop/src/test/resources/application.properties diff --git a/spring-custom-aop/spring-custom-aop/src/test/resources/exception-hibernate.properties b/spring-custom-aop/src/test/resources/exception-hibernate.properties similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/test/resources/exception-hibernate.properties rename to spring-custom-aop/src/test/resources/exception-hibernate.properties diff --git a/spring-custom-aop/spring-custom-aop/src/test/resources/exception.properties b/spring-custom-aop/src/test/resources/exception.properties similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/test/resources/exception.properties rename to spring-custom-aop/src/test/resources/exception.properties diff --git a/spring-custom-aop/spring-custom-aop/src/test/resources/import.sql b/spring-custom-aop/src/test/resources/import.sql similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/test/resources/import.sql rename to spring-custom-aop/src/test/resources/import.sql diff --git a/spring-custom-aop/spring-custom-aop/src/test/resources/org/baeldung/boot/expected.json b/spring-custom-aop/src/test/resources/org/baeldung/boot/expected.json similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/test/resources/org/baeldung/boot/expected.json rename to spring-custom-aop/src/test/resources/org/baeldung/boot/expected.json diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegationTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTest.java similarity index 92% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegationTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTest.java index cb671dc469..05ba58d616 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegationTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTest.java @@ -9,6 +9,6 @@ import org.springframework.test.context.support.DependencyInjectionTestExecution @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { MultiBucketCouchbaseConfig.class, MultiBucketIntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public abstract class MultiBucketIntegationTest { +public abstract class MultiBucketIntegrationTest { } diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java index 71648cf59b..0996b252f1 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplIntegrationTest.java @@ -10,7 +10,7 @@ import java.util.Set; import javax.annotation.PostConstruct; import org.baeldung.spring.data.couchbase.model.Campus; -import org.baeldung.spring.data.couchbase2b.MultiBucketIntegationTest; +import org.baeldung.spring.data.couchbase2b.MultiBucketIntegrationTest; import org.baeldung.spring.data.couchbase2b.repos.CampusRepository; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -18,7 +18,7 @@ import org.springframework.data.geo.Distance; import org.springframework.data.geo.Metrics; import org.springframework.data.geo.Point; -public class CampusServiceImplIntegrationTest extends MultiBucketIntegationTest { +public class CampusServiceImplIntegrationTest extends MultiBucketIntegrationTest { @Autowired private CampusServiceImpl campusService; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java index 819798d536..45475e50f6 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplIntegrationTest.java @@ -9,7 +9,7 @@ import java.util.List; import org.baeldung.spring.data.couchbase.model.Person; import org.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig; -import org.baeldung.spring.data.couchbase2b.MultiBucketIntegationTest; +import org.baeldung.spring.data.couchbase2b.MultiBucketIntegrationTest; import org.joda.time.DateTime; import org.junit.BeforeClass; import org.junit.Test; @@ -21,7 +21,7 @@ import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; -public class PersonServiceImplIntegrationTest extends MultiBucketIntegationTest { +public class PersonServiceImplIntegrationTest extends MultiBucketIntegrationTest { static final String typeField = "_class"; static final String john = "John"; diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java index f37f11744d..e7c1eab92a 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplIntegrationTest.java @@ -11,7 +11,7 @@ import javax.validation.ConstraintViolationException; import org.baeldung.spring.data.couchbase.model.Student; import org.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig; -import org.baeldung.spring.data.couchbase2b.MultiBucketIntegationTest; +import org.baeldung.spring.data.couchbase2b.MultiBucketIntegrationTest; import org.joda.time.DateTime; import org.junit.BeforeClass; import org.junit.Test; @@ -23,7 +23,7 @@ import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; -public class StudentServiceImplIntegrationTest extends MultiBucketIntegationTest { +public class StudentServiceImplIntegrationTest extends MultiBucketIntegrationTest { static final String typeField = "_class"; static final String joe = "Joe"; diff --git a/spring-data-elasticsearch/pom.xml b/spring-data-elasticsearch/pom.xml index 804cf23a69..386bd54ee8 100644 --- a/spring-data-elasticsearch/pom.xml +++ b/spring-data-elasticsearch/pom.xml @@ -9,16 +9,16 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -53,7 +53,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -80,7 +80,6 @@ UTF-8 1.8 1.8 - 4.3.4.RELEASE 2.0.5.RELEASE 4.2.2 2.4.2 diff --git a/spring-data-keyvalue/README.md b/spring-data-keyvalue/README.md new file mode 100644 index 0000000000..f76cf4d5ac --- /dev/null +++ b/spring-data-keyvalue/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [A Guide to Spring Data Key Value](http://www.baeldung.com/spring-data-key-value) diff --git a/spring-data-keyvalue/pom.xml b/spring-data-keyvalue/pom.xml new file mode 100644 index 0000000000..e90f18948f --- /dev/null +++ b/spring-data-keyvalue/pom.xml @@ -0,0 +1,37 @@ + + 4.0.0 + com.baeldung + spring-data-keyvalue + 1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.0.1.RELEASE + + + + + 2.0.3.RELEASE + + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.data + spring-data-keyvalue + + + + org.springframework.boot + spring-boot-starter-test + + + + \ No newline at end of file diff --git a/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/Configurations.java b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/Configurations.java new file mode 100644 index 0000000000..c762c00333 --- /dev/null +++ b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/Configurations.java @@ -0,0 +1,28 @@ +package com.baeldung.spring.data.keyvalue; + +import java.util.concurrent.ConcurrentHashMap; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.keyvalue.core.KeyValueAdapter; +import org.springframework.data.keyvalue.core.KeyValueOperations; +import org.springframework.data.keyvalue.core.KeyValueTemplate; +import org.springframework.data.map.MapKeyValueAdapter; + +@Configuration +public class Configurations { + + //To be used only if @EnableMapRepositories is not used. + //Else @EnableMapRepositories gives us a template as well. + @Bean("keyValueTemplate") + public KeyValueOperations keyValueTemplate() { + return new KeyValueTemplate(keyValueAdapter()); + + } + + @Bean + public KeyValueAdapter keyValueAdapter() { + return new MapKeyValueAdapter(ConcurrentHashMap.class); + } + +} diff --git a/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/SpringDataKeyValueApplication.java b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/SpringDataKeyValueApplication.java new file mode 100644 index 0000000000..6a5b5264df --- /dev/null +++ b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/SpringDataKeyValueApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.data.keyvalue; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.map.repository.config.EnableMapRepositories; + +@SpringBootApplication +@EnableMapRepositories +public class SpringDataKeyValueApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringDataKeyValueApplication.class, args); + } + +} diff --git a/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/repositories/EmployeeRepository.java b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/repositories/EmployeeRepository.java new file mode 100644 index 0000000000..5b7545d5b6 --- /dev/null +++ b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/repositories/EmployeeRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.spring.data.keyvalue.repositories; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.spring.data.keyvalue.vo.Employee; + +@Repository("employeeRepository") +public interface EmployeeRepository extends CrudRepository { +} \ No newline at end of file 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 new file mode 100644 index 0000000000..83117b3baa --- /dev/null +++ b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/EmployeeService.java @@ -0,0 +1,21 @@ +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); + + Optional get(Integer id); + + Iterable fetchAll(); + + void update(Employee employee); + + void delete(Integer id); + + Iterable getSortedListOfEmployeesBySalary(); + +} 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 new file mode 100644 index 0000000000..3eb1d0f66a --- /dev/null +++ b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithKeyValueTemplate.java @@ -0,0 +1,56 @@ +package com.baeldung.spring.data.keyvalue.services.impl; + +import java.util.Optional; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.DependsOn; +import org.springframework.data.domain.Sort; +import org.springframework.data.keyvalue.core.KeyValueTemplate; +import org.springframework.data.keyvalue.core.query.KeyValueQuery; +import org.springframework.stereotype.Service; + +import com.baeldung.spring.data.keyvalue.services.EmployeeService; +import com.baeldung.spring.data.keyvalue.vo.Employee; + +@Service("employeeServicesWithKeyValueTemplate") +@DependsOn("keyValueTemplate") +public class EmployeeServicesWithKeyValueTemplate implements EmployeeService { + + @Autowired + @Qualifier("keyValueTemplate") + KeyValueTemplate keyValueTemplate; + + @Override + public void save(Employee employee) { + keyValueTemplate.insert(employee); + } + + @Override + public Optional get(Integer id) { + return keyValueTemplate.findById(id, Employee.class); + } + + @Override + public Iterable fetchAll() { + return keyValueTemplate.findAll(Employee.class); + } + + @Override + public void update(Employee employee) { + keyValueTemplate.update(employee); + } + + @Override + public void delete(Integer id) { + keyValueTemplate.delete(id, Employee.class); + } + + @Override + public Iterable getSortedListOfEmployeesBySalary() { + KeyValueQuery query = new KeyValueQuery(); + query.setSort(new Sort(Sort.Direction.DESC, "salary")); + return keyValueTemplate.find(query, Employee.class); + } + +} 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 new file mode 100644 index 0000000000..70e00dadc0 --- /dev/null +++ b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/services/impl/EmployeeServicesWithRepository.java @@ -0,0 +1,50 @@ +package com.baeldung.spring.data.keyvalue.services.impl; + +import java.util.Optional; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.baeldung.spring.data.keyvalue.repositories.EmployeeRepository; +import com.baeldung.spring.data.keyvalue.services.EmployeeService; +import com.baeldung.spring.data.keyvalue.vo.Employee; + +@Service("employeeServicesWithRepository") +public class EmployeeServicesWithRepository implements EmployeeService { + + @Autowired + EmployeeRepository employeeRepository; + + + @Override + public void save(Employee employee) { + employeeRepository.save(employee); + } + + @Override + public Iterable fetchAll() { + return employeeRepository.findAll(); + + } + + @Override + public Optional get(Integer id) { + return employeeRepository.findById(id); + } + + @Override + public void update(Employee employee) { + employeeRepository.save(employee); + + } + + @Override + public void delete(Integer id) { + employeeRepository.deleteById(id); + } + + public Iterable getSortedListOfEmployeesBySalary() { + throw new RuntimeException("Method not supported by CRUDRepository"); + } + +} 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 new file mode 100644 index 0000000000..1063c578f3 --- /dev/null +++ b/spring-data-keyvalue/src/main/java/com/baeldung/spring/data/keyvalue/vo/Employee.java @@ -0,0 +1,68 @@ +package com.baeldung.spring.data.keyvalue.vo; + +import java.io.Serializable; + +import org.springframework.data.annotation.Id; +import org.springframework.data.keyvalue.annotation.KeySpace; + +@KeySpace("employees") +public class Employee { + + @Id + private Integer id; + + private String name; + + private String department; + + private String salary; + + public Employee(Integer id, String name, String department, String salary) { + this.id = id; + this.name = name; + this.department = department; + this.salary = salary; + } + + 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; + } + + public String getDepartment() { + return department; + } + + public void setDepartment(String department) { + this.department = department; + } + + public String getSalary() { + return salary; + } + + public void setSalary(String salary) { + this.salary = salary; + } + + @Override + public String toString() { + return "Employee{" + + "id=" + id + + ", name='" + name + '\'' + + ", department='" + department + '\'' + + ", salary='" + salary + '\'' + + '}'; + } +} 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 new file mode 100644 index 0000000000..37b0a69a2d --- /dev/null +++ b/spring-data-keyvalue/src/test/java/com/baeldung/spring/data/keyvalue/services/test/EmployeeServicesWithKeyValueRepositoryIntegrationTest.java @@ -0,0 +1,88 @@ +package com.baeldung.spring.data.keyvalue.services.test; + +import static org.junit.Assert.assertEquals; + +import java.util.List; + +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.keyvalue.core.KeyValueTemplate; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.keyvalue.SpringDataKeyValueApplication; +import com.baeldung.spring.data.keyvalue.services.EmployeeService; +import com.baeldung.spring.data.keyvalue.vo.Employee; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = SpringDataKeyValueApplication.class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class EmployeeServicesWithKeyValueRepositoryIntegrationTest { + + @Autowired + @Qualifier("employeeServicesWithKeyValueTemplate") + EmployeeService employeeService; + + @Autowired + @Qualifier("keyValueTemplate") + KeyValueTemplate keyValueTemplate; + + static Employee employee1; + + static Employee employee2; + + @BeforeClass + public static void setUp() { + employee1 = new Employee(1, "Karan", "IT", "5000"); + employee2 = new Employee(2, "Jack", "HR", "2000"); + } + + @Test + public void test1_whenEmployeeSaved_thenEmployeeIsAddedToMap() { + employeeService.save(employee1); + assertEquals(keyValueTemplate.findById(1, Employee.class).get(), employee1); + } + + @Test + public void test2_whenEmployeeGet_thenEmployeeIsReturnedFromMap() { + Employee employeeFetched = employeeService.get(1).get(); + assertEquals(employeeFetched, employee1); + } + + @Test + public void test3_whenEmployeesFetched_thenEmployeesAreReturnedFromMap() { + List employees = (List)employeeService.fetchAll(); + assertEquals(employees.size(), 1); + assertEquals(employees.get(0), employee1); + } + + @Test + public void test4_whenEmployeeUpdated_thenEmployeeIsUpdatedToMap() { + employee1.setName("Pawan"); + employeeService.update(employee1); + assertEquals(keyValueTemplate.findById(1, Employee.class).get().getName(),"Pawan"); + } + + @Test + public void test5_whenSortedEmployeesFetched_thenEmployeesAreReturnedFromMapInOrder() { + employeeService.save(employee2); + List employees = (List)employeeService.getSortedListOfEmployeesBySalary(); + assertEquals(employees.size(), 2); + assertEquals(employees.get(0), employee1); + assertEquals(employees.get(1), employee2); + } + + @Test + public void test6_whenEmployeeDeleted_thenEmployeeIsRemovedMap() { + employeeService.delete(1); + assertEquals(keyValueTemplate.findById(1, Employee.class).isPresent(), false); + } + + + +} 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 new file mode 100644 index 0000000000..d0ed1506f8 --- /dev/null +++ b/spring-data-keyvalue/src/test/java/com/baeldung/spring/data/keyvalue/services/test/EmployeeServicesWithRepositoryIntegrationTest.java @@ -0,0 +1,73 @@ +package com.baeldung.spring.data.keyvalue.services.test; + +import static org.junit.Assert.assertEquals; + +import java.util.List; + +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.spring.data.keyvalue.SpringDataKeyValueApplication; +import com.baeldung.spring.data.keyvalue.repositories.EmployeeRepository; +import com.baeldung.spring.data.keyvalue.services.EmployeeService; +import com.baeldung.spring.data.keyvalue.vo.Employee; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = SpringDataKeyValueApplication.class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class EmployeeServicesWithRepositoryIntegrationTest { + + @Autowired + @Qualifier("employeeServicesWithRepository") + EmployeeService employeeService; + + @Autowired + EmployeeRepository employeeRepository; + + static Employee employee1; + + @BeforeClass + public static void setUp() { + employee1 = new Employee(1, "Karan", "IT", "5000"); + } + + @Test + public void test1_whenEmployeeSaved_thenEmployeeIsAddedToMap() { + employeeService.save(employee1); + assertEquals(employeeRepository.findById(1).get(), employee1); + } + + @Test + public void test2_whenEmployeeGet_thenEmployeeIsReturnedFromMap() { + Employee employeeFetched = employeeService.get(1).get(); + assertEquals(employeeFetched, employee1); + } + + @Test + public void test3_whenEmployeesFetched_thenEmployeesAreReturnedFromMap() { + List employees = (List)employeeService.fetchAll(); + assertEquals(employees.size(), 1); + assertEquals(employees.get(0), employee1); + } + + @Test + public void test4_whenEmployeeUpdated_thenEmployeeIsUpdatedToMap() { + employee1.setName("Pawan"); + employeeService.update(employee1); + assertEquals(employeeRepository.findById(1).get().getName(),"Pawan"); + } + + @Test + public void test5_whenEmployeeDeleted_thenEmployeeIsRemovedMap() { + employeeService.delete(1); + assertEquals(employeeRepository.findById(1).isPresent(), false); + } + +} diff --git a/spring-data-mongodb/README.md b/spring-data-mongodb/README.md index c2a1f703b5..4e12a2218a 100644 --- a/spring-data-mongodb/README.md +++ b/spring-data-mongodb/README.md @@ -10,3 +10,4 @@ - [GridFS in Spring Data MongoDB](http://www.baeldung.com/spring-data-mongodb-gridfs) - [Introduction to Spring Data MongoDB](http://www.baeldung.com/spring-data-mongodb-tutorial) - [Spring Data MongoDB: Projections and Aggregations](http://www.baeldung.com/spring-data-mongodb-projections-aggregations) +- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations) diff --git a/spring-data-mongodb/pom.xml b/spring-data-mongodb/pom.xml index 24847aaec6..c3d1f74b4b 100644 --- a/spring-data-mongodb/pom.xml +++ b/spring-data-mongodb/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -22,7 +22,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -33,7 +33,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -71,7 +71,6 @@ UTF-8 - 4.3.4.RELEASE 1.10.4.RELEASE 2.9.0 4.1.4 diff --git a/spring-data-mongodb/src/main/java/org/baeldung/annotation/CascadeSave.java b/spring-data-mongodb/src/main/java/com/baeldung/annotation/CascadeSave.java similarity index 88% rename from spring-data-mongodb/src/main/java/org/baeldung/annotation/CascadeSave.java rename to spring-data-mongodb/src/main/java/com/baeldung/annotation/CascadeSave.java index aae0214d09..3e43221aff 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/annotation/CascadeSave.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/annotation/CascadeSave.java @@ -1,4 +1,4 @@ -package org.baeldung.annotation; +package com.baeldung.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/config/MongoConfig.java b/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java similarity index 84% rename from spring-data-mongodb/src/main/java/org/baeldung/config/MongoConfig.java rename to spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java index 80b177f4c9..551a9142a6 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/config/MongoConfig.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java @@ -1,10 +1,10 @@ -package org.baeldung.config; +package com.baeldung.config; import com.mongodb.Mongo; import com.mongodb.MongoClient; -import org.baeldung.converter.UserWriterConverter; -import org.baeldung.event.CascadeSaveMongoEventListener; -import org.baeldung.event.UserCascadeSaveMongoEventListener; +import com.baeldung.converter.UserWriterConverter; +import com.baeldung.event.CascadeSaveMongoEventListener; +import com.baeldung.event.UserCascadeSaveMongoEventListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.converter.Converter; @@ -17,7 +17,7 @@ import java.util.ArrayList; import java.util.List; @Configuration -@EnableMongoRepositories(basePackages = "org.baeldung.repository") +@EnableMongoRepositories(basePackages = "com.baeldung.repository") public class MongoConfig extends AbstractMongoConfiguration { private final List> converters = new ArrayList>(); @@ -34,7 +34,7 @@ public class MongoConfig extends AbstractMongoConfiguration { @Override public String getMappingBasePackage() { - return "org.baeldung"; + return "com.baeldung"; } @Bean diff --git a/spring-data-mongodb/src/main/java/org/baeldung/config/SimpleMongoConfig.java b/spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java similarity index 86% rename from spring-data-mongodb/src/main/java/org/baeldung/config/SimpleMongoConfig.java rename to spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java index 9653796d8d..95f192811f 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/config/SimpleMongoConfig.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import com.mongodb.Mongo; import com.mongodb.MongoClient; @@ -8,7 +8,7 @@ import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; @Configuration -@EnableMongoRepositories(basePackages = "org.baeldung.repository") +@EnableMongoRepositories(basePackages = "com.baeldung.repository") public class SimpleMongoConfig { @Bean diff --git a/spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java b/spring-data-mongodb/src/main/java/com/baeldung/converter/UserWriterConverter.java similarity index 92% rename from spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java rename to spring-data-mongodb/src/main/java/com/baeldung/converter/UserWriterConverter.java index 4a6970489e..542ebb2c85 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/converter/UserWriterConverter.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/converter/UserWriterConverter.java @@ -1,8 +1,8 @@ -package org.baeldung.converter; +package com.baeldung.converter; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; -import org.baeldung.model.User; +import com.baeldung.model.User; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java b/spring-data-mongodb/src/main/java/com/baeldung/event/CascadeCallback.java similarity index 95% rename from spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java rename to spring-data-mongodb/src/main/java/com/baeldung/event/CascadeCallback.java index 94cad4566a..6ce5747793 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeCallback.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/event/CascadeCallback.java @@ -1,8 +1,8 @@ -package org.baeldung.event; +package com.baeldung.event; import java.lang.reflect.Field; -import org.baeldung.annotation.CascadeSave; +import com.baeldung.annotation.CascadeSave; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.util.ReflectionUtils; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java b/spring-data-mongodb/src/main/java/com/baeldung/event/CascadeSaveMongoEventListener.java similarity index 96% rename from spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java rename to spring-data-mongodb/src/main/java/com/baeldung/event/CascadeSaveMongoEventListener.java index acc377011d..499e727a90 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/CascadeSaveMongoEventListener.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/event/CascadeSaveMongoEventListener.java @@ -1,4 +1,4 @@ -package org.baeldung.event; +package com.baeldung.event; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/FieldCallback.java b/spring-data-mongodb/src/main/java/com/baeldung/event/FieldCallback.java similarity index 95% rename from spring-data-mongodb/src/main/java/org/baeldung/event/FieldCallback.java rename to spring-data-mongodb/src/main/java/com/baeldung/event/FieldCallback.java index c6bd90d4f3..5e478270c1 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/FieldCallback.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/event/FieldCallback.java @@ -1,4 +1,4 @@ -package org.baeldung.event; +package com.baeldung.event; import java.lang.reflect.Field; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java b/spring-data-mongodb/src/main/java/com/baeldung/event/UserCascadeSaveMongoEventListener.java similarity index 92% rename from spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java rename to spring-data-mongodb/src/main/java/com/baeldung/event/UserCascadeSaveMongoEventListener.java index ade20bcc1d..832e3563f9 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/event/UserCascadeSaveMongoEventListener.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/event/UserCascadeSaveMongoEventListener.java @@ -1,6 +1,6 @@ -package org.baeldung.event; +package com.baeldung.event; -import org.baeldung.model.User; +import com.baeldung.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/model/EmailAddress.java b/spring-data-mongodb/src/main/java/com/baeldung/model/EmailAddress.java similarity index 94% rename from spring-data-mongodb/src/main/java/org/baeldung/model/EmailAddress.java rename to spring-data-mongodb/src/main/java/com/baeldung/model/EmailAddress.java index 6db7d160d7..13fe340f69 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/model/EmailAddress.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/model/EmailAddress.java @@ -1,4 +1,4 @@ -package org.baeldung.model; +package com.baeldung.model; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/model/User.java b/spring-data-mongodb/src/main/java/com/baeldung/model/User.java similarity index 96% rename from spring-data-mongodb/src/main/java/org/baeldung/model/User.java rename to spring-data-mongodb/src/main/java/com/baeldung/model/User.java index 9b8c47a58f..1bbe49ee1d 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/model/User.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/model/User.java @@ -1,6 +1,6 @@ -package org.baeldung.model; +package com.baeldung.model; -import org.baeldung.annotation.CascadeSave; +import com.baeldung.annotation.CascadeSave; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.PersistenceConstructor; diff --git a/spring-data-mongodb/src/main/java/org/baeldung/repository/UserRepository.java b/spring-data-mongodb/src/main/java/com/baeldung/repository/UserRepository.java similarity index 94% rename from spring-data-mongodb/src/main/java/org/baeldung/repository/UserRepository.java rename to spring-data-mongodb/src/main/java/com/baeldung/repository/UserRepository.java index 8e442e8b7f..e9dc0f5c95 100644 --- a/spring-data-mongodb/src/main/java/org/baeldung/repository/UserRepository.java +++ b/spring-data-mongodb/src/main/java/com/baeldung/repository/UserRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.repository; +package com.baeldung.repository; -import org.baeldung.model.User; +import com.baeldung.model.User; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import org.springframework.data.querydsl.QueryDslPredicateExecutor; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/aggregation/ZipsAggregationLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java similarity index 97% rename from spring-data-mongodb/src/test/java/org/baeldung/aggregation/ZipsAggregationLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java index 5686465c19..a4bea45fcf 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/aggregation/ZipsAggregationLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java @@ -1,12 +1,12 @@ -package org.baeldung.aggregation; +package com.baeldung.aggregation; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.util.JSON; -import org.baeldung.aggregation.model.StatePopulation; -import org.baeldung.config.MongoConfig; +import com.baeldung.aggregation.model.StatePopulation; +import com.baeldung.config.MongoConfig; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/aggregation/model/StatePopulation.java b/spring-data-mongodb/src/test/java/com/baeldung/aggregation/model/StatePopulation.java similarity index 95% rename from spring-data-mongodb/src/test/java/org/baeldung/aggregation/model/StatePopulation.java rename to spring-data-mongodb/src/test/java/com/baeldung/aggregation/model/StatePopulation.java index 6a3cd0d426..be77783439 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/aggregation/model/StatePopulation.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/aggregation/model/StatePopulation.java @@ -1,4 +1,4 @@ -package org.baeldung.aggregation.model; +package com.baeldung.aggregation.model; import org.springframework.data.annotation.Id; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java similarity index 99% rename from spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java index 88205ba7fd..02485e8517 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/gridfs/GridFSLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.gridfs; +package com.baeldung.gridfs; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java similarity index 97% rename from spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java index 729b0f6dfa..7a61f9f98a 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/DocumentQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java @@ -1,8 +1,8 @@ -package org.baeldung.mongotemplate; +package com.baeldung.mongotemplate; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.EmailAddress; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.EmailAddress; +import com.baeldung.model.User; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java similarity index 94% rename from spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java index 2d2117afbb..309f14e995 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateProjectionLiveTest.java @@ -1,7 +1,7 @@ -package org.baeldung.mongotemplate; +package com.baeldung.mongotemplate; -import org.baeldung.config.SimpleMongoConfig; -import org.baeldung.model.User; +import com.baeldung.config.SimpleMongoConfig; +import com.baeldung.model.User; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java similarity index 97% rename from spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java index b7ce0cafae..ee1d4f4760 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java @@ -1,8 +1,8 @@ -package org.baeldung.mongotemplate; +package com.baeldung.mongotemplate; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.EmailAddress; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.EmailAddress; +import com.baeldung.model.User; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/BaseQueryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/BaseQueryLiveTest.java similarity index 83% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/BaseQueryLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/repository/BaseQueryLiveTest.java index afd7259c6c..e4849181e5 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/BaseQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/BaseQueryLiveTest.java @@ -1,7 +1,7 @@ -package org.baeldung.repository; +package com.baeldung.repository; -import org.baeldung.model.User; -import org.baeldung.repository.UserRepository; +import com.baeldung.model.User; +import com.baeldung.repository.UserRepository; import org.junit.After; import org.junit.Before; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/DSLQueryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/DSLQueryLiveTest.java similarity index 95% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/DSLQueryLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/repository/DSLQueryLiveTest.java index 5924dea9fe..f87ca5cbb5 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/DSLQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/DSLQueryLiveTest.java @@ -1,13 +1,13 @@ -package org.baeldung.repository; +package com.baeldung.repository; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.List; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.QUser; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.QUser; +import com.baeldung.model.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/JSONQueryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/JSONQueryLiveTest.java similarity index 96% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/JSONQueryLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/repository/JSONQueryLiveTest.java index 9464a4eb52..4e99c0b140 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/JSONQueryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/JSONQueryLiveTest.java @@ -1,12 +1,12 @@ -package org.baeldung.repository; +package com.baeldung.repository; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.List; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/QueryMethodsLiveTest.java similarity index 96% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/repository/QueryMethodsLiveTest.java index 5705c119b8..47e67a6b4c 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/QueryMethodsLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/QueryMethodsLiveTest.java @@ -1,12 +1,12 @@ -package org.baeldung.repository; +package com.baeldung.repository; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.List; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java similarity index 97% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java index 1543b847ba..da4e91baec 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java @@ -1,12 +1,12 @@ -package org.baeldung.repository; +package com.baeldung.repository; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.List; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.User; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryProjectionLiveTest.java b/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryProjectionLiveTest.java similarity index 93% rename from spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryProjectionLiveTest.java rename to spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryProjectionLiveTest.java index 5436896f08..80f4275794 100644 --- a/spring-data-mongodb/src/test/java/org/baeldung/repository/UserRepositoryProjectionLiveTest.java +++ b/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryProjectionLiveTest.java @@ -1,9 +1,9 @@ -package org.baeldung.repository; +package com.baeldung.repository; import static org.junit.Assert.*; -import org.baeldung.config.MongoConfig; -import org.baeldung.model.User; +import com.baeldung.config.MongoConfig; +import com.baeldung.model.User; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/spring-data-rest-querydsl/README.md b/spring-data-rest-querydsl/README.md new file mode 100644 index 0000000000..03b5fee06a --- /dev/null +++ b/spring-data-rest-querydsl/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [REST Query Language Over Multiple Tables with Querydsl Web Support](http://www.baeldung.com/rest-querydsl-multiple-tables) diff --git a/spring-data-rest-querydsl/pom.xml b/spring-data-rest-querydsl/pom.xml new file mode 100644 index 0000000000..e4832e1552 --- /dev/null +++ b/spring-data-rest-querydsl/pom.xml @@ -0,0 +1,101 @@ + + + 4.0.0 + + com.baeldung + spring-data-rest-querydsl + 1.0 + + spring-data-rest-querydsl + + + org.springframework.boot + spring-boot-starter-parent + 1.5.9.RELEASE + + + + + org.springframework.boot + spring-boot-starter-data-rest + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + + + com.querydsl + querydsl-apt + + + com.querydsl + querydsl-jpa + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.boot + spring-boot-maven-plugin + + ${start-class} + ZIP + + + + + repackage + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + -verbose + -parameters + + + + + com.mysema.maven + apt-maven-plugin + 1.1.3 + + + generate-sources + + process + + + ${project.build.directory}/generated-sources + com.querydsl.apt.jpa.JPAAnnotationProcessor + + + + + + +<<<<<<< HEAD + +======= + +>>>>>>> 19a1633c35d6d49f9c51b8ecc3dbe127c91d75c3 diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/Application.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..28d084a4dc --- /dev/null +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/Application.java @@ -0,0 +1,44 @@ +package com.baeldung; + +import com.baeldung.controller.repository.AddressRepository; +import com.baeldung.controller.repository.UserRepository; +import com.baeldung.entity.Address; +import com.baeldung.entity.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +import javax.annotation.PostConstruct; + +@SpringBootApplication +@EntityScan("com.baeldung.entity") +@EnableJpaRepositories("com.baeldung.controller.repository") +@EnableAutoConfiguration +public class Application { + + @Autowired + private UserRepository personRepository; + @Autowired + private AddressRepository addressRepository; + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @PostConstruct + private void initializeData() { + // Create John + final User john = new User("John"); + personRepository.save(john); + final Address addressOne = new Address("Fake Street 1", "Spain", john); + addressRepository.save(addressOne); + // Create Lisa + final User lisa = new User("Lisa"); + personRepository.save(lisa); + final Address addressTwo = new Address("Real Street 1", "Germany", lisa); + addressRepository.save(addressTwo); + } +} diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/QueryController.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/QueryController.java new file mode 100644 index 0000000000..e29932657f --- /dev/null +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/QueryController.java @@ -0,0 +1,34 @@ +package com.baeldung.controller; + +import com.baeldung.controller.repository.AddressRepository; +import com.baeldung.controller.repository.UserRepository; +import com.baeldung.entity.Address; +import com.baeldung.entity.User; +import com.querydsl.core.BooleanBuilder; +import com.querydsl.core.types.Predicate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.querydsl.binding.QuerydslPredicate; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class QueryController { + + @Autowired + private UserRepository personRepository; + @Autowired + private AddressRepository addressRepository; + + @GetMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE) + public Iterable queryOverUser(@QuerydslPredicate(root = User.class) Predicate predicate) { + final BooleanBuilder builder = new BooleanBuilder(); + return personRepository.findAll(builder.and(predicate)); + } + + @GetMapping(value = "/addresses", produces = MediaType.APPLICATION_JSON_VALUE) + public Iterable
queryOverAddress(@QuerydslPredicate(root = Address.class) Predicate predicate) { + final BooleanBuilder builder = new BooleanBuilder(); + return addressRepository.findAll(builder.and(predicate)); + } +} diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/AddressRepository.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/AddressRepository.java new file mode 100644 index 0000000000..2e88820c98 --- /dev/null +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/AddressRepository.java @@ -0,0 +1,19 @@ +package com.baeldung.controller.repository; + +import com.baeldung.entity.Address; +import com.baeldung.entity.QAddress; +import com.querydsl.core.types.dsl.StringExpression; +import com.querydsl.core.types.dsl.StringPath; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer; +import org.springframework.data.querydsl.binding.QuerydslBindings; +import org.springframework.data.querydsl.binding.SingleValueBinding; + +public interface AddressRepository + extends JpaRepository, QueryDslPredicateExecutor
, QuerydslBinderCustomizer { + @Override + default void customize(final QuerydslBindings bindings, final QAddress root) { + bindings.bind(String.class).first((SingleValueBinding) StringExpression::eq); + } +} diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/UserRepository.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/UserRepository.java new file mode 100644 index 0000000000..98ff2ac5e3 --- /dev/null +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/controller/repository/UserRepository.java @@ -0,0 +1,19 @@ +package com.baeldung.controller.repository; + +import com.baeldung.entity.QUser; +import com.baeldung.entity.User; +import com.querydsl.core.types.dsl.StringExpression; +import com.querydsl.core.types.dsl.StringPath; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.querydsl.QueryDslPredicateExecutor; +import org.springframework.data.querydsl.binding.QuerydslBinderCustomizer; +import org.springframework.data.querydsl.binding.QuerydslBindings; +import org.springframework.data.querydsl.binding.SingleValueBinding; + +public interface UserRepository + extends JpaRepository, QueryDslPredicateExecutor, QuerydslBinderCustomizer { + @Override + default void customize(final QuerydslBindings bindings, final QUser root) { + bindings.bind(String.class).first((SingleValueBinding) StringExpression::eq); + } +} diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/Address.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/Address.java new file mode 100644 index 0000000000..b01194adb7 --- /dev/null +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/Address.java @@ -0,0 +1,57 @@ +package com.baeldung.entity; + + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import javax.persistence.*; + +@Entity +@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) +public class Address { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", unique = true, nullable = false) + private Long id; + @Column + private String address; + @Column + private String country; + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id") + private User user; + + public Address() { + } + + public Address(String address, String country, User user) { + this.id = id; + this.address = address; + this.country = country; + this.user = user; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } +} diff --git a/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/User.java b/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/User.java new file mode 100644 index 0000000000..cfd484bb7a --- /dev/null +++ b/spring-data-rest-querydsl/src/main/java/com/baeldung/entity/User.java @@ -0,0 +1,51 @@ +package com.baeldung.entity; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import javax.persistence.*; + + +@Entity +@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", unique = true, nullable = false) + private Long id; + @Column + private String name; + @OneToOne(fetch = FetchType.LAZY, mappedBy = "user") + private Address address; + + public User() { + } + + public User(String name) { + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } +} diff --git a/spring-data-rest-querydsl/src/main/resources/application.yml b/spring-data-rest-querydsl/src/main/resources/application.yml new file mode 100644 index 0000000000..f25c6ea0e3 --- /dev/null +++ b/spring-data-rest-querydsl/src/main/resources/application.yml @@ -0,0 +1,11 @@ +spring: + datasource: + driver-class-name: com.mysql.jdbc.Driver + hikari: + pool-name: hikari-pool + url: jdbc:mysql://localhost:3306/baeldung?verifyServerCertificate=false&useSSL=false&requireSSL=false + username: root + + jpa: + hibernate: + ddl-auto: create diff --git a/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java new file mode 100644 index 0000000000..ef86c2f36d --- /dev/null +++ b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/IntegrationTest.java @@ -0,0 +1,52 @@ +package com.baeldung.springdatarestquerydsl; + +import com.baeldung.Application; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import java.nio.charset.Charset; + +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = Application.class) @WebAppConfiguration +public class IntegrationTest { + + final MediaType contentType = + new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); + + @Autowired private WebApplicationContext webApplicationContext; + + private MockMvc mockMvc; + + @Before public void setupMockMvc() { + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); + } + + @Test public void givenRequestHasBeenMade_whenQueryOverNameAttribute_thenGetJohn() throws Exception { + // Get John + mockMvc.perform(get("/personQuery?name=John")).andExpect(status().isOk()).andExpect(content().contentType(contentType)) + .andExpect(jsonPath("$", hasSize(1))).andExpect(jsonPath("$[0].name", is("John"))) + .andExpect(jsonPath("$[0].address.address", is("Fake Street 1"))) + .andExpect(jsonPath("$[0].address.country", is("Fake Country"))); + } + + @Test public void givenRequestHasBeenMade_whenQueryOverNameAttribute_thenGetLisa() throws Exception { + // Get Lisa + mockMvc.perform(get("/personQuery?name=Lisa")).andExpect(status().isOk()).andExpect(content().contentType(contentType)) + .andExpect(jsonPath("$", hasSize(1))).andExpect(jsonPath("$[0].name", is("Lisa"))) + .andExpect(jsonPath("$[0].address.address", is("Real Street 1"))) + .andExpect(jsonPath("$[0].address.country", is("Real Country"))); + } +} diff --git a/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/QuerydslIntegrationTest.java b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/QuerydslIntegrationTest.java new file mode 100644 index 0000000000..11e5ffca05 --- /dev/null +++ b/spring-data-rest-querydsl/src/test/java/com/baeldung/springdatarestquerydsl/QuerydslIntegrationTest.java @@ -0,0 +1,65 @@ +package com.baeldung.springdatarestquerydsl; + +import com.baeldung.Application; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import java.nio.charset.Charset; + +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringBootTest(classes = Application.class) +@WebAppConfiguration +public class QuerydslIntegrationTest { + + final MediaType contentType = + new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); + + @Autowired + private WebApplicationContext webApplicationContext; + + private MockMvc mockMvc; + + @Before + public void setupMockMvc() { + mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); + } + + @Test + public void givenRequest_whenQueryUserFilteringByCountrySpain_thenGetJohn() throws Exception { + mockMvc.perform(get("/users?address.country=Spain")).andExpect(status().isOk()).andExpect(content() + .contentType + (contentType)) + .andExpect(jsonPath("$", hasSize(1))) + .andExpect(jsonPath("$[0].name", is("John"))) + .andExpect(jsonPath("$[0].address.address", is("Fake Street 1"))) + .andExpect(jsonPath("$[0].address.country", is("Spain"))); + } + + @Test + public void givenRequest_whenQueryUserWithoutFilter_thenGetJohnAndLisa() throws Exception { + mockMvc.perform(get("/users")).andExpect(status().isOk()).andExpect(content() + .contentType + (contentType)) + .andExpect(jsonPath("$", hasSize(2))) + .andExpect(jsonPath("$[0].name", is("John"))) + .andExpect(jsonPath("$[0].address.address", is("Fake Street 1"))) + .andExpect(jsonPath("$[0].address.country", is("Spain"))) + .andExpect(jsonPath("$[1].name", is("Lisa"))) + .andExpect(jsonPath("$[1].address.address", is("Real Street 1"))) + .andExpect(jsonPath("$[1].address.country", is("Germany"))); + } +} diff --git a/spring-data-rest/README.md b/spring-data-rest/README.md index fa4a264abb..09f8391406 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,10 @@ 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) +- [Spring Data REST Events with @RepositoryEventHandler](http://www.baeldung.com/spring-data-rest-events) diff --git a/spring-data-rest/pom.xml b/spring-data-rest/pom.xml index bad7a38281..0e525474e3 100644 --- a/spring-data-rest/pom.xml +++ b/spring-data-rest/pom.xml @@ -10,10 +10,10 @@ Intro to Spring Data REST - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-data-rest/src/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/AuthorEventHandlerUnitTest.java b/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerUnitTest.java new file mode 100644 index 0000000000..6db536c40c --- /dev/null +++ b/spring-data-rest/src/test/java/com/baeldung/events/AuthorEventHandlerUnitTest.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 AuthorEventHandlerUnitTest { + + @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/BookEventHandlerUnitTest.java b/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerUnitTest.java new file mode 100644 index 0000000000..28f0b91e1c --- /dev/null +++ b/spring-data-rest/src/test/java/com/baeldung/events/BookEventHandlerUnitTest.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 BookEventHandlerUnitTest { + @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-data-spring-security/pom.xml b/spring-data-spring-security/pom.xml index afdf3c332c..467c38284d 100644 --- a/spring-data-spring-security/pom.xml +++ b/spring-data-spring-security/pom.xml @@ -11,10 +11,10 @@ Spring Data with Spring Security - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-dispatcher-servlet/pom.xml b/spring-dispatcher-servlet/pom.xml index 9fa02f157d..9dfd3c0f39 100644 --- a/spring-dispatcher-servlet/pom.xml +++ b/spring-dispatcher-servlet/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -90,7 +90,6 @@ - 4.3.7.RELEASE 3.0-r1655215 3.0.0 diff --git a/spring-ejb/README.md b/spring-ejb/README.md index 8fa8833f3a..d09b27db27 100644 --- a/spring-ejb/README.md +++ b/spring-ejb/README.md @@ -1,3 +1,4 @@ ### Relevant Articles - [Integration Guide for Spring and EJB](http://www.baeldung.com/spring-ejb) +- [Singleton Session Bean in Java EE](http://www.baeldung.com/java-ee-singleton-session-bean) diff --git a/spring-ejb/singleton-ejb-bean/pom.xml b/spring-ejb/ejb-beans/pom.xml similarity index 100% rename from spring-ejb/singleton-ejb-bean/pom.xml rename to spring-ejb/ejb-beans/pom.xml diff --git a/spring-ejb/singleton-ejb-bean/src/main/java/com/baeldung/singletonbean/CountryState.java b/spring-ejb/ejb-beans/src/main/java/com/baeldung/singletonbean/CountryState.java similarity index 72% rename from spring-ejb/singleton-ejb-bean/src/main/java/com/baeldung/singletonbean/CountryState.java rename to spring-ejb/ejb-beans/src/main/java/com/baeldung/singletonbean/CountryState.java index a9a426ae32..1f96fdba7c 100644 --- a/spring-ejb/singleton-ejb-bean/src/main/java/com/baeldung/singletonbean/CountryState.java +++ b/spring-ejb/ejb-beans/src/main/java/com/baeldung/singletonbean/CountryState.java @@ -8,5 +8,7 @@ import javax.ejb.Local; public interface CountryState { public List getStates(String country); + + public void setStates(String country, List states); } diff --git a/spring-ejb/singleton-ejb-bean/src/main/java/com/baeldung/singletonbean/CountryStateBeanManagedBean.java b/spring-ejb/ejb-beans/src/main/java/com/baeldung/singletonbean/CountryStateBeanManagedBean.java similarity index 85% rename from spring-ejb/singleton-ejb-bean/src/main/java/com/baeldung/singletonbean/CountryStateBeanManagedBean.java rename to spring-ejb/ejb-beans/src/main/java/com/baeldung/singletonbean/CountryStateBeanManagedBean.java index ee2c1f005a..3ef7a62753 100644 --- a/spring-ejb/singleton-ejb-bean/src/main/java/com/baeldung/singletonbean/CountryStateBeanManagedBean.java +++ b/spring-ejb/ejb-beans/src/main/java/com/baeldung/singletonbean/CountryStateBeanManagedBean.java @@ -19,7 +19,7 @@ public class CountryStateBeanManagedBean implements CountryState { private final Map> countryStatesMap = new HashMap>(); @PostConstruct - public synchronized void initialize() { + public void initialize() { List states = new ArrayList(); states.add("Texas"); @@ -34,4 +34,8 @@ public class CountryStateBeanManagedBean implements CountryState { public List getStates(String country) { return countryStatesMap.get(country); } + + public synchronized void setStates(String country, List states) { + countryStatesMap.put(country, states); + } } diff --git a/spring-ejb/singleton-ejb-bean/src/main/java/com/baeldung/singletonbean/CountryStateContainerManagedBean.java b/spring-ejb/ejb-beans/src/main/java/com/baeldung/singletonbean/CountryStateContainerManagedBean.java similarity index 88% rename from spring-ejb/singleton-ejb-bean/src/main/java/com/baeldung/singletonbean/CountryStateContainerManagedBean.java rename to spring-ejb/ejb-beans/src/main/java/com/baeldung/singletonbean/CountryStateContainerManagedBean.java index ee16285824..0a970f4c5c 100644 --- a/spring-ejb/singleton-ejb-bean/src/main/java/com/baeldung/singletonbean/CountryStateContainerManagedBean.java +++ b/spring-ejb/ejb-beans/src/main/java/com/baeldung/singletonbean/CountryStateContainerManagedBean.java @@ -38,4 +38,9 @@ public class CountryStateContainerManagedBean implements CountryState { public List getStates(String country) { return countryStatesMap.get(country); } + + @Lock(LockType.WRITE) + public void setStates(String country, List states) { + countryStatesMap.put(country, states); + } } diff --git a/spring-ejb/singleton-ejb-bean/src/test/java/com/baeldung/singletonbean/CountryStateCacheBeanTest.java b/spring-ejb/ejb-beans/src/test/java/com/baeldung/singletonbean/CountryStateCacheBeanUnitTest.java similarity index 50% rename from spring-ejb/singleton-ejb-bean/src/test/java/com/baeldung/singletonbean/CountryStateCacheBeanTest.java rename to spring-ejb/ejb-beans/src/test/java/com/baeldung/singletonbean/CountryStateCacheBeanUnitTest.java index 62412084bd..4cec01a4f7 100644 --- a/spring-ejb/singleton-ejb-bean/src/test/java/com/baeldung/singletonbean/CountryStateCacheBeanTest.java +++ b/spring-ejb/ejb-beans/src/test/java/com/baeldung/singletonbean/CountryStateCacheBeanUnitTest.java @@ -3,6 +3,8 @@ package com.baeldung.singletonbean; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertNotNull; +import java.util.Arrays; +import java.util.Collections; import java.util.List; import javax.ejb.embeddable.EJBContainer; @@ -12,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; @@ -24,29 +26,55 @@ public class CountryStateCacheBeanTest { ejbContainer = EJBContainer.createEJBContainer(); context = ejbContainer.getContext(); } - + @Test public void whenCallGetStatesFromContainerManagedBean_ReturnsStatesForCountry() throws Exception { String[] expectedStates = { "Texas", "Alabama", "Alaska", "Arizona", "Arkansas" }; - CountryState countryStateBean = (CountryState) context.lookup("java:global/singleton-ejb-bean/CountryStateContainerManagedBean"); + CountryState countryStateBean = (CountryState) context.lookup("java:global/ejb-beans/CountryStateContainerManagedBean"); List actualStates = countryStateBean.getStates("UnitedStates"); assertNotNull(actualStates); assertArrayEquals(expectedStates, actualStates.toArray()); } - + @Test public void whenCallGetStatesFromBeanManagedBean_ReturnsStatesForCountry() throws Exception { String[] expectedStates = { "Texas", "Alabama", "Alaska", "Arizona", "Arkansas" }; - CountryState countryStateBean = (CountryState) context.lookup("java:global/singleton-ejb-bean/CountryStateBeanManagedBean"); + CountryState countryStateBean = (CountryState) context.lookup("java:global/ejb-beans/CountryStateBeanManagedBean"); List actualStates = countryStateBean.getStates("UnitedStates"); assertNotNull(actualStates); assertArrayEquals(expectedStates, actualStates.toArray()); } - + + @Test + public void whenCallSetStatesFromContainerManagedBean_SetsStatesForCountry() throws Exception { + + String[] expectedStates = { "California", "Florida", "Hawaii", "Pennsylvania", "Michigan" }; + + CountryState countryStateBean = (CountryState) context.lookup("java:global/ejb-beans/CountryStateContainerManagedBean"); + countryStateBean.setStates("UnitedStates", Arrays.asList(expectedStates)); + + List actualStates = countryStateBean.getStates("UnitedStates"); + assertNotNull(actualStates); + assertArrayEquals(expectedStates, actualStates.toArray()); + } + + @Test + public void whenCallSetStatesFromBeanManagedBean_SetsStatesForCountry() throws Exception { + + String[] expectedStates = { "California", "Florida", "Hawaii", "Pennsylvania", "Michigan" }; + + CountryState countryStateBean = (CountryState) context.lookup("java:global/ejb-beans/CountryStateBeanManagedBean"); + countryStateBean.setStates("UnitedStates", Arrays.asList(expectedStates)); + + List actualStates = countryStateBean.getStates("UnitedStates"); + assertNotNull(actualStates); + assertArrayEquals(expectedStates, actualStates.toArray()); + } + @After public void close() { if (ejbContainer != null) diff --git a/spring-ejb/ejb-remote-for-spring/pom.xml b/spring-ejb/ejb-remote-for-spring/pom.xml index 9978196725..92f9dbf16c 100755 --- a/spring-ejb/ejb-remote-for-spring/pom.xml +++ b/spring-ejb/ejb-remote-for-spring/pom.xml @@ -45,7 +45,7 @@ wildfly10x - http://download.jboss.org/wildfly/10.1.0.Final/wildfly-10.1.0.Final.zip + http://download.jboss.org/wildfly/12.0.0.Final/wildfly-12.0.0.Final.zip @@ -66,7 +66,7 @@ - 7.0 + 8.0 1.6.1 diff --git a/spring-ejb/pom.xml b/spring-ejb/pom.xml index bd0183d71d..357c2cc84c 100755 --- a/spring-ejb/pom.xml +++ b/spring-ejb/pom.xml @@ -43,13 +43,13 @@ javax javaee-api - 7.0 + 8.0 provided org.wildfly wildfly-ejb-client-bom - 10.1.0.Final + 12.0.0.Final pom import @@ -73,6 +73,6 @@ ejb-remote-for-spring spring-ejb-client - singleton-ejb-bean + ejb-beans diff --git a/spring-ejb/spring-ejb-client/pom.xml b/spring-ejb/spring-ejb-client/pom.xml index f7b42212be..83c7028dab 100644 --- a/spring-ejb/spring-ejb-client/pom.xml +++ b/spring-ejb/spring-ejb-client/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-5 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-2 @@ -31,7 +31,7 @@ org.wildfly wildfly-ejb-client-bom - 10.1.0.Final + 12.0.0.Final pom @@ -47,6 +47,12 @@ spring-boot-starter-test test + + + io.undertow + undertow-servlet + + @@ -58,43 +64,4 @@ - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - - - spring-snapshots - Spring Snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - Spring Milestones - https://repo.spring.io/milestone - - false - - - - - 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-integration/src/test/java/com/baeldung/si/TestSpringIntegrationSecurityExecutor.java b/spring-integration/src/test/java/com/baeldung/si/TestSpringIntegrationSecurityExecutorIntegrationTest.java similarity index 95% rename from spring-integration/src/test/java/com/baeldung/si/TestSpringIntegrationSecurityExecutor.java rename to spring-integration/src/test/java/com/baeldung/si/TestSpringIntegrationSecurityExecutorIntegrationTest.java index b06136a7ca..0246bda0e1 100644 --- a/spring-integration/src/test/java/com/baeldung/si/TestSpringIntegrationSecurityExecutor.java +++ b/spring-integration/src/test/java/com/baeldung/si/TestSpringIntegrationSecurityExecutorIntegrationTest.java @@ -23,7 +23,7 @@ import com.baeldung.si.security.SecurityPubSubChannel; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { SecurityPubSubChannel.class, MessageConsumer.class, SecurityConfig.class }) -public class TestSpringIntegrationSecurityExecutor { +public class TestSpringIntegrationSecurityExecutorIntegrationTest { @Autowired SubscribableChannel startPSChannel; diff --git a/spring-integration/src/test/java/com/baeldung/si/TestSpringIntegrationSecurity.java b/spring-integration/src/test/java/com/baeldung/si/TestSpringIntegrationSecurityIntegrationTest.java similarity index 95% rename from spring-integration/src/test/java/com/baeldung/si/TestSpringIntegrationSecurity.java rename to spring-integration/src/test/java/com/baeldung/si/TestSpringIntegrationSecurityIntegrationTest.java index 9ae82af2dc..eccab0bee6 100644 --- a/spring-integration/src/test/java/com/baeldung/si/TestSpringIntegrationSecurity.java +++ b/spring-integration/src/test/java/com/baeldung/si/TestSpringIntegrationSecurityIntegrationTest.java @@ -22,7 +22,7 @@ import com.baeldung.si.security.SecurityConfig; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { SecurityConfig.class, SecuredDirectChannel.class, MessageConsumer.class }) -public class TestSpringIntegrationSecurity { +public class TestSpringIntegrationSecurityIntegrationTest { @Rule public ExpectedException expectedException = ExpectedException.none(); diff --git a/spring-jenkins-pipeline/pom.xml b/spring-jenkins-pipeline/pom.xml index c43952e277..9c3b6f14ed 100644 --- a/spring-jenkins-pipeline/pom.xml +++ b/spring-jenkins-pipeline/pom.xml @@ -9,10 +9,10 @@ Intro to Jenkins 2 and the power of pipelines - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -55,6 +55,7 @@ **/*IntegrationTest.java + **/*IntTest.java diff --git a/spring-jersey/pom.xml b/spring-jersey/pom.xml index 4a37f4b2ab..5fb4adcc61 100644 --- a/spring-jersey/pom.xml +++ b/spring-jersey/pom.xml @@ -127,6 +127,7 @@ **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index 3891be1ec3..db0d7e6df9 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -8,10 +8,10 @@ Intro to Kafka with Spring - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index 27075de747..6addb614f5 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -7,10 +7,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -33,7 +33,7 @@ io.katharsis - katharsis-servlet + katharsis-spring ${katharsis.version} diff --git a/spring-katharsis/src/main/java/org/baeldung/Application.java b/spring-katharsis/src/main/java/org/baeldung/Application.java index ee072305d8..5ce4ac7e08 100644 --- a/spring-katharsis/src/main/java/org/baeldung/Application.java +++ b/spring-katharsis/src/main/java/org/baeldung/Application.java @@ -1,10 +1,14 @@ package org.baeldung; +import io.katharsis.spring.boot.v3.KatharsisConfigV3; + import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.context.annotation.Import; @SpringBootApplication +@Import(KatharsisConfigV3.class) public class Application extends SpringBootServletInitializer { public static void main(String[] args) { diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/JsonApiFilter.java b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/JsonApiFilter.java deleted file mode 100644 index 3d0d441357..0000000000 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/JsonApiFilter.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.baeldung.persistence.katharsis; - -import io.katharsis.invoker.internal.legacy.KatharsisInvokerBuilder; -import io.katharsis.legacy.locator.JsonServiceLocator; -import io.katharsis.servlet.legacy.AbstractKatharsisFilter; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.stereotype.Component; - -@Component -public class JsonApiFilter extends AbstractKatharsisFilter implements BeanFactoryAware { - - private static final String DEFAULT_RESOURCE_SEARCH_PACKAGE = "org.baeldung.persistence"; - - private static final String RESOURCE_DEFAULT_DOMAIN = "http://localhost:8080"; - - private BeanFactory beanFactory; - - @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.beanFactory = beanFactory; - } - - @Override - protected KatharsisInvokerBuilder createKatharsisInvokerBuilder() { - final KatharsisInvokerBuilder builder = new KatharsisInvokerBuilder(); - - builder.resourceSearchPackage(DEFAULT_RESOURCE_SEARCH_PACKAGE).resourceDefaultDomain(RESOURCE_DEFAULT_DOMAIN).jsonServiceLocator(new JsonServiceLocator() { - @Override - public T getInstance(Class clazz) { - return beanFactory.getBean(clazz); - } - }); - - return builder; - } - -} diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java index 52ca40e26e..1998c414bb 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/RoleResourceRepository.java @@ -1,7 +1,9 @@ package org.baeldung.persistence.katharsis; -import io.katharsis.legacy.queryParams.QueryParams; -import io.katharsis.legacy.repository.ResourceRepository; + +import io.katharsis.queryspec.QuerySpec; +import io.katharsis.repository.ResourceRepositoryV2; +import io.katharsis.resource.list.ResourceList; import org.baeldung.persistence.dao.RoleRepository; import org.baeldung.persistence.model.Role; @@ -9,23 +11,23 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component -public class RoleResourceRepository implements ResourceRepository { +public class RoleResourceRepository implements ResourceRepositoryV2 { @Autowired private RoleRepository roleRepository; @Override - public Role findOne(Long id, QueryParams params) { + public Role findOne(Long id, QuerySpec querySpec) { return roleRepository.findOne(id); } @Override - public Iterable findAll(QueryParams params) { - return roleRepository.findAll(); + public ResourceList findAll(QuerySpec querySpec) { + return querySpec.apply(roleRepository.findAll()); } @Override - public Iterable findAll(Iterable ids, QueryParams params) { - return roleRepository.findAll(ids); + public ResourceList findAll(Iterable ids, QuerySpec querySpec) { + return querySpec.apply(roleRepository.findAll(ids)); } @Override @@ -38,4 +40,14 @@ public class RoleResourceRepository implements ResourceRepository { roleRepository.delete(id); } + @Override + public Class getResourceClass() { + return Role.class; + } + + @Override + public S create(S entity) { + return save(entity); + } + } diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java index a36c3c3c0a..9b3de31601 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserResourceRepository.java @@ -1,7 +1,8 @@ package org.baeldung.persistence.katharsis; -import io.katharsis.legacy.queryParams.QueryParams; -import io.katharsis.legacy.repository.ResourceRepository; +import io.katharsis.queryspec.QuerySpec; +import io.katharsis.repository.ResourceRepositoryV2; +import io.katharsis.resource.list.ResourceList; import org.baeldung.persistence.dao.UserRepository; import org.baeldung.persistence.model.User; @@ -9,24 +10,24 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component -public class UserResourceRepository implements ResourceRepository { +public class UserResourceRepository implements ResourceRepositoryV2 { @Autowired private UserRepository userRepository; @Override - public User findOne(Long id, QueryParams params) { + public User findOne(Long id, QuerySpec querySpec) { return userRepository.findOne(id); } @Override - public Iterable findAll(QueryParams params) { - return userRepository.findAll(); + public ResourceList findAll(QuerySpec querySpec) { + return querySpec.apply(userRepository.findAll()); } @Override - public Iterable findAll(Iterable ids, QueryParams params) { - return userRepository.findAll(ids); + public ResourceList findAll(Iterable ids, QuerySpec querySpec) { + return querySpec.apply(userRepository.findAll(ids)); } @Override @@ -39,4 +40,14 @@ public class UserResourceRepository implements ResourceRepository { userRepository.delete(id); } + @Override + public Class getResourceClass() { + return User.class; + } + + @Override + public S create(S entity) { + return save(entity); + } + } diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java index 19007a285f..dbeb769fac 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java @@ -1,7 +1,8 @@ package org.baeldung.persistence.katharsis; -import io.katharsis.legacy.queryParams.QueryParams; -import io.katharsis.legacy.repository.RelationshipRepository; +import io.katharsis.queryspec.QuerySpec; +import io.katharsis.repository.RelationshipRepositoryV2; +import io.katharsis.resource.list.ResourceList; import java.util.HashSet; import java.util.Set; @@ -14,7 +15,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component -public class UserToRoleRelationshipRepository implements RelationshipRepository { +public class UserToRoleRelationshipRepository implements RelationshipRepositoryV2 { @Autowired private UserRepository userRepository; @@ -52,14 +53,25 @@ public class UserToRoleRelationshipRepository implements RelationshipRepository< } @Override - public Role findOneTarget(Long sourceId, String fieldName, QueryParams QueryParams) { + public Role findOneTarget(Long sourceId, String fieldName, QuerySpec querySpec) { // not for many-to-many return null; } @Override - public Iterable findManyTargets(Long sourceId, String fieldName, QueryParams QueryParams) { + public ResourceList findManyTargets(Long sourceId, String fieldName, QuerySpec querySpec) { final User user = userRepository.findOne(sourceId); - return user.getRoles(); + return querySpec.apply(user.getRoles()); } + + @Override + public Class getSourceResourceClass() { + return User.class; + } + + @Override + public Class getTargetResourceClass() { + return Role.class; + } + } diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/model/Role.java b/spring-katharsis/src/main/java/org/baeldung/persistence/model/Role.java index fcaf40ac2c..f391efd37c 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/model/Role.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/model/Role.java @@ -1,8 +1,8 @@ package org.baeldung.persistence.model; import io.katharsis.resource.annotations.JsonApiId; +import io.katharsis.resource.annotations.JsonApiRelation; import io.katharsis.resource.annotations.JsonApiResource; -import io.katharsis.resource.annotations.JsonApiToMany; import java.util.Set; @@ -25,7 +25,7 @@ public class Role { private String name; @ManyToMany(mappedBy = "roles") - @JsonApiToMany + @JsonApiRelation private Set users; // @@ -66,23 +66,30 @@ public class Role { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } final Role other = (Role) obj; if (id == null) { - if (other.id != null) + if (other.id != null) { return false; - } else if (!id.equals(other.id)) + } + } else if (!id.equals(other.id)) { return false; + } if (name == null) { - if (other.name != null) + if (other.name != null) { return false; - } else if (!name.equals(other.name)) + } + } else if (!name.equals(other.name)) { return false; + } return true; } diff --git a/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java b/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java index 58a92002c8..7c55e29599 100644 --- a/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-katharsis/src/main/java/org/baeldung/persistence/model/User.java @@ -1,9 +1,9 @@ package org.baeldung.persistence.model; import io.katharsis.resource.annotations.JsonApiId; -import io.katharsis.resource.annotations.JsonApiIncludeByDefault; +import io.katharsis.resource.annotations.JsonApiRelation; import io.katharsis.resource.annotations.JsonApiResource; -import io.katharsis.resource.annotations.JsonApiToMany; +import io.katharsis.resource.annotations.SerializeType; import java.util.Set; @@ -31,8 +31,7 @@ public class User { @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) - @JsonApiToMany - @JsonApiIncludeByDefault + @JsonApiRelation(serialize=SerializeType.EAGER) private Set roles; public User() { @@ -87,15 +86,19 @@ public class User { @Override public boolean equals(final Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } final User user = (User) obj; - if (!email.equals(user.email)) + if (!email.equals(user.email)) { return false; + } return true; } diff --git a/spring-katharsis/src/main/resources/application.properties b/spring-katharsis/src/main/resources/application.properties index b55fdbba03..120b3c62ee 100644 --- a/spring-katharsis/src/main/resources/application.properties +++ b/spring-katharsis/src/main/resources/application.properties @@ -6,4 +6,7 @@ spring.jpa.hibernate.ddl-auto = create-drop spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect server.port=8082 -server.context-path=/spring-katharsis \ No newline at end of file +server.context-path=/spring-katharsis + +katharsis.domainName=http://localhost:8082/spring-katharsis +katharsis.pathPrefix=/ \ No newline at end of file diff --git a/spring-ldap/pom.xml b/spring-ldap/pom.xml index 2f806e89f8..41683d32a1 100644 --- a/spring-ldap/pom.xml +++ b/spring-ldap/pom.xml @@ -127,6 +127,7 @@ **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java diff --git a/spring-mobile/pom.xml b/spring-mobile/pom.xml index 6916bb9320..3d47bb106b 100644 --- a/spring-mobile/pom.xml +++ b/spring-mobile/pom.xml @@ -11,10 +11,10 @@ http://maven.apache.org - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-mockito/README.md b/spring-mockito/README.md index 3ced7161fa..969954c15e 100644 --- a/spring-mockito/README.md +++ b/spring-mockito/README.md @@ -5,3 +5,4 @@ ### Relevant Articles: - [Injecting Mockito Mocks into Spring Beans](http://www.baeldung.com/injecting-mocks-in-spring) +- [Mockito ArgumentMatchers](http://www.baeldung.com/mockito-argument-matchers) diff --git a/spring-mockito/pom.xml b/spring-mockito/pom.xml index 63a5521c98..e27e25b4c8 100644 --- a/spring-mockito/pom.xml +++ b/spring-mockito/pom.xml @@ -12,16 +12,16 @@ Injecting Mockito Mocks into Spring Beans - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 org.springframework.boot - spring-boot-starter + spring-boot-starter-web org.mockito diff --git a/spring-mockito/src/main/java/com/baeldung/app/api/Flower.java b/spring-mockito/src/main/java/com/baeldung/app/api/Flower.java new file mode 100644 index 0000000000..dc1c36e3ff --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/app/api/Flower.java @@ -0,0 +1,28 @@ +package com.baeldung.app.api; + +public class Flower { + + private String name; + private Integer petals; + + public Flower(String name, Integer petals) { + this.name = name; + this.petals = petals; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getPetals() { + return petals; + } + + public void setPetals(Integer petals) { + this.petals = petals; + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/app/api/MessageApi.java b/spring-mockito/src/main/java/com/baeldung/app/api/MessageApi.java new file mode 100644 index 0000000000..edbe5a1d5a --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/app/api/MessageApi.java @@ -0,0 +1,31 @@ +package com.baeldung.app.api; + +public class MessageApi { + private String from; + private String to; + private String text; + + public String getFrom() { + return from; + } + + public void setFrom(String from) { + this.from = from; + } + + public String getTo() { + return to; + } + + public void setTo(String to) { + this.to = to; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/app/rest/FlowerController.java b/spring-mockito/src/main/java/com/baeldung/app/rest/FlowerController.java new file mode 100644 index 0000000000..b3d8888cec --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/app/rest/FlowerController.java @@ -0,0 +1,27 @@ +package com.baeldung.app.rest; + +import com.baeldung.app.api.Flower; +import com.baeldung.domain.service.FlowerService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +@RequestMapping("/flowers") +public class FlowerController { + + @Autowired + private FlowerService flowerService; + + @PostMapping("/isAFlower") + public String isAFlower (@RequestBody String flower) { + return flowerService.analize(flower); + } + + @PostMapping("/isABigFlower") + public Boolean isABigFlower (@RequestBody Flower flower) { + return flowerService.isABigFlower(flower.getName(), flower.getPetals()); + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/app/rest/MessageController.java b/spring-mockito/src/main/java/com/baeldung/app/rest/MessageController.java new file mode 100644 index 0000000000..e23c2e7607 --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/app/rest/MessageController.java @@ -0,0 +1,34 @@ +package com.baeldung.app.rest; + +import com.baeldung.app.api.MessageApi; +import com.baeldung.domain.model.Message; +import com.baeldung.domain.service.MessageService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; + +import java.time.Instant; +import java.util.Date; +import java.util.UUID; + +@Controller +@RequestMapping("/message") +public class MessageController { + + @Autowired + private MessageService messageService; + + @PostMapping + public Message createMessage (@RequestBody MessageApi messageDTO) { + Message message = new Message(); + message.setText(messageDTO.getText()); + message.setFrom(messageDTO.getFrom()); + message.setTo(messageDTO.getTo()); + message.setDate(Date.from(Instant.now())); + message.setId(UUID.randomUUID()); + + return messageService.deliverMessage(message); + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/domain/model/Message.java b/spring-mockito/src/main/java/com/baeldung/domain/model/Message.java new file mode 100644 index 0000000000..a516d5619b --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/domain/model/Message.java @@ -0,0 +1,53 @@ +package com.baeldung.domain.model; + +import java.util.Date; +import java.util.UUID; + +public class Message { + + private String from; + private String to; + private String text; + private Date date; + private UUID id; + + public String getFrom() { + return from; + } + + public void setFrom(String from) { + this.from = from; + } + + public String getTo() { + return to; + } + + public void setTo(String to) { + this.to = to; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/domain/service/FlowerService.java b/spring-mockito/src/main/java/com/baeldung/domain/service/FlowerService.java new file mode 100644 index 0000000000..3c76cb5d76 --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/domain/service/FlowerService.java @@ -0,0 +1,28 @@ +package com.baeldung.domain.service; + +import org.springframework.stereotype.Service; + +import java.util.Arrays; +import java.util.List; + +@Service +public class FlowerService { + + private List flowers = Arrays.asList("Poppy", "Ageratum", "Carnation", "Diascia", "Lantana"); + + public String analize(String name) { + if(flowers.contains(name)) { + return "flower"; + } + return null; + } + + public boolean isABigFlower(String name, int petals) { + if(flowers.contains(name)) { + if(petals > 10) { + return true; + } + } + return false; + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/domain/service/MessageService.java b/spring-mockito/src/main/java/com/baeldung/domain/service/MessageService.java new file mode 100644 index 0000000000..d156c59571 --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/domain/service/MessageService.java @@ -0,0 +1,13 @@ +package com.baeldung.domain.service; + +import com.baeldung.domain.model.Message; +import org.springframework.stereotype.Service; + +@Service +public class MessageService { + + public Message deliverMessage (Message message) { + + return message; + } +} diff --git a/spring-mockito/src/main/java/com/baeldung/domain/util/MessageMatcher.java b/spring-mockito/src/main/java/com/baeldung/domain/util/MessageMatcher.java new file mode 100644 index 0000000000..05cb43e4df --- /dev/null +++ b/spring-mockito/src/main/java/com/baeldung/domain/util/MessageMatcher.java @@ -0,0 +1,27 @@ +package com.baeldung.domain.util; + +import com.baeldung.domain.model.Message; +import org.mockito.ArgumentMatcher; + +public class MessageMatcher extends ArgumentMatcher { + + private Message left; + + public MessageMatcher(Message message) { + this.left = message; + } + + @Override + public boolean matches(Object object) { + if (object instanceof Message) { + Message right = (Message) object; + return left.getFrom().equals(right.getFrom()) && + left.getTo().equals(right.getTo()) && + left.getText().equals(right.getText()) && + right.getDate() != null && + right.getId() != null; + } + + return false; + } +} \ No newline at end of file diff --git a/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java b/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationUnitTest.java similarity index 95% rename from spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java rename to spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationUnitTest.java index d70f916b12..573a37a9a4 100644 --- a/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationTest.java +++ b/spring-mockito/src/test/java/com/baeldung/UserServiceIntegrationUnitTest.java @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ActiveProfiles("test") @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = MocksApplication.class) -public class UserServiceIntegrationTest { +public class UserServiceIntegrationUnitTest { @Autowired private UserService userService; diff --git a/spring-mockito/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java b/spring-mockito/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java new file mode 100644 index 0000000000..f30af140af --- /dev/null +++ b/spring-mockito/src/test/java/com/baeldung/app/rest/FlowerControllerUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.app.rest; + +import com.baeldung.app.api.Flower; +import com.baeldung.domain.service.FlowerService; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.mockito.Matchers.anyInt; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class FlowerControllerUnitTest { + + @Mock + private FlowerService flowerService; + + @InjectMocks + private FlowerController flowerController; + + @Test + public void isAFlower_withMockito_OK() { + when(flowerService.analize(eq("violetta"))).thenReturn("Flower"); + + String response = flowerController.isAFlower("violetta"); + + Assert.assertEquals("Flower", response); + } + + @Test + public void isABigFlower_withMockito_OK() { + when(flowerService.isABigFlower(eq("violetta"), anyInt())).thenReturn(true); + + Flower flower = new Flower("violetta", 15); + + Boolean response = flowerController.isABigFlower(flower); + + Assert.assertTrue(response); + } +} diff --git a/spring-mockito/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java b/spring-mockito/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java new file mode 100644 index 0000000000..e303c85caf --- /dev/null +++ b/spring-mockito/src/test/java/com/baeldung/app/rest/MessageControllerUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.app.rest; + +import com.baeldung.app.api.MessageApi; +import com.baeldung.domain.model.Message; +import com.baeldung.domain.service.MessageService; +import com.baeldung.domain.util.MessageMatcher; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; + +import static org.mockito.Mockito.times; + +@RunWith(MockitoJUnitRunner.class) +public class MessageControllerUnitTest { + + @Mock + private MessageService messageService; + + @InjectMocks + private MessageController messageController; + + @Test + public void createMessage_NewMessage_OK() { + MessageApi messageApi = new MessageApi(); + messageApi.setFrom("me"); + messageApi.setTo("you"); + messageApi.setText("Hello, you!"); + + messageController.createMessage(messageApi); + + Message message = new Message(); + message.setFrom("me"); + message.setTo("you"); + message.setText("Hello, you!"); + + Mockito.verify(messageService, times(1)).deliverMessage(Matchers.argThat(new MessageMatcher(message))); + } +} diff --git a/spring-mvc-email/pom.xml b/spring-mvc-email/pom.xml index 436b4155fa..40d83046ef 100644 --- a/spring-mvc-email/pom.xml +++ b/spring-mvc-email/pom.xml @@ -10,10 +10,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-mvc-forms-thymeleaf/README.md b/spring-mvc-forms-thymeleaf/README.md index 450b10433c..f0f7e35a98 100644 --- a/spring-mvc-forms-thymeleaf/README.md +++ b/spring-mvc-forms-thymeleaf/README.md @@ -1,3 +1,4 @@ ### Relevant articles - [Session Attributes in Spring MVC](http://www.baeldung.com/spring-mvc-session-attributes) +- [Binding a List in Thymeleaf](http://www.baeldung.com/thymeleaf-list) diff --git a/spring-mvc-forms-thymeleaf/pom.xml b/spring-mvc-forms-thymeleaf/pom.xml index b6e931edda..31e5b6cd48 100644 --- a/spring-mvc-forms-thymeleaf/pom.xml +++ b/spring-mvc-forms-thymeleaf/pom.xml @@ -58,6 +58,7 @@ true **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java @@ -68,6 +69,8 @@ UTF-8 UTF-8 + 3.0.9.RELEASE + com.baeldung.sessionattrs.SessionAttrsApplication diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Book.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Book.java new file mode 100644 index 0000000000..823ff436fb --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Book.java @@ -0,0 +1,73 @@ +package com.baeldung.listbindingexample; + +public class Book { + + private long id; + + private String title; + + private String author; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((author == null) ? 0 : author.hashCode()); + result = prime * result + (int) (id ^ (id >>> 32)); + result = prime * result + ((title == null) ? 0 : title.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Book other = (Book) obj; + if (author == null) { + if (other.author != null) + return false; + } else if (!author.equals(other.author)) + return false; + if (id != other.id) + return false; + if (title == null) { + if (other.title != null) + return false; + } else if (!title.equals(other.title)) + return false; + return true; + } + + @Override + public String toString() { + return "Book [id=" + id + ", title=" + title + ", author=" + author + "]"; + } +} diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BookService.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BookService.java new file mode 100644 index 0000000000..c72d8fe70d --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BookService.java @@ -0,0 +1,10 @@ +package com.baeldung.listbindingexample; + +import java.util.List; + +public interface BookService { + + List findAll(); + + void saveAll(List books); +} diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BooksCreationDto.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BooksCreationDto.java new file mode 100644 index 0000000000..a25418815b --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/BooksCreationDto.java @@ -0,0 +1,29 @@ +package com.baeldung.listbindingexample; + +import java.util.ArrayList; +import java.util.List; + +public class BooksCreationDto { + + private List books; + + public BooksCreationDto() { + this.books = new ArrayList<>(); + } + + public BooksCreationDto(List books) { + this.books = books; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } + + public void addBook(Book book) { + this.books.add(book); + } +} diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Config.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Config.java new file mode 100644 index 0000000000..00e1a0393e --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/Config.java @@ -0,0 +1,33 @@ +package com.baeldung.listbindingexample; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; +import org.thymeleaf.templateresolver.ITemplateResolver; + +@EnableWebMvc +@Configuration +public class Config implements WebMvcConfigurer { + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/") + .setViewName("index"); + registry.setOrder(Ordered.HIGHEST_PRECEDENCE); + } + + @Bean + public ITemplateResolver templateResolver() { + ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver(); + resolver.setPrefix("templates/books/"); + resolver.setSuffix(".html"); + resolver.setTemplateMode(TemplateMode.HTML); + resolver.setCharacterEncoding("UTF-8"); + return resolver; + } +} diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/InMemoryBookService.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/InMemoryBookService.java new file mode 100644 index 0000000000..b35522a3ee --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/InMemoryBookService.java @@ -0,0 +1,44 @@ +package com.baeldung.listbindingexample; + +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +@Service +public class InMemoryBookService implements BookService { + + static Map booksDB = new HashMap<>(); + + @Override + public List findAll() { + return new ArrayList<>(booksDB.values()); + } + + @Override + public void saveAll(List books) { + long nextId = getNextId(); + for (Book book : books) { + if (book.getId() == 0) { + book.setId(nextId++); + } + } + + Map bookMap = books.stream() + .collect(Collectors.toMap(Book::getId, Function.identity())); + + booksDB.putAll(bookMap); + } + + private Long getNextId() { + return booksDB.keySet() + .stream() + .mapToLong(value -> value) + .max() + .orElse(0) + 1; + } +} diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/ListBindingApplication.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/ListBindingApplication.java new file mode 100644 index 0000000000..261954fcff --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/ListBindingApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.listbindingexample; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; + +@SpringBootApplication(exclude = { SecurityAutoConfiguration.class, DataSourceAutoConfiguration.class }) +public class ListBindingApplication { + + public static void main(String[] args) { + SpringApplication.run(ListBindingApplication.class, args); + } +} diff --git a/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/MultipleBooksController.java b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/MultipleBooksController.java new file mode 100644 index 0000000000..1ed44778c6 --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/java/com/baeldung/listbindingexample/MultipleBooksController.java @@ -0,0 +1,61 @@ +package com.baeldung.listbindingexample; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +import java.util.ArrayList; +import java.util.List; + +@Controller +@RequestMapping("/books") +public class MultipleBooksController { + + @Autowired + private BookService bookService; + + @GetMapping(value = "/all") + public String showAll(Model model) { + model.addAttribute("books", bookService.findAll()); + + return "allBooks"; + } + + @GetMapping(value = "/create") + public String showCreateForm(Model model) { + BooksCreationDto booksForm = new BooksCreationDto(); + + for (int i = 1; i <= 3; i++) { + booksForm.addBook(new Book()); + } + + model.addAttribute("form", booksForm); + + return "createBooksForm"; + } + + @GetMapping(value = "/edit") + public String showEditForm(Model model) { + List books = new ArrayList<>(); + bookService.findAll() + .iterator() + .forEachRemaining(books::add); + + model.addAttribute("form", new BooksCreationDto(books)); + + return "editBooksForm"; + } + + @PostMapping(value = "/save") + public String saveBooks(@ModelAttribute BooksCreationDto form, Model model) { + bookService.saveAll(form.getBooks()); + + model.addAttribute("books", bookService.findAll()); + + return "redirect:/books/all"; + } +} diff --git a/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/allBooks.html b/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/allBooks.html new file mode 100644 index 0000000000..9f75bec8bd --- /dev/null +++ b/spring-mvc-forms-thymeleaf/src/main/resources/templates/books/allBooks.html @@ -0,0 +1,40 @@ + + + All Books + + + +
+
+
+

Books

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

Add Books

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

Add Books

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

+

Binding a List in Thymeleaf - Example

+

+
+ + + diff --git a/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxyIntegrationTest.java b/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxyIntegrationTest.java index a8a6ce469d..037d4f9d71 100644 --- a/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxyIntegrationTest.java +++ b/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithScopedProxyIntegrationTest.java @@ -1,6 +1,7 @@ package com.baeldung.sessionattrs; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -22,7 +23,7 @@ import org.springframework.util.StringUtils; import org.springframework.web.context.WebApplicationContext; @RunWith(SpringRunner.class) -@SpringBootTest +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) @AutoConfigureMockMvc @Import(TestConfig.class) public class TodoControllerWithScopedProxyIntegrationTest { @@ -47,7 +48,7 @@ public class TodoControllerWithScopedProxyIntegrationTest { .andReturn(); TodoItem item = (TodoItem) result.getModelAndView().getModel().get("todo"); - assertTrue(StringUtils.isEmpty(item.getDescription())); + assertFalse(StringUtils.isEmpty(item.getDescription())); } @Test diff --git a/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributesIntegrationTest.java b/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributesIntegrationTest.java index b1caac5756..101f4f71d9 100644 --- a/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributesIntegrationTest.java +++ b/spring-mvc-forms-thymeleaf/src/test/java/com/baeldung/sessionattrs/TodoControllerWithSessionAttributesIntegrationTest.java @@ -22,7 +22,7 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.FlashMap; @RunWith(SpringRunner.class) -@SpringBootTest +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) @AutoConfigureMockMvc public class TodoControllerWithSessionAttributesIntegrationTest { diff --git a/spring-mvc-java/README.md b/spring-mvc-java/README.md index 5f62f71211..b97b961e60 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,9 @@ 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) +- [Spring Boot Annotations](http://www.baeldung.com/spring-boot-annotations) +- [Spring Scheduling Annotations](http://www.baeldung.com/spring-scheduling-annotations) +- [Spring Web Annotations](http://www.baeldung.com/spring-mvc-annotations) +- [Spring Core Annotations](http://www.baeldung.com/spring-core-annotations) diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index f8d1d32f63..14ced24da7 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -7,10 +7,10 @@ spring-mvc-java - parent-boot-5 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-2 @@ -49,33 +49,26 @@ com.fasterxml.jackson.core jackson-databind - ${jackson.version} javax.servlet javax.servlet-api - ${javax.servlet-api.version} - provided javax.servlet jstl - ${jstl.version} - runtime org.aspectj aspectjrt - ${aspectj.version} org.aspectj aspectjweaver - ${aspectj.version} @@ -87,7 +80,6 @@ net.sourceforge.htmlunit htmlunit - ${net.sourceforge.htmlunit} commons-logging @@ -111,7 +103,6 @@ com.jayway.jsonpath json-path - ${jsonpath.version} test @@ -128,11 +119,6 @@ - - javax.validation - validation-api - 1.1.0.Final - org.hibernate hibernate-validator @@ -170,13 +156,11 @@ maven-resources-plugin - ${maven-resources-plugin.version} org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} false @@ -223,6 +207,7 @@ **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java @@ -266,18 +251,14 @@ - - 2.1.5.RELEASE - 2.9.4 + 3.0.9.RELEASE 5.2.5.Final 5.1.40 - 5.4.1.Final - 3.1.0 - 1.2 + 6.0.10.Final 19.0 diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/Bike.java b/spring-mvc-java/src/main/java/com/baeldung/annotations/Bike.java new file mode 100644 index 0000000000..2a893e7903 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/annotations/Bike.java @@ -0,0 +1,20 @@ +package com.baeldung.annotations; + +import org.springframework.beans.factory.annotation.Required; +import org.springframework.context.annotation.DependsOn; + +@DependsOn +public class Bike implements Vehicle { + + private String color; + + @Required + public void setColor(String color) { + this.color = color; + } + + public String getColor() { + return color; + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/Biker.java b/spring-mvc-java/src/main/java/com/baeldung/annotations/Biker.java new file mode 100644 index 0000000000..dcbe534a90 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/annotations/Biker.java @@ -0,0 +1,24 @@ +package com.baeldung.annotations; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; + +@Component +public class Biker { + + @Autowired + @Qualifier("bike") + private Vehicle vehicle; + + @Autowired + public Biker(@Qualifier("bike") Vehicle vehicle) { + this.vehicle = vehicle; + } + + @Autowired + public void setVehicle(@Qualifier("bike") Vehicle vehicle) { + this.vehicle = vehicle; + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/Car.java b/spring-mvc-java/src/main/java/com/baeldung/annotations/Car.java new file mode 100644 index 0000000000..cb252b60c9 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/annotations/Car.java @@ -0,0 +1,30 @@ +package com.baeldung.annotations; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.DependsOn; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Component; + +@Component +@Primary +@DependsOn("engine") +public class Car implements Vehicle { + + @Autowired + private Engine engine; + + @Autowired + public Car(Engine engine) { + this.engine = engine; + } + + @Autowired + public void setEngine(Engine engine) { + this.engine = engine; + } + + public Engine getEngine() { + return engine; + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/CarMechanic.java b/spring-mvc-java/src/main/java/com/baeldung/annotations/CarMechanic.java new file mode 100644 index 0000000000..fc933dcd61 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/annotations/CarMechanic.java @@ -0,0 +1,10 @@ +package com.baeldung.annotations; + +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +@Component +@Lazy +public class CarMechanic { + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/CarUtility.java b/spring-mvc-java/src/main/java/com/baeldung/annotations/CarUtility.java new file mode 100644 index 0000000000..e66ab02b01 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/annotations/CarUtility.java @@ -0,0 +1,7 @@ +package com.baeldung.annotations; + +import org.springframework.stereotype.Component; + +@Component +public class CarUtility { +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/CustomResponseController.java b/spring-mvc-java/src/main/java/com/baeldung/annotations/CustomResponseController.java new file mode 100644 index 0000000000..a29a6252f2 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/annotations/CustomResponseController.java @@ -0,0 +1,62 @@ +package com.baeldung.annotations; + +import java.io.IOException; +import java.time.Year; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +@Controller +@RequestMapping("/customResponse") +public class CustomResponseController { + + @GetMapping("/hello") + public ResponseEntity hello() { + return new ResponseEntity<>("Hello World!", HttpStatus.OK); + } + + @GetMapping("/age") + public ResponseEntity age(@RequestParam("yearOfBirth") int yearOfBirth) { + if (isInFuture(yearOfBirth)) { + return new ResponseEntity<>("Year of birth cannot be in the future", HttpStatus.BAD_REQUEST); + } + + return new ResponseEntity<>("Your age is " + calculateAge(yearOfBirth), HttpStatus.OK); + } + + private int calculateAge(int yearOfBirth) { + return currentYear() - yearOfBirth; + } + + private boolean isInFuture(int year) { + return currentYear() < year; + } + + private int currentYear() { + return Year.now().getValue(); + } + + @GetMapping("/customHeader") + public ResponseEntity customHeader() { + HttpHeaders headers = new HttpHeaders(); + headers.add("Custom-Header", "foo"); + + return new ResponseEntity<>("Custom header set", headers, HttpStatus.OK); + } + + @GetMapping("/manual") + public void manual(HttpServletResponse response) throws IOException { + response.setHeader("Custom-Header", "foo"); + response.setStatus(200); + response.getWriter() + .println("Hello World!"); + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/Driver.java b/spring-mvc-java/src/main/java/com/baeldung/annotations/Driver.java new file mode 100644 index 0000000000..5a2d86e99e --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/annotations/Driver.java @@ -0,0 +1,32 @@ +package com.baeldung.annotations; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Component +public class Driver { + + @Autowired + private Vehicle vehicle; + + @Autowired + public Driver(Vehicle vehicle) { + this.vehicle = vehicle; + } + + @Autowired + public void setVehicle(Vehicle vehicle) { + this.vehicle = vehicle; + } + + public Vehicle getVehicle() { + return vehicle; + } + + @Scheduled(fixedRate = 10000) + @Scheduled(cron = "0 * * * * MON-FRI") + public void checkVehicle() { + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/Engine.java b/spring-mvc-java/src/main/java/com/baeldung/annotations/Engine.java new file mode 100644 index 0000000000..f8c0154639 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/annotations/Engine.java @@ -0,0 +1,26 @@ +package com.baeldung.annotations; + +import org.springframework.beans.factory.annotation.Value; + +public class Engine { + + @Value("8") + private int cylinderCount; + + @Value("${engine.fuelType}") + private String fuelType; + + public Engine() { + this(8); + } + + public Engine(@Value("8") int cylinderCount) { + this.cylinderCount = cylinderCount; + } + + @Value("8") + public void setCylinderCount(int cylinderCount) { + this.cylinderCount = cylinderCount; + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/Vehicle.java b/spring-mvc-java/src/main/java/com/baeldung/annotations/Vehicle.java new file mode 100644 index 0000000000..7176c3cc8a --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/annotations/Vehicle.java @@ -0,0 +1,4 @@ +package com.baeldung.annotations; + +public interface Vehicle { +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleController.java b/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleController.java new file mode 100644 index 0000000000..a979dff708 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleController.java @@ -0,0 +1,66 @@ +package com.baeldung.annotations; + +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +@Controller +@RequestMapping(value = "/vehicles", method = RequestMethod.GET) +public class VehicleController { + + @CrossOrigin + @ResponseBody + @RequestMapping("/hello") + public String hello() { + return "Hello World!"; + } + + @RequestMapping("/home") + public String home() { + return "home"; + } + + @PostMapping("/save") + public void saveVehicle(@RequestBody Vehicle vehicle) { + } + + @RequestMapping("/{id}") + public Vehicle getVehicle(@PathVariable("id") long id) { + return null; + } + + @RequestMapping + public Vehicle getVehicleByParam(@RequestParam("id") long id) { + return null; + } + + @RequestMapping("/buy") + public Car buyCar(@RequestParam(defaultValue = "5") int seatCount) { + return null; + } + + @ExceptionHandler(IllegalArgumentException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public void onIllegalArgumentException(IllegalArgumentException exception) { + } + + @PostMapping("/assemble") + public void assembleVehicle(@ModelAttribute("vehicle") Vehicle vehicle) { + } + + @ModelAttribute("vehicle") + public Vehicle getVehicle() { + return null; + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java b/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java new file mode 100644 index 0000000000..ab90d8cef2 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleFactoryApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.annotations; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +// @SpringBootApplication +public class VehicleFactoryApplication { + +// public static void main(String[] args) { +// SpringApplication.run(VehicleFactoryApplication.class, args); +// } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleFactoryConfig.java b/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleFactoryConfig.java new file mode 100644 index 0000000000..ad43a19b66 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleFactoryConfig.java @@ -0,0 +1,30 @@ +package com.baeldung.annotations; + +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; +import org.springframework.context.annotation.Lazy; +import org.springframework.context.annotation.PropertySource; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; + +@Configuration +@ComponentScan(basePackages = "com.baeldung.annotations") +@ComponentScan(basePackageClasses = VehicleFactoryConfig.class) +@ImportResource("classpath:/annotations.xml") +@PropertySource("classpath:/annotations.properties") +@Lazy +@EnableAutoConfiguration +@EnableAsync +@EnableScheduling +public class VehicleFactoryConfig { + + @Bean + @Lazy(false) + public Engine engine() { + return new Engine(); + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleRepository.java b/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleRepository.java new file mode 100644 index 0000000000..4dfd2dd771 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.annotations; + +import org.springframework.stereotype.Repository; + +@Repository +public class VehicleRepository { + +} diff --git a/spring-boot/src/main/java/com/baeldung/shutdown/shutdown/ShutdownController.java b/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleRestController.java similarity index 52% rename from spring-boot/src/main/java/com/baeldung/shutdown/shutdown/ShutdownController.java rename to spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleRestController.java index b0acc1f422..9dd98e688f 100644 --- a/spring-boot/src/main/java/com/baeldung/shutdown/shutdown/ShutdownController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleRestController.java @@ -1,7 +1,8 @@ -package com.baeldung.shutdown.shutdown; +package com.baeldung.annotations; import org.springframework.web.bind.annotation.RestController; @RestController -public class ShutdownController { +public class VehicleRestController { + } diff --git a/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleService.java b/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleService.java new file mode 100644 index 0000000000..19e5a3b4a4 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/annotations/VehicleService.java @@ -0,0 +1,13 @@ +package com.baeldung.annotations; + +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Service; + +@Service +public class VehicleService { + + @Async + public void repairCar() { + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/app/Application.java b/spring-mvc-java/src/main/java/com/baeldung/app/Application.java index 301caffca9..68d078de78 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/app/Application.java +++ b/spring-mvc-java/src/main/java/com/baeldung/app/Application.java @@ -3,7 +3,7 @@ package com.baeldung.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; @EnableAutoConfiguration diff --git a/spring-mvc-java/src/main/java/com/baeldung/dialect/CustomDialect.java b/spring-mvc-java/src/main/java/com/baeldung/dialect/CustomDialect.java deleted file mode 100644 index 0c6a7c3ae0..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/dialect/CustomDialect.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.dialect; - -import java.util.HashSet; -import java.util.Set; - -import com.baeldung.processor.NameProcessor; -import org.thymeleaf.dialect.AbstractDialect; -import org.thymeleaf.processor.IProcessor; - -public class CustomDialect extends AbstractDialect { - - @Override - public String getPrefix() { - return "custom"; - } - - @Override - public Set getProcessors() { - final Set processors = new HashSet(); - processors.add(new NameProcessor()); - return processors; - } - -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/processor/NameProcessor.java b/spring-mvc-java/src/main/java/com/baeldung/processor/NameProcessor.java deleted file mode 100644 index 9a7857198c..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/processor/NameProcessor.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.processor; - -import org.thymeleaf.Arguments; -import org.thymeleaf.dom.Element; -import org.thymeleaf.processor.attr.AbstractTextChildModifierAttrProcessor; - -public class NameProcessor extends AbstractTextChildModifierAttrProcessor { - - public NameProcessor() { - super("name"); - } - - @Override - protected String getText(final Arguments arguements, final Element elements, final String attributeName) { - return "Hello, " + elements.getAttributeValue(attributeName) + "!"; - } - - @Override - public int getPrecedence() { - return 1000; - } - -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java index 1b30479685..de47f9f69e 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java @@ -1,9 +1,7 @@ package com.baeldung.spring.web.config; -import java.util.HashSet; -import java.util.Set; - -import com.baeldung.dialect.CustomDialect; +import javax.servlet.ServletContext; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -13,27 +11,28 @@ import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; -import org.thymeleaf.dialect.IDialect; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @EnableWebMvc @Configuration -public class ClientWebConfig extends WebMvcConfigurerAdapter { +public class ClientWebConfig implements WebMvcConfigurer { public ClientWebConfig() { super(); } // API + + @Autowired + private ServletContext ctx; @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); registry.addViewController("/sample.html"); } @@ -59,7 +58,7 @@ public class ClientWebConfig extends WebMvcConfigurerAdapter { @Bean @Description("Thymeleaf template resolver serving HTML 5") public ServletContextTemplateResolver templateResolver() { - final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(ctx); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode("HTML5"); @@ -71,9 +70,6 @@ public class ClientWebConfig extends WebMvcConfigurerAdapter { public SpringTemplateEngine templateEngine() { final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); - final Set dialects = new HashSet<>(); - dialects.add(new CustomDialect()); - templateEngine.setAdditionalDialects(dialects); return templateEngine; } diff --git a/spring-mvc-java/src/main/resources/annotations.properties b/spring-mvc-java/src/main/resources/annotations.properties new file mode 100644 index 0000000000..ac2f50b39b --- /dev/null +++ b/spring-mvc-java/src/main/resources/annotations.properties @@ -0,0 +1 @@ +engine.fuelType=petrol \ No newline at end of file diff --git a/spring-mvc-java/src/main/resources/annotations.xml b/spring-mvc-java/src/main/resources/annotations.xml new file mode 100644 index 0000000000..b477b68ef6 --- /dev/null +++ b/spring-mvc-java/src/main/resources/annotations.xml @@ -0,0 +1,9 @@ + + + + + + + + diff --git a/spring-mvc-java/src/test/java/com/baeldung/config/ControllerClassNameHandlerMappingConfig.java b/spring-mvc-java/src/test/java/com/baeldung/config/ControllerClassNameHandlerMappingConfig.java deleted file mode 100644 index 6e9318602f..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/config/ControllerClassNameHandlerMappingConfig.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.config; - -import com.baeldung.web.controller.handlermapping.WelcomeController; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping; -import org.springframework.web.servlet.view.InternalResourceViewResolver; - -@Configuration -public class ControllerClassNameHandlerMappingConfig { - - @Bean - public ViewResolver viewResolver() { - InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); - viewResolver.setPrefix("/"); - viewResolver.setSuffix(".jsp"); - return viewResolver; - } - - @Bean - public ControllerClassNameHandlerMapping controllerClassNameHandlerMapping() { - ControllerClassNameHandlerMapping controllerClassNameHandlerMapping = new ControllerClassNameHandlerMapping(); - return controllerClassNameHandlerMapping; - } - - @Bean - public WelcomeController welcome() { - return new WelcomeController(); - } - - -} diff --git a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingIntegrationTest.java deleted file mode 100644 index b84998470d..0000000000 --- a/spring-mvc-java/src/test/java/com/baeldung/handlermappings/ControllerClassNameHandlerMappingIntegrationTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.handlermappings; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.MockitoAnnotations; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; - -import com.baeldung.config.ControllerClassNameHandlerMappingConfig; - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = ControllerClassNameHandlerMappingConfig.class) -public class ControllerClassNameHandlerMappingIntegrationTest { - - @Autowired - private WebApplicationContext webAppContext; - private MockMvc mockMvc; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build(); - } - - @Test - public void whenControllerClassNameMapping_thenMappedOK() throws Exception { - mockMvc.perform(get("/welcome")).andExpect(status().isOk()).andExpect(view().name("welcome")).andDo(print()); - } -} \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java index 479b02e77f..e734676b98 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java @@ -9,7 +9,6 @@ import org.junit.Test; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; -import com.gargoylesoftware.htmlunit.html.HtmlHeading1; import com.gargoylesoftware.htmlunit.html.HtmlPage; public class HtmlUnitWebScrapingLiveTest { @@ -37,7 +36,7 @@ public class HtmlUnitWebScrapingLiveTest { final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath(xpath).get(0); final HtmlPage postPage = latestPostLink.click(); - final List h1 = (List) postPage.getByXPath("//h1"); + final List h1 = postPage.getByXPath("//h1"); Assert.assertTrue(h1.size() > 0); } diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java index 17a68d67a5..5b86b59095 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java @@ -1,10 +1,14 @@ package com.baeldung.htmlunit; +import javax.servlet.ServletContext; + +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; @@ -13,8 +17,11 @@ import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.baeldung.web.controller" }) -public class TestConfig extends WebMvcConfigurerAdapter { +public class TestConfig implements WebMvcConfigurer { + @Autowired + private ServletContext ctx; + @Bean public ViewResolver thymeleafViewResolver() { final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); @@ -25,7 +32,7 @@ public class TestConfig extends WebMvcConfigurerAdapter { @Bean public ServletContextTemplateResolver templateResolver() { - final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(ctx); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode("HTML5"); diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java similarity index 95% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerTest.java rename to spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java index 23b8c639d3..23be3a1655 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.baeldung.web.controller.SimpleBookController; -public class SimpleBookRestControllerTest { +public class SimpleBookControllerIntegrationTest { private MockMvc mockMvc; private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; diff --git a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerTest.java b/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java similarity index 95% rename from spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerTest.java rename to spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java index 4be0ded963..c5bd53f1a7 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookControllerTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/web/controller/SimpleBookRestControllerIntegrationTest.java @@ -12,7 +12,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.baeldung.web.controller.SimpleBookController; -public class SimpleBookControllerTest { +public class SimpleBookRestControllerIntegrationTest { private MockMvc mockMvc; private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; diff --git a/spring-mvc-simple/README.md b/spring-mvc-simple/README.md index 600a448076..3505fb8009 100644 --- a/spring-mvc-simple/README.md +++ b/spring-mvc-simple/README.md @@ -4,3 +4,4 @@ - [Template Engines for Spring](http://www.baeldung.com/spring-template-engines) - [Spring 5 and Servlet 4 – The PushBuilder](http://www.baeldung.com/spring-5-push) - [Servlet Redirect vs Forward](http://www.baeldung.com/servlet-redirect-forward) +- [Apache Tiles Integration with Spring MVC](http://www.baeldung.com/spring-mvc-apache-tiles) diff --git a/spring-mvc-simple/pom.xml b/spring-mvc-simple/pom.xml index 07d7221048..08eab59540 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} @@ -88,12 +88,18 @@ spring-jade4j ${jade.version} + + + org.apache.tiles + tiles-jsp + ${apache-tiles.version} + org.springframework spring-test - ${springframework.version} + ${spring.version} test @@ -159,7 +165,6 @@ 1.8 1.8 UTF-8 - 5.0.2.RELEASE 3.2.0 3.7.0 2.21.0 @@ -182,6 +187,7 @@ 5.1.0 20180130 5.0.2.RELEASE + 3.0.8 diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java index c4c6791f9a..c28ee02eef 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/ApplicationConfiguration.java @@ -14,7 +14,7 @@ import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; import org.springframework.web.servlet.view.InternalResourceViewResolver; @@ -24,7 +24,7 @@ import java.util.List; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.baeldung.springmvcforms", "com.baeldung.spring.controller", "com.baeldung.spring.validator" }) -public class ApplicationConfiguration extends WebMvcConfigurerAdapter { +public class ApplicationConfiguration implements WebMvcConfigurer { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { @@ -59,7 +59,5 @@ public class ApplicationConfiguration extends WebMvcConfigurerAdapter { converters.add(new StringHttpMessageConverter()); converters.add(new RssChannelHttpMessageConverter()); converters.add(new JsonChannelHttpMessageConverter()); - - super.configureMessageConverters(converters); } } diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/TilesApplicationConfiguration.java similarity index 86% rename from spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java rename to spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/TilesApplicationConfiguration.java index d2e90a4f53..de2b7fe68f 100644 --- a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/TilesApplicationConfiguration.java @@ -1,47 +1,47 @@ -package com.baeldung.tiles.springmvc; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.springframework.web.servlet.view.tiles3.TilesConfigurer; -import org.springframework.web.servlet.view.tiles3.TilesViewResolver; - -@Configuration -@EnableWebMvc -@ComponentScan(basePackages = "com.baeldung.tiles.springmvc") -public class ApplicationConfiguration extends WebMvcConfigurerAdapter { - - /** - * Configure TilesConfigurer. - */ - @Bean - public TilesConfigurer tilesConfigurer() { - TilesConfigurer tilesConfigurer = new TilesConfigurer(); - tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/views/**/tiles.xml" }); - tilesConfigurer.setCheckRefresh(true); - return tilesConfigurer; - } - - /** - * Configure ViewResolvers to deliver views. - */ - @Override - public void configureViewResolvers(ViewResolverRegistry registry) { - TilesViewResolver viewResolver = new TilesViewResolver(); - registry.viewResolver(viewResolver); - } - - /** - * Configure ResourceHandlers to serve static resources - */ - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/static/**").addResourceLocations("/static/"); - } - -} +package com.baeldung.spring.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.view.tiles3.TilesConfigurer; +import org.springframework.web.servlet.view.tiles3.TilesViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "com.baeldung.spring.controller.tiles") +public class TilesApplicationConfiguration implements WebMvcConfigurer { + + /** + * Configure TilesConfigurer. + */ + @Bean + public TilesConfigurer tilesConfigurer() { + TilesConfigurer tilesConfigurer = new TilesConfigurer(); + tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/views/**/tiles.xml" }); + tilesConfigurer.setCheckRefresh(true); + return tilesConfigurer; + } + + /** + * Configure ViewResolvers to deliver views. + */ + @Override + public void configureViewResolvers(ViewResolverRegistry registry) { + TilesViewResolver viewResolver = new TilesViewResolver(); + registry.viewResolver(viewResolver); + } + + /** + * Configure ResourceHandlers to serve static resources + */ + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/static/**").addResourceLocations("/static/"); + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java index 09030a8347..74094a11c7 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/configuration/WebInitializer.java @@ -21,6 +21,8 @@ public class WebInitializer implements WebApplicationInitializer { // ctx.register(JadeTemplateConfiguration.class); // ctx.register(PushConfiguration.class); // ctx.setServletContext(container); + + //ctx.register(TilesApplicationConfiguration.class); // Manage the lifecycle of the root application context container.addListener(new ContextLoaderListener(ctx)); diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/tiles/TilesController.java similarity index 87% rename from spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java rename to spring-mvc-simple/src/main/java/com/baeldung/spring/controller/tiles/TilesController.java index 1a348d1c26..319340b886 100644 --- a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/tiles/TilesController.java @@ -1,26 +1,26 @@ -package com.baeldung.tiles.springmvc; - -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -@Controller -@RequestMapping("/") -public class ApplicationController { - - @RequestMapping(value = { "/" }, method = RequestMethod.GET) - public String homePage(ModelMap model) { - return "home"; - } - - @RequestMapping(value = { "/apachetiles" }, method = RequestMethod.GET) - public String productsPage(ModelMap model) { - return "apachetiles"; - } - - @RequestMapping(value = { "/springmvc" }, method = RequestMethod.GET) - public String contactUsPage(ModelMap model) { - return "springmvc"; - } -} +package com.baeldung.spring.controller.tiles; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +@RequestMapping("/") +public class TilesController { + + @RequestMapping(value = { "/" }, method = RequestMethod.GET) + public String homePage(ModelMap model) { + return "home"; + } + + @RequestMapping(value = { "/apachetiles" }, method = RequestMethod.GET) + public String productsPage(ModelMap model) { + return "apachetiles"; + } + + @RequestMapping(value = { "/springmvc" }, method = RequestMethod.GET) + public String contactUsPage(ModelMap model) { + return "springmvc"; + } +} diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp similarity index 97% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp index 9936957c04..918c52ab45 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp @@ -1,12 +1,12 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - - - - -Apache Tiles - - -

Tiles with Spring MVC Demo

- +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Apache Tiles + + +

Tiles with Spring MVC Demo

+ \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/home.jsp similarity index 97% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/home.jsp index b501d4968e..47157a5d2a 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/home.jsp @@ -1,12 +1,12 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - - - - -Home - - -

Welcome to Apache Tiles integration with Spring MVC

- +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Home + + +

Welcome to Apache Tiles integration with Spring MVC

+ \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/springmvc.jsp similarity index 97% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/springmvc.jsp index 209b1004de..497e04901a 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/pages/springmvc.jsp @@ -1,12 +1,12 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> - - - - -Spring MVC - - -

Spring MVC configured to work with Apache Tiles

- +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Spring MVC + + +

Spring MVC configured to work with Apache Tiles

+ \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp similarity index 96% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp index 2370ad4ab1..064f3ee78b 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp @@ -1,25 +1,25 @@ -<%@ page language="java" contentType="text/html; charset=ISO-8859-1" - pageEncoding="ISO-8859-1"%> -<%@ page isELIgnored="false"%> -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> -<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%> - - - - - -<tiles:getAsString name="title" /> - - - - -
- - -
- -
- -
- - +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ page isELIgnored="false"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%> + + + + + +<tiles:getAsString name="title" /> + + + + +
+ + +
+ +
+ +
+ + diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp similarity index 95% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp index 3849cc5230..0946549e06 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp @@ -1,2 +1,2 @@ - -
copyright Baeldung
+ +
copyright Baeldung
diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp similarity index 97% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp index 8a878c857d..4ad29d82e0 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp @@ -1,3 +1,3 @@ -
-

Welcome to Spring MVC integration with Apache Tiles

+
+

Welcome to Spring MVC integration with Apache Tiles

\ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp similarity index 97% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp index 2c91eace85..17502fd051 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp @@ -1,8 +1,8 @@ - + diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/tiles.xml similarity index 97% rename from spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml rename to spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/tiles.xml index 789fbd809a..648ecb44fe 100644 --- a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml +++ b/spring-mvc-simple/src/main/webapp/WEB-INF/views/tiles/tiles.xml @@ -1,34 +1,34 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/static/css/app.css b/spring-mvc-simple/src/main/webapp/static/css/app.css similarity index 100% rename from spring-mvc-tiles/src/main/webapp/static/css/app.css rename to spring-mvc-simple/src/main/webapp/static/css/app.css 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/README.md b/spring-mvc-tiles/README.md deleted file mode 100644 index 58991005f5..0000000000 --- a/spring-mvc-tiles/README.md +++ /dev/null @@ -1,2 +0,0 @@ -###Relevant Articles: -- [Apache Tiles Integration with Spring MVC](http://www.baeldung.com/spring-mvc-apache-tiles) diff --git a/spring-mvc-tiles/pom.xml b/spring-mvc-tiles/pom.xml deleted file mode 100644 index 94908d5d8b..0000000000 --- a/spring-mvc-tiles/pom.xml +++ /dev/null @@ -1,94 +0,0 @@ - - 4.0.0 - com.baeldung - spring-mvc-tiles - 0.0.1-SNAPSHOT - war - spring-mvc-tiles - Integrating Spring MVC with Apache Tiles - - - com.baeldung - parent-spring - 0.0.1-SNAPSHOT - ../parent-spring - - - - - - org.springframework - spring-core - ${springframework.version} - - - commons-logging - commons-logging - - - - - org.springframework - spring-web - ${springframework.version} - - - org.springframework - spring-webmvc - ${springframework.version} - - - - org.apache.tiles - tiles-jsp - ${apache-tiles.version} - - - - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - - - javax.servlet.jsp - javax.servlet.jsp-api - ${javax.servlet.jsp-api.version} - - - javax.servlet - jstl - ${jstl.version} - - - - - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - src/main/webapp - spring-mvc-tiles - false - - - - - spring-mvc-tiles - - - - 4.3.4.RELEASE - 3.0.7 - 3.1.0 - 2.3.1 - 1.2 - 2.6 - - - diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java deleted file mode 100644 index 79583dbe83..0000000000 --- a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.tiles.springmvc; - -import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; - -public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { - - @Override - protected Class[] getRootConfigClasses() { - return new Class[] { ApplicationConfiguration.class }; - } - - @Override - protected Class[] getServletConfigClasses() { - return null; - } - - @Override - protected String[] getServletMappings() { - return new String[] { "/" }; - } - -} diff --git a/spring-mvc-velocity/pom.xml b/spring-mvc-velocity/pom.xml index 07d7182b7d..077d55c2de 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 @@ -112,6 +112,7 @@ true **/*IntegrationTest.java + **/*IntTest.java @@ -125,9 +126,6 @@ - - 4.3.4.RELEASE - 1.6.6 diff --git a/spring-protobuf/pom.xml b/spring-protobuf/pom.xml index 5081634d9b..1dce122f27 100644 --- a/spring-protobuf/pom.xml +++ b/spring-protobuf/pom.xml @@ -7,10 +7,10 @@ spring-protobuf - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-quartz/pom.xml b/spring-quartz/pom.xml index 435e571180..2a449ce494 100644 --- a/spring-quartz/pom.xml +++ b/spring-quartz/pom.xml @@ -11,10 +11,10 @@ Demo project for Scheduling in Spring with Quartz - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-reactor/pom.xml b/spring-reactor/pom.xml index 1098f8b60d..cedaa5e381 100644 --- a/spring-reactor/pom.xml +++ b/spring-reactor/pom.xml @@ -9,10 +9,10 @@ http://maven.apache.org - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-remoting/pom.xml b/spring-remoting/pom.xml index aac8357c10..150c1a771c 100644 --- a/spring-remoting/pom.xml +++ b/spring-remoting/pom.xml @@ -11,10 +11,10 @@ Parent for all projects related to Spring Remoting. - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-rest-angular/pom.xml b/spring-rest-angular/pom.xml index 7f3c21801c..090f09de3b 100644 --- a/spring-rest-angular/pom.xml +++ b/spring-rest-angular/pom.xml @@ -9,10 +9,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-rest-embedded-tomcat/pom.xml b/spring-rest-embedded-tomcat/pom.xml index 9ab9b4b718..8fbecb86e8 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 @@ -74,6 +74,7 @@ true **/*IntegrationTest.java + **/*IntTest.java **/*LongRunningUnitTest.java **/*ManualTest.java **/JdbcTest.java @@ -85,7 +86,6 @@ - 5.0.2.RELEASE 2.19.1 2.9.2 1.8 diff --git a/spring-rest-full/pom.xml b/spring-rest-full/pom.xml index fd2c485eaf..1df22faddd 100644 --- a/spring-rest-full/pom.xml +++ b/spring-rest-full/pom.xml @@ -9,10 +9,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -286,6 +286,7 @@ **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java diff --git a/spring-rest-full/src/test/java/org/baeldung/spring/ConfigTest.java b/spring-rest-full/src/test/java/org/baeldung/spring/ConfigIntegrationTest.java similarity index 75% rename from spring-rest-full/src/test/java/org/baeldung/spring/ConfigTest.java rename to spring-rest-full/src/test/java/org/baeldung/spring/ConfigIntegrationTest.java index 56f3de6cb0..77603da0dd 100644 --- a/spring-rest-full/src/test/java/org/baeldung/spring/ConfigTest.java +++ b/spring-rest-full/src/test/java/org/baeldung/spring/ConfigIntegrationTest.java @@ -6,9 +6,9 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration @ComponentScan("org.baeldung.test") -public class ConfigTest extends WebMvcConfigurerAdapter { +public class ConfigIntegrationTest extends WebMvcConfigurerAdapter { - public ConfigTest() { + public ConfigIntegrationTest() { super(); } diff --git a/spring-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java b/spring-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java index a899d387ab..912ad89ed7 100644 --- a/spring-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java +++ b/spring-rest-full/src/test/java/org/baeldung/test/JacksonMarshaller.java @@ -8,9 +8,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; -import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Preconditions; diff --git a/spring-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java b/spring-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java index c0e1f9d04d..a6577e4de8 100644 --- a/spring-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java +++ b/spring-rest-full/src/test/java/org/baeldung/web/FooDiscoverabilityLiveTest.java @@ -4,7 +4,7 @@ import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import org.baeldung.common.web.AbstractDiscoverabilityLiveTest; import org.baeldung.persistence.model.Foo; -import org.baeldung.spring.ConfigTest; +import org.baeldung.spring.ConfigIntegrationTest; import org.junit.runner.RunWith; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { ConfigIntegrationTest.class }, loader = AnnotationConfigContextLoader.class) @ActiveProfiles("test") public class FooDiscoverabilityLiveTest extends AbstractDiscoverabilityLiveTest { diff --git a/spring-rest-full/src/test/java/org/baeldung/web/FooLiveTest.java b/spring-rest-full/src/test/java/org/baeldung/web/FooLiveTest.java index 5a4f472fe3..65564a6845 100644 --- a/spring-rest-full/src/test/java/org/baeldung/web/FooLiveTest.java +++ b/spring-rest-full/src/test/java/org/baeldung/web/FooLiveTest.java @@ -4,7 +4,7 @@ import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import org.baeldung.common.web.AbstractBasicLiveTest; import org.baeldung.persistence.model.Foo; -import org.baeldung.spring.ConfigTest; +import org.baeldung.spring.ConfigIntegrationTest; import org.junit.runner.RunWith; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; @@ -12,7 +12,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { ConfigIntegrationTest.class }, loader = AnnotationConfigContextLoader.class) @ActiveProfiles("test") public class FooLiveTest extends AbstractBasicLiveTest { diff --git a/spring-rest-full/src/test/java/org/baeldung/web/FooPageableLiveTest.java b/spring-rest-full/src/test/java/org/baeldung/web/FooPageableLiveTest.java index 62a8983356..3f637c5213 100644 --- a/spring-rest-full/src/test/java/org/baeldung/web/FooPageableLiveTest.java +++ b/spring-rest-full/src/test/java/org/baeldung/web/FooPageableLiveTest.java @@ -13,7 +13,7 @@ import java.util.List; import org.baeldung.common.web.AbstractBasicLiveTest; import org.baeldung.persistence.model.Foo; -import org.baeldung.spring.ConfigTest; +import org.baeldung.spring.ConfigIntegrationTest; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ActiveProfiles; @@ -22,7 +22,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ConfigTest.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { ConfigIntegrationTest.class }, loader = AnnotationConfigContextLoader.class) @ActiveProfiles("test") public class FooPageableLiveTest extends AbstractBasicLiveTest { diff --git a/spring-rest-query-language/pom.xml b/spring-rest-query-language/pom.xml index d20a97268b..398181c1c8 100644 --- a/spring-rest-query-language/pom.xml +++ b/spring-rest-query-language/pom.xml @@ -9,10 +9,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 @@ -305,6 +305,7 @@ **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java 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..36ee39ab27 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 @@ -226,6 +227,7 @@ true **/*IntegrationTest.java + **/*IntTest.java **/*LongRunningUnitTest.java **/*ManualTest.java **/JdbcTest.java @@ -240,7 +242,7 @@ cargo-maven2-plugin ${cargo-maven2-plugin.version} - true + tomcat8x embedded @@ -281,6 +283,7 @@ **/*IntegrationTest.java + **/*IntTest.java 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..d1dcf554a5 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,9 @@ 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) +- [Configure a RestTemplate with RestTemplateBuilder](http://www.baeldung.com/spring-rest-template-builder) + diff --git a/spring-rest/pom.xml b/spring-rest/pom.xml index d56eb9949b..2b6b663b2a 100644 --- a/spring-rest/pom.xml +++ b/spring-rest/pom.xml @@ -253,6 +253,7 @@ true **/*IntegrationTest.java + **/*IntTest.java **/*LongRunningUnitTest.java **/*ManualTest.java **/*LiveTest.java diff --git a/spring-rest/src/main/java/com/baeldung/transfer/LoginForm.java b/spring-rest/src/main/java/com/baeldung/transfer/LoginForm.java index 19c9b0a349..caafcdb500 100644 --- a/spring-rest/src/main/java/com/baeldung/transfer/LoginForm.java +++ b/spring-rest/src/main/java/com/baeldung/transfer/LoginForm.java @@ -7,6 +7,12 @@ public class LoginForm { public LoginForm() { } + public LoginForm(String username, String password) { + super(); + this.username = username; + this.password = password; + } + public String getUsername() { return username; } diff --git a/spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java b/spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java new file mode 100644 index 0000000000..8743af20fe --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/config/RestClientConfig.java @@ -0,0 +1,28 @@ +package org.baeldung.config; + +import java.util.ArrayList; +import java.util.List; + +import org.baeldung.interceptors.RestTemplateHeaderModifierInterceptor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.util.CollectionUtils; +import org.springframework.web.client.RestTemplate; + +@Configuration +public class RestClientConfig { + + @Bean + public RestTemplate restTemplate() { + RestTemplate restTemplate = new RestTemplate(); + + List interceptors = restTemplate.getInterceptors(); + if (CollectionUtils.isEmpty(interceptors)) { + interceptors = new ArrayList(); + } + 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/resttemplate/configuration/CustomClientHttpRequestInterceptor.java b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java new file mode 100644 index 0000000000..a39994ae67 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/CustomClientHttpRequestInterceptor.java @@ -0,0 +1,32 @@ +package org.baeldung.resttemplate.configuration; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; + +import java.io.IOException; + +/** + * interceptor to log incoming requests + */ +public class CustomClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { + + private static final Logger LOGGER = LoggerFactory.getLogger(CustomClientHttpRequestInterceptor.class); + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + + logRequestDetails(request); + + return execution.execute(request, body); + } + + private void logRequestDetails(HttpRequest request) { + LOGGER.info("Request Headers: {}", request.getHeaders()); + LOGGER.info("Request Method: {}", request.getMethod()); + LOGGER.info("Request URI: {}", request.getURI()); + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java new file mode 100644 index 0000000000..5e8220d064 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/CustomRestTemplateCustomizer.java @@ -0,0 +1,14 @@ +package org.baeldung.resttemplate.configuration; + +import org.springframework.boot.web.client.RestTemplateCustomizer; +import org.springframework.web.client.RestTemplate; + +/** + * customize rest template with an interceptor + */ +public class CustomRestTemplateCustomizer implements RestTemplateCustomizer { + @Override + public void customize(RestTemplate restTemplate) { + restTemplate.getInterceptors().add(new CustomClientHttpRequestInterceptor()); + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java new file mode 100644 index 0000000000..ee404db4f8 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/HelloController.java @@ -0,0 +1,37 @@ +package org.baeldung.resttemplate.configuration; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestTemplate; + +/** + * Controller to test RestTemplate configuration + */ +@RestController +public class HelloController { + + private static final String RESOURCE_URL = "http://localhost:8082/spring-rest/baz"; + private RestTemplate restTemplate; + + @Autowired + public HelloController(RestTemplateBuilder builder) { + this.restTemplate = builder.build(); + } + + @RequestMapping("/foo") + public String foo() { + + ResponseEntity response = restTemplate.getForEntity(RESOURCE_URL, String.class); + + return response.getBody(); + } + + @RequestMapping("/baz") + public String baz() { + return "Foo"; + } + +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/RestTemplateConfigurationApplication.java b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/RestTemplateConfigurationApplication.java new file mode 100644 index 0000000000..76fc346aca --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/RestTemplateConfigurationApplication.java @@ -0,0 +1,14 @@ +package org.baeldung.resttemplate.configuration; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@EnableAutoConfiguration +public class RestTemplateConfigurationApplication { + + public static void main(String[] args) { + SpringApplication.run(RestTemplateConfigurationApplication.class, args); + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java new file mode 100644 index 0000000000..4e121185b1 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/configuration/SpringConfig.java @@ -0,0 +1,28 @@ +package org.baeldung.resttemplate.configuration; + +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; + +@Configuration +@EnableAutoConfiguration +@ComponentScan("org.baeldung.resttemplate.configuration") +public class SpringConfig { + + @Bean + @Qualifier("customRestTemplateCustomizer") + public CustomRestTemplateCustomizer customRestTemplateCustomizer() { + return new CustomRestTemplateCustomizer(); + } + + @Bean + @DependsOn(value = {"customRestTemplateCustomizer"}) + public RestTemplateBuilder restTemplateBuilder() { + return new RestTemplateBuilder(customRestTemplateCustomizer()); + } + +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/EmployeeApplication.java b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/EmployeeApplication.java new file mode 100644 index 0000000000..baaa4c4d80 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/EmployeeApplication.java @@ -0,0 +1,16 @@ +package org.baeldung.resttemplate.lists; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * Sample application used to demonstrate working with Lists and RestTemplate. + */ +@SpringBootApplication +public class EmployeeApplication +{ + public static void main(String[] args) + { + SpringApplication.run(EmployeeApplication.class, args); + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/client/EmployeeClient.java b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/client/EmployeeClient.java new file mode 100644 index 0000000000..729fa3ca3e --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/client/EmployeeClient.java @@ -0,0 +1,100 @@ +package org.baeldung.resttemplate.lists.client; + +import org.baeldung.resttemplate.lists.dto.Employee; +import org.baeldung.resttemplate.lists.dto.EmployeeList; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.*; +import org.springframework.web.client.RestTemplate; + +import java.util.ArrayList; +import java.util.List; + +/** + * Application that shows how to use Lists with RestTemplate. + */ +public class EmployeeClient +{ + public static void main(String[] args) + { + EmployeeClient employeeClient = new EmployeeClient(); + + System.out.println("Calling GET using ParameterizedTypeReference"); + employeeClient.getAllEmployeesUsingParameterizedTypeReference(); + + System.out.println("Calling GET using wrapper class"); + employeeClient.getAllEmployeesUsingWrapperClass(); + + System.out.println("Calling POST using normal lists"); + employeeClient.createEmployeesUsingLists(); + + System.out.println("Calling POST using wrapper class"); + employeeClient.createEmployeesUsingWrapperClass(); + } + + public EmployeeClient() + { + + } + + public List getAllEmployeesUsingParameterizedTypeReference() + { + RestTemplate restTemplate = new RestTemplate(); + + ResponseEntity> response = + restTemplate.exchange( + "http://localhost:8080/spring-rest/employees/", + HttpMethod.GET, + null, + new ParameterizedTypeReference>(){}); + + List employees = response.getBody(); + + employees.forEach(e -> System.out.println(e)); + + return employees; + } + + public List getAllEmployeesUsingWrapperClass() + { + RestTemplate restTemplate = new RestTemplate(); + + EmployeeList response = + restTemplate.getForObject( + "http://localhost:8080/spring-rest/employees/v2", + EmployeeList.class); + + List employees = response.getEmployees(); + + employees.forEach(e -> System.out.println(e)); + + return employees; + } + + public void createEmployeesUsingLists() + { + RestTemplate restTemplate = new RestTemplate(); + + List newEmployees = new ArrayList<>(); + newEmployees.add(new Employee(3, "Intern")); + newEmployees.add(new Employee(4, "CEO")); + + restTemplate.postForObject( + "http://localhost:8080/spring-rest/employees/", + newEmployees, + ResponseEntity.class); + } + + public void createEmployeesUsingWrapperClass() + { + RestTemplate restTemplate = new RestTemplate(); + + List newEmployees = new ArrayList<>(); + newEmployees.add(new Employee(3, "Intern")); + newEmployees.add(new Employee(4, "CEO")); + + restTemplate.postForObject( + "http://localhost:8080/spring-rest/employees/v2/", + new EmployeeList(newEmployees), + ResponseEntity.class); + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/controller/EmployeeResource.java b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/controller/EmployeeResource.java new file mode 100644 index 0000000000..f051c6a78b --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/controller/EmployeeResource.java @@ -0,0 +1,45 @@ +package org.baeldung.resttemplate.lists.controller; + +import org.baeldung.resttemplate.lists.dto.Employee; +import org.baeldung.resttemplate.lists.dto.EmployeeList; +import org.baeldung.resttemplate.lists.service.EmployeeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/employees") +public class EmployeeResource +{ + @Autowired + private EmployeeService employeeService; + + @RequestMapping(method = RequestMethod.GET, path = "/") + public List getEmployees() + { + return employeeService.getAllEmployees(); + } + + @RequestMapping(method = RequestMethod.GET, path = "/v2") + public EmployeeList getEmployeesUsingWrapperClass() + { + List employees = employeeService.getAllEmployees(); + return new EmployeeList(employees); + } + + @RequestMapping(method = RequestMethod.POST, path = "/") + public void addEmployees(@RequestBody List employees) + { + employeeService.addEmployees(employees); + } + + @RequestMapping(method = RequestMethod.POST, path = "/v2") + public void addEmployeesUsingWrapperClass(@RequestBody EmployeeList employeeWrapper) + { + employeeService.addEmployees(employeeWrapper.getEmployees()); + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/Employee.java b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/Employee.java new file mode 100644 index 0000000000..bd8ebbf969 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/Employee.java @@ -0,0 +1,40 @@ +package org.baeldung.resttemplate.lists.dto; + +public class Employee { + + public long id; + public String title; + + public Employee() + { + + } + + public Employee(long id, String title) + { + this.id = id; + this.title = title; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + @Override + public String toString() + { + return "Employee #" + id + "[" + title + "]"; + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/EmployeeList.java b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/EmployeeList.java new file mode 100644 index 0000000000..2bb86ac5b4 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/dto/EmployeeList.java @@ -0,0 +1,29 @@ +package org.baeldung.resttemplate.lists.dto; + +import java.util.ArrayList; +import java.util.List; + +public class EmployeeList +{ + public List employees; + + public EmployeeList() + { + employees = new ArrayList<>(); + } + + public EmployeeList(List employees) + { + this.employees = employees; + } + + public void setEmployees(List employees) + { + this.employees = employees; + } + + public List getEmployees() + { + return employees; + } +} diff --git a/spring-rest/src/main/java/org/baeldung/resttemplate/lists/service/EmployeeService.java b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/service/EmployeeService.java new file mode 100644 index 0000000000..08196dda77 --- /dev/null +++ b/spring-rest/src/main/java/org/baeldung/resttemplate/lists/service/EmployeeService.java @@ -0,0 +1,24 @@ +package org.baeldung.resttemplate.lists.service; + +import org.baeldung.resttemplate.lists.dto.Employee; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class EmployeeService +{ + public List getAllEmployees() + { + List employees = new ArrayList<>(); + employees.add(new Employee(1, "Manager")); + employees.add(new Employee(2, "Java Developer")); + return employees; + } + + public void addEmployees(List employees) + { + employees.forEach(e -> System.out.println("Adding new employee " + e)); + } +} diff --git a/spring-rest/src/main/resources/com/baeldung/produceimage/images/favicon.ico b/spring-rest/src/main/resources/com/baeldung/produceimage/images/favicon.ico new file mode 100644 index 0000000000..64105ac11c Binary files /dev/null and b/spring-rest/src/main/resources/com/baeldung/produceimage/images/favicon.ico differ diff --git a/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorTest.java b/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java similarity index 97% rename from spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorTest.java rename to spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java index e87adbc712..a84f866dfe 100644 --- a/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorTest.java +++ b/spring-rest/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java @@ -10,7 +10,7 @@ import com.baeldung.propertyeditor.creditcard.CreditCard; import com.baeldung.propertyeditor.creditcard.CreditCardEditor; @RunWith(MockitoJUnitRunner.class) -public class CreditCardEditorTest { +public class CreditCardEditorUnitTest { private CreditCardEditor creditCardEditor; diff --git a/spring-rest/src/test/java/org/baeldung/resttemplate/RestTemplateIntegrationTest.java b/spring-rest/src/test/java/org/baeldung/resttemplate/RestTemplateIntegrationTest.java new file mode 100644 index 0000000000..e0c24c32b1 --- /dev/null +++ b/spring-rest/src/test/java/org/baeldung/resttemplate/RestTemplateIntegrationTest.java @@ -0,0 +1,43 @@ +package org.baeldung.resttemplate; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import org.baeldung.config.RestClientConfig; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.client.RestTemplate; + +import com.baeldung.transfer.LoginForm; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = RestClientConfig.class) +public class RestTemplateIntegrationTest { + + @Autowired + RestTemplate restTemplate; + + @Test + public void givenRestTemplate_whenRequested_thenLogAndModifyResponse() { + LoginForm loginForm = new LoginForm("userName", "password"); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity requestEntity = new HttpEntity(loginForm, headers); + + ResponseEntity responseEntity = restTemplate.postForEntity("http://httpbin.org/post", requestEntity, String.class); + + assertThat(responseEntity.getStatusCode(), is(equalTo(HttpStatus.OK))); + assertThat(responseEntity.getHeaders() + .get("Foo") + .get(0), is(equalTo("bar"))); + } +} diff --git a/spring-security-acl/pom.xml b/spring-security-acl/pom.xml index 7ddbf66365..88502bd268 100644 --- a/spring-security-acl/pom.xml +++ b/spring-security-acl/pom.xml @@ -11,10 +11,10 @@ Spring Security ACL - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-security-cache-control/pom.xml b/spring-security-cache-control/pom.xml index 890ff5bd3f..85b8b5a203 100644 --- a/spring-security-cache-control/pom.xml +++ b/spring-security-cache-control/pom.xml @@ -8,10 +8,10 @@ 1.0-SNAPSHOT - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-security-client/spring-security-jsp-authentication/pom.xml b/spring-security-client/spring-security-jsp-authentication/pom.xml index 9b1ebc6fdc..637fd3dbdb 100644 --- a/spring-security-client/spring-security-jsp-authentication/pom.xml +++ b/spring-security-client/spring-security-jsp-authentication/pom.xml @@ -12,10 +12,10 @@ Spring Security JSP Authentication tag sample - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-security-client/spring-security-jsp-authorize/pom.xml b/spring-security-client/spring-security-jsp-authorize/pom.xml index ee8c9bacbd..94f70ed5f0 100644 --- a/spring-security-client/spring-security-jsp-authorize/pom.xml +++ b/spring-security-client/spring-security-jsp-authorize/pom.xml @@ -12,10 +12,10 @@ Spring Security JSP Authorize tag sample - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-security-client/spring-security-jsp-config/pom.xml b/spring-security-client/spring-security-jsp-config/pom.xml index 0ec72c3527..54dc2fe947 100644 --- a/spring-security-client/spring-security-jsp-config/pom.xml +++ b/spring-security-client/spring-security-jsp-config/pom.xml @@ -12,10 +12,10 @@ Spring Security JSP configuration - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-security-client/spring-security-mvc/pom.xml b/spring-security-client/spring-security-mvc/pom.xml index a6c3065cc8..5064aec7e8 100644 --- a/spring-security-client/spring-security-mvc/pom.xml +++ b/spring-security-client/spring-security-mvc/pom.xml @@ -12,10 +12,10 @@ Spring Security MVC - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml index 345daa9570..7bea8124e7 100644 --- a/spring-security-client/spring-security-thymeleaf-authentication/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-authentication/pom.xml @@ -12,10 +12,10 @@ Spring Security thymeleaf authentication tag sample - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-security-client/spring-security-thymeleaf-authorize/pom.xml b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml index 3e66e9f613..b03464877a 100644 --- a/spring-security-client/spring-security-thymeleaf-authorize/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-authorize/pom.xml @@ -12,10 +12,10 @@ Spring Security thymeleaf authorize tag sample - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-security-client/spring-security-thymeleaf-config/pom.xml b/spring-security-client/spring-security-thymeleaf-config/pom.xml index f5d4306754..3abe9d8c8b 100644 --- a/spring-security-client/spring-security-thymeleaf-config/pom.xml +++ b/spring-security-client/spring-security-thymeleaf-config/pom.xml @@ -12,10 +12,10 @@ Spring Security thymeleaf configuration sample project - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-5 + ../../parent-boot-1 diff --git a/spring-security-core/pom.xml b/spring-security-core/pom.xml index 27c6741790..a11743d9fa 100644 --- a/spring-security-core/pom.xml +++ b/spring-security-core/pom.xml @@ -9,10 +9,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-security-mvc-boot/pom.xml b/spring-security-mvc-boot/pom.xml index bbc701313a..3b1796b978 100644 --- a/spring-security-mvc-boot/pom.xml +++ b/spring-security-mvc-boot/pom.xml @@ -12,10 +12,10 @@ Spring Security MVC Boot - parent-boot-5 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-2 @@ -79,26 +79,6 @@ test - - org.apache.derby - derby - ${derby.version} - - - org.apache.derby - derbyclient - ${derby.version} - - - org.apache.derby - derbynet - ${derby.version} - - - org.apache.derby - derbytools - ${derby.version} - taglibs standard @@ -107,13 +87,11 @@ org.springframework.security spring-security-taglibs - ${spring-security-taglibs.version} org.springframework.security spring-security-core - ${spring-security-core.version} @@ -122,10 +100,6 @@ ${jstl.version} - - org.springframework.security - spring-security-acl - org.springframework.security spring-security-config @@ -237,6 +211,7 @@ **/*LiveTest.java **/*IntegrationTest.java + **/*IntTest.java **/*EntryPointsTest.java @@ -268,12 +243,7 @@ comment the tag above and uncomment the one below --> - 10.13.1.1 1.1.2 - 4.2.2.RELEASE - 4.2.2.RELEASE - 4.2.2.RELEASE - 1.2 1.6.1 diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/Application.java b/spring-security-mvc-boot/src/main/java/org/baeldung/Application.java deleted file mode 100644 index 8a40744bdc..0000000000 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/Application.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.baeldung; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.web.support.SpringBootServletInitializer; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@EnableAutoConfiguration -@ComponentScan({ "org.baeldung.config", "org.baeldung.persistence", "org.baeldung.security", "org.baeldung.web" }) -// @ComponentScan(excludeFilters = { @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.voter.*"), @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.multipleauthproviders.*"), -// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.multiplelogin.*"), @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.multipleentrypoints.*"), -// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.rolesauthorities.*"), @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.acl.*") }) -public class Application extends SpringBootServletInitializer { - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } -} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/ACLContext.java b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/ACLContext.java deleted file mode 100644 index 63a4ea58ef..0000000000 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/ACLContext.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.baeldung.acl.config; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.cache.ehcache.EhCacheFactoryBean; -import org.springframework.cache.ehcache.EhCacheManagerFactoryBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; -import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; -import org.springframework.security.acls.AclPermissionCacheOptimizer; -import org.springframework.security.acls.AclPermissionEvaluator; -import org.springframework.security.acls.domain.AclAuthorizationStrategy; -import org.springframework.security.acls.domain.AclAuthorizationStrategyImpl; -import org.springframework.security.acls.domain.ConsoleAuditLogger; -import org.springframework.security.acls.domain.DefaultPermissionGrantingStrategy; -import org.springframework.security.acls.domain.EhCacheBasedAclCache; -import org.springframework.security.acls.jdbc.BasicLookupStrategy; -import org.springframework.security.acls.jdbc.JdbcMutableAclService; -import org.springframework.security.acls.jdbc.LookupStrategy; -import org.springframework.security.acls.model.PermissionGrantingStrategy; -import org.springframework.security.core.authority.SimpleGrantedAuthority; - -@Configuration -@EnableAutoConfiguration -public class ACLContext { - - @Autowired - DataSource dataSource; - - @Bean - public EhCacheBasedAclCache aclCache() { - return new EhCacheBasedAclCache(aclEhCacheFactoryBean().getObject(), permissionGrantingStrategy(), aclAuthorizationStrategy()); - } - - @Bean - public EhCacheFactoryBean aclEhCacheFactoryBean() { - EhCacheFactoryBean ehCacheFactoryBean = new EhCacheFactoryBean(); - ehCacheFactoryBean.setCacheManager(aclCacheManager().getObject()); - ehCacheFactoryBean.setCacheName("aclCache"); - return ehCacheFactoryBean; - } - - @Bean - public EhCacheManagerFactoryBean aclCacheManager() { - return new EhCacheManagerFactoryBean(); - } - - @Bean - public PermissionGrantingStrategy permissionGrantingStrategy() { - return new DefaultPermissionGrantingStrategy(new ConsoleAuditLogger()); - } - - @Bean - public AclAuthorizationStrategy aclAuthorizationStrategy() { - return new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_ADMIN")); - } - - @Bean - public MethodSecurityExpressionHandler defaultMethodSecurityExpressionHandler() { - DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler(); - AclPermissionEvaluator permissionEvaluator = new AclPermissionEvaluator(aclService()); - expressionHandler.setPermissionEvaluator(permissionEvaluator); - expressionHandler.setPermissionCacheOptimizer(new AclPermissionCacheOptimizer(aclService())); - return expressionHandler; - } - - @Bean - public LookupStrategy lookupStrategy() { - return new BasicLookupStrategy(dataSource, aclCache(), aclAuthorizationStrategy(), new ConsoleAuditLogger()); - } - - @Bean - public JdbcMutableAclService aclService() { - return new JdbcMutableAclService(dataSource, lookupStrategy(), aclCache()); - } - -} \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/AclMethodSecurityConfiguration.java b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/AclMethodSecurityConfiguration.java deleted file mode 100644 index 110c4a6d24..0000000000 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/AclMethodSecurityConfiguration.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.acl.config; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; - -@Configuration -@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) -public class AclMethodSecurityConfiguration extends GlobalMethodSecurityConfiguration { - - @Autowired - MethodSecurityExpressionHandler defaultMethodSecurityExpressionHandler; - - @Override - protected MethodSecurityExpressionHandler createExpressionHandler() { - return defaultMethodSecurityExpressionHandler; - } - -} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/JPAPersistenceConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/JPAPersistenceConfig.java deleted file mode 100644 index 9b87efa92c..0000000000 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/config/JPAPersistenceConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.acl.config; - -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -@Configuration -@EnableTransactionManagement -@EnableJpaRepositories(basePackages = "org.baeldung.acl.persistence.dao") -@PropertySource("classpath:org.baeldung.acl.datasource.properties") -@EntityScan(basePackages={ "org.baeldung.acl.persistence.entity" }) -public class JPAPersistenceConfig { - -} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/persistence/dao/NoticeMessageRepository.java b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/persistence/dao/NoticeMessageRepository.java deleted file mode 100644 index 8662c88d6c..0000000000 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/persistence/dao/NoticeMessageRepository.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.baeldung.acl.persistence.dao; - -import java.util.List; - -import org.baeldung.acl.persistence.entity.NoticeMessage; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.repository.query.Param; -import org.springframework.security.access.prepost.PostAuthorize; -import org.springframework.security.access.prepost.PostFilter; -import org.springframework.security.access.prepost.PreAuthorize; - -public interface NoticeMessageRepository extends JpaRepository{ - - @PostFilter("hasPermission(filterObject, 'READ')") - List findAll(); - - @PostAuthorize("hasPermission(returnObject, 'READ')") - NoticeMessage findById(Integer id); - - @SuppressWarnings("unchecked") - @PreAuthorize("hasPermission(#noticeMessage, 'WRITE')") - NoticeMessage save(@Param("noticeMessage")NoticeMessage noticeMessage); - -} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/persistence/entity/NoticeMessage.java b/spring-security-mvc-boot/src/main/java/org/baeldung/acl/persistence/entity/NoticeMessage.java deleted file mode 100644 index 23f01a8edb..0000000000 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/acl/persistence/entity/NoticeMessage.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.baeldung.acl.persistence.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name="system_message") -public class NoticeMessage { - - @Id - @Column - private Integer id; - @Column - private String content; - public Integer getId() { - return id; - } - public void setId(Integer id) { - this.id = id; - } - public String getContent() { - return content; - } - public void setContent(String content) { - this.content = content; - } -} \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/config/PersistenceConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/config/PersistenceConfig.java deleted file mode 100644 index 1c4cb0124a..0000000000 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/config/PersistenceConfig.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.baeldung.config; - -import java.util.Properties; - -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -@Configuration -@EnableTransactionManagement -@PropertySource({ "classpath:persistence-derby.properties" }) -@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao") -public class PersistenceConfig { - - @Autowired - private Environment env; - - public PersistenceConfig() { - super(); - } - - // beans - - @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); - - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - em.setJpaProperties(additionalProperties()); - - return em; - } - - @Bean - public DataSource dataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); - dataSource.setUrl(env.getProperty("jdbc.url")); - dataSource.setUsername(env.getProperty("jdbc.user")); - dataSource.setPassword(env.getProperty("jdbc.pass")); - - return dataSource; - } - - @Bean - public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(emf); - return transactionManager; - } - - @Bean - public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { - return new PersistenceExceptionTranslationPostProcessor(); - } - - final Properties additionalProperties() { - final Properties hibernateProperties = new Properties(); - hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); - hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); - // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); - return hibernateProperties; - } -} \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/custom/Application.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/Application.java new file mode 100644 index 0000000000..f932ac3066 --- /dev/null +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/Application.java @@ -0,0 +1,16 @@ +package org.baeldung.custom; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/config/MethodSecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java similarity index 84% rename from spring-security-mvc-boot/src/main/java/org/baeldung/config/MethodSecurityConfig.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java index c4624e85e0..6a005153dc 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/config/MethodSecurityConfig.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java @@ -1,7 +1,7 @@ -package org.baeldung.config; +package org.baeldung.custom.config; -import org.baeldung.security.CustomMethodSecurityExpressionHandler; -import org.baeldung.security.CustomPermissionEvaluator; +import org.baeldung.custom.security.CustomMethodSecurityExpressionHandler; +import org.baeldung.custom.security.CustomPermissionEvaluator; import org.springframework.context.annotation.Configuration; import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/config/MvcConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MvcConfig.java similarity index 90% rename from spring-security-mvc-boot/src/main/java/org/baeldung/config/MvcConfig.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MvcConfig.java index 9ade60e54c..58d11ea9ae 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/config/MvcConfig.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MvcConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package org.baeldung.custom.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -7,11 +7,11 @@ import org.springframework.web.servlet.config.annotation.DefaultServletHandlerCo import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc -public class MvcConfig extends WebMvcConfigurerAdapter { +public class MvcConfig implements WebMvcConfigurer { public MvcConfig() { super(); @@ -30,7 +30,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); registry.addViewController("/").setViewName("forward:/index"); registry.addViewController("/index"); } diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/config/SecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java similarity index 96% rename from spring-security-mvc-boot/src/main/java/org/baeldung/config/SecurityConfig.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java index acb7e6820a..f2da5af92c 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/config/SecurityConfig.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java @@ -1,6 +1,6 @@ -package org.baeldung.config; +package org.baeldung.custom.config; -import org.baeldung.security.MyUserDetailsService; +import org.baeldung.custom.security.MyUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/persistence/SetupData.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/SetupData.java similarity index 84% rename from spring-security-mvc-boot/src/main/java/org/baeldung/persistence/SetupData.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/SetupData.java index 2cc86167e2..f0fcce3908 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/persistence/SetupData.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/SetupData.java @@ -1,16 +1,16 @@ -package org.baeldung.persistence; +package org.baeldung.custom.persistence; import java.util.Arrays; import java.util.HashSet; import javax.annotation.PostConstruct; -import org.baeldung.persistence.dao.OrganizationRepository; -import org.baeldung.persistence.dao.PrivilegeRepository; -import org.baeldung.persistence.dao.UserRepository; -import org.baeldung.persistence.model.Organization; -import org.baeldung.persistence.model.Privilege; -import org.baeldung.persistence.model.User; +import org.baeldung.custom.persistence.dao.OrganizationRepository; +import org.baeldung.custom.persistence.dao.PrivilegeRepository; +import org.baeldung.custom.persistence.dao.UserRepository; +import org.baeldung.custom.persistence.model.Organization; +import org.baeldung.custom.persistence.model.Privilege; +import org.baeldung.custom.persistence.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/persistence/dao/OrganizationRepository.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java similarity index 65% rename from spring-security-mvc-boot/src/main/java/org/baeldung/persistence/dao/OrganizationRepository.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java index a20d24057b..1319a7b9f8 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/persistence/dao/OrganizationRepository.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.persistence.dao; +package org.baeldung.custom.persistence.dao; -import org.baeldung.persistence.model.Organization; +import org.baeldung.custom.persistence.model.Organization; import org.springframework.data.jpa.repository.JpaRepository; public interface OrganizationRepository extends JpaRepository { diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/persistence/dao/PrivilegeRepository.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java similarity index 65% rename from spring-security-mvc-boot/src/main/java/org/baeldung/persistence/dao/PrivilegeRepository.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java index edf9002c3d..c232bb986c 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/persistence/dao/PrivilegeRepository.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.persistence.dao; +package org.baeldung.custom.persistence.dao; -import org.baeldung.persistence.model.Privilege; +import org.baeldung.custom.persistence.model.Privilege; import org.springframework.data.jpa.repository.JpaRepository; public interface PrivilegeRepository extends JpaRepository { diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/persistence/dao/UserRepository.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java similarity index 76% rename from spring-security-mvc-boot/src/main/java/org/baeldung/persistence/dao/UserRepository.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java index 337106a187..68dd1d756c 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/persistence/dao/UserRepository.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java @@ -1,6 +1,6 @@ -package org.baeldung.persistence.dao; +package org.baeldung.custom.persistence.dao; -import org.baeldung.persistence.model.User; +import org.baeldung.custom.persistence.model.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.transaction.annotation.Transactional; diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/persistence/model/Foo.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Foo.java similarity index 97% rename from spring-security-mvc-boot/src/main/java/org/baeldung/persistence/model/Foo.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Foo.java index 29c19cf22e..f139382eea 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/persistence/model/Foo.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.model; +package org.baeldung.custom.persistence.model; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/persistence/model/Organization.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Organization.java similarity index 97% rename from spring-security-mvc-boot/src/main/java/org/baeldung/persistence/model/Organization.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Organization.java index 645285b5e9..1fdb88e320 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/persistence/model/Organization.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Organization.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.model; +package org.baeldung.custom.persistence.model; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/persistence/model/Privilege.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Privilege.java similarity index 97% rename from spring-security-mvc-boot/src/main/java/org/baeldung/persistence/model/Privilege.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Privilege.java index ff3ae62c25..ed3edd5085 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/persistence/model/Privilege.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Privilege.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.model; +package org.baeldung.custom.persistence.model; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/persistence/model/User.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/User.java similarity index 98% rename from spring-security-mvc-boot/src/main/java/org/baeldung/persistence/model/User.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/User.java index 2ff8beebf0..c14ef034b4 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/persistence/model/User.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/User.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.model; +package org.baeldung.custom.persistence.model; import java.util.Set; diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionHandler.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java similarity index 97% rename from spring-security-mvc-boot/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionHandler.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java index e040a0b109..646f5a387f 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionHandler.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package org.baeldung.custom.security; import org.aopalliance.intercept.MethodInvocation; import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java similarity index 93% rename from spring-security-mvc-boot/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java index 2d84536a14..b2f2be8cf5 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/security/CustomMethodSecurityExpressionRoot.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java @@ -1,6 +1,6 @@ -package org.baeldung.security; +package org.baeldung.custom.security; -import org.baeldung.persistence.model.User; +import org.baeldung.custom.persistence.model.User; import org.springframework.security.access.expression.SecurityExpressionRoot; import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; import org.springframework.security.core.Authentication; diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java similarity index 97% rename from spring-security-mvc-boot/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java index 5d96673a8f..f436b4488b 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/security/CustomPermissionEvaluator.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package org.baeldung.custom.security; import java.io.Serializable; diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java similarity index 98% rename from spring-security-mvc-boot/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java index 4d3561b325..03d18cb755 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/security/MySecurityExpressionRoot.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java @@ -1,11 +1,11 @@ -package org.baeldung.security; +package org.baeldung.custom.security; import java.io.Serializable; import java.util.Collection; import java.util.HashSet; import java.util.Set; -import org.baeldung.persistence.model.User; +import org.baeldung.custom.persistence.model.User; import org.springframework.security.access.PermissionEvaluator; import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; import org.springframework.security.access.hierarchicalroles.RoleHierarchy; diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java similarity index 84% rename from spring-security-mvc-boot/src/main/java/org/baeldung/security/MyUserDetailsService.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java index 685219728f..b9b40fbcb9 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/security/MyUserDetailsService.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java @@ -1,7 +1,7 @@ -package org.baeldung.security; +package org.baeldung.custom.security; -import org.baeldung.persistence.dao.UserRepository; -import org.baeldung.persistence.model.User; +import org.baeldung.custom.persistence.dao.UserRepository; +import org.baeldung.custom.persistence.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/security/MyUserPrincipal.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java similarity index 90% rename from spring-security-mvc-boot/src/main/java/org/baeldung/security/MyUserPrincipal.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java index 437bb02cdb..7d57227316 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/security/MyUserPrincipal.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java @@ -1,11 +1,11 @@ -package org.baeldung.security; +package org.baeldung.custom.security; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.baeldung.persistence.model.Privilege; -import org.baeldung.persistence.model.User; +import org.baeldung.custom.persistence.model.Privilege; +import org.baeldung.custom.persistence.model.User; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/web/MainController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java similarity index 86% rename from spring-security-mvc-boot/src/main/java/org/baeldung/web/MainController.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java index 4752f7bdd9..6572954427 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/web/MainController.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java @@ -1,8 +1,8 @@ -package org.baeldung.web; +package org.baeldung.custom.web; -import org.baeldung.persistence.dao.OrganizationRepository; -import org.baeldung.persistence.model.Foo; -import org.baeldung.persistence.model.Organization; +import org.baeldung.custom.persistence.dao.OrganizationRepository; +import org.baeldung.custom.persistence.model.Foo; +import org.baeldung.custom.persistence.model.Organization; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; @@ -52,7 +52,7 @@ public class MainController { @RequestMapping(method = RequestMethod.GET, value = "/organizations/{id}") @ResponseBody public Organization findOrgById(@PathVariable final long id) { - return organizationRepository.findOne(id); + return organizationRepository.findById(id).orElse(null); } } diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java index 80573c1c7d..b63169bb00 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java @@ -1,12 +1,12 @@ package org.baeldung.multipleauthproviders; -import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MultipleAuthController { - @RequestMapping("/api/ping") + @GetMapping("/api/ping") public String getPing() { return "OK"; } diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java index 432cc61e87..3819e981a2 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java @@ -1,10 +1,13 @@ package org.baeldung.multipleauthproviders; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; @EnableWebSecurity public class MultipleAuthProvidersSecurityConfig extends WebSecurityConfigurerAdapter { @@ -19,7 +22,7 @@ public class MultipleAuthProvidersSecurityConfig extends WebSecurityConfigurerAd auth.inMemoryAuthentication() .withUser("memuser") - .password("pass") + .password(passwordEncoder().encode("pass")) .roles("USER"); } @@ -31,4 +34,9 @@ public class MultipleAuthProvidersSecurityConfig extends WebSecurityConfigurerAd .antMatchers("/api/**") .authenticated(); } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } } diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java index 9f2eba0a2e..dc89c83cde 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java @@ -8,6 +8,8 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; @@ -21,10 +23,15 @@ public class MultipleEntryPointsSecurityConfig { @Bean public UserDetailsService userDetailsService() throws Exception { InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); - manager.createUser(User.withUsername("user").password("userPass").roles("USER").build()); - manager.createUser(User.withUsername("admin").password("adminPass").roles("ADMIN").build()); + manager.createUser(User.withUsername("user").password(encoder().encode("userPass")).roles("USER").build()); + manager.createUser(User.withUsername("admin").password(encoder().encode("adminPass")).roles("ADMIN").build()); return manager; } + + @Bean + public PasswordEncoder encoder() { + return new BCryptPasswordEncoder(); + } @Configuration @Order(1) diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java index ec76be1909..204b186411 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java @@ -5,6 +5,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @@ -13,7 +14,7 @@ import org.springframework.context.annotation.ComponentScan; @EnableWebMvc @Configuration @ComponentScan("org.baeldung.controller") -public class MultipleLoginMvcConfig extends WebMvcConfigurerAdapter { +public class MultipleLoginMvcConfig implements WebMvcConfigurer { public MultipleLoginMvcConfig() { super(); @@ -23,8 +24,6 @@ public class MultipleLoginMvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/anonymous.html"); registry.addViewController("/login.html"); diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java index 8327e7e5d3..9962bf41a9 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java @@ -1,17 +1,16 @@ package org.baeldung.multiplelogin; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; -import org.springframework.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.TestingAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration @@ -21,10 +20,15 @@ public class MultipleLoginSecurityConfig { @Bean public UserDetailsService userDetailsService() throws Exception { InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); - manager.createUser(User.withUsername("user").password("userPass").roles("USER").build()); - manager.createUser(User.withUsername("admin").password("adminPass").roles("ADMIN").build()); + manager.createUser(User.withUsername("user").password(encoder().encode("userPass")).roles("USER").build()); + manager.createUser(User.withUsername("admin").password(encoder().encode("adminPass")).roles("ADMIN").build()); return manager; } + + @Bean + public static PasswordEncoder encoder() { + return new BCryptPasswordEncoder(); + } @Configuration @Order(1) @@ -36,7 +40,7 @@ public class MultipleLoginSecurityConfig { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN"); + auth.inMemoryAuthentication().withUser("admin").password(encoder().encode("admin")).roles("ADMIN"); } @Override @@ -59,7 +63,7 @@ public class MultipleLoginSecurityConfig { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("user").password("user").roles("USER"); + auth.inMemoryAuthentication().withUser("user").password(encoder().encode("user")).roles("USER"); } protected void configure(HttpSecurity http) throws Exception { diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/UsersController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/UsersController.java index 0672a760af..61d7da127c 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/UsersController.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/UsersController.java @@ -1,37 +1,37 @@ package org.baeldung.multiplelogin; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.GetMapping; @Controller public class UsersController { - @RequestMapping("/protectedLinks") + @GetMapping("/protectedLinks") public String getAnonymousPage() { return "protectedLinks"; } - @RequestMapping("/userPage") + @GetMapping("/userPage") public String getUserPage() { return "userPage"; } - @RequestMapping("/adminPage") + @GetMapping("/adminPage") public String getAdminPage() { return "adminPage"; } - @RequestMapping("/loginAdmin") + @GetMapping("/loginAdmin") public String getAdminLoginPage() { return "loginAdmin"; } - @RequestMapping("/loginUser") + @GetMapping("/loginUser") public String getUserLoginPage() { return "loginUser"; } - @RequestMapping("/403") + @GetMapping("/403") public String getAccessDeniedPage() { return "403"; } diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java index 1c55c145b3..3c4e6f7b5a 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java @@ -2,7 +2,7 @@ package org.baeldung.rolesauthorities; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java index d2edfed749..c42958457e 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java @@ -7,11 +7,11 @@ import org.springframework.web.servlet.config.annotation.DefaultServletHandlerCo import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc -public class MvcConfig extends WebMvcConfigurerAdapter { +public class MvcConfig implements WebMvcConfigurer { public MvcConfig() { super(); @@ -30,7 +30,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); registry.addViewController("/").setViewName("forward:/home"); registry.addViewController("/protectedbynothing").setViewName("rolesauthorities/protectedbynothing"); registry.addViewController("/protectedbyrole").setViewName("rolesauthorities/protectedbyrole"); diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PersistenceJPAConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PersistenceJPAConfig.java deleted file mode 100644 index a993e41a83..0000000000 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PersistenceJPAConfig.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.baeldung.rolesauthorities.persistence; - -import java.util.Properties; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -@Configuration -@EnableTransactionManagement -@PropertySource({ "classpath:persistence.properties" }) -@ComponentScan({ "org.baeldung.rolesauthorities.persistence" }) -@EnableJpaRepositories(basePackages = "org.baeldung.rolesauthorities.persistence") -public class PersistenceJPAConfig { - - @Autowired - private Environment env; - - public PersistenceJPAConfig() { - super(); - } - - // - - @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.rolesauthorities" }); - HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - em.setJpaProperties(additionalProperties()); - return em; - } - - @Bean - public DataSource dataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); - dataSource.setUrl(env.getProperty("jdbc.url")); - dataSource.setUsername(env.getProperty("jdbc.user")); - dataSource.setPassword(env.getProperty("jdbc.pass")); - return dataSource; - } - - @Bean - public JpaTransactionManager transactionManager() { - JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); - return transactionManager; - } - - @Bean - public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { - return new PersistenceExceptionTranslationPostProcessor(); - } - - protected Properties additionalProperties() { - Properties hibernateProperties = new Properties(); - hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - return hibernateProperties; - } - -} diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterMvcConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterMvcConfig.java index e282c794d0..8f41153f06 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterMvcConfig.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterMvcConfig.java @@ -3,6 +3,7 @@ package org.baeldung.voter; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** @@ -10,7 +11,7 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter */ @Configuration -public class VoterMvcConfig extends WebMvcConfigurerAdapter { +public class VoterMvcConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("private"); diff --git a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/WebSecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/voter/WebSecurityConfig.java index 06fb4d2316..84ed070e8e 100644 --- a/spring-security-mvc-boot/src/main/java/org/baeldung/voter/WebSecurityConfig.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/voter/WebSecurityConfig.java @@ -12,6 +12,8 @@ import org.springframework.security.config.annotation.authentication.builders.Au import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.access.expression.WebExpressionVoter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @@ -24,7 +26,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { // @formatter: off - auth.inMemoryAuthentication().withUser("user").password("pass").roles("USER").and().withUser("admin").password("pass").roles("ADMIN"); + auth.inMemoryAuthentication().withUser("user").password(passwordEncoder().encode("pass")).roles("USER").and().withUser("admin").password(passwordEncoder().encode("pass")).roles("ADMIN"); // @formatter: on } @@ -45,4 +47,9 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { // @formatter: on return new UnanimousBased(decisionVoters); } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } } diff --git a/spring-security-mvc-boot/src/main/resources/acl-data.sql b/spring-security-mvc-boot/src/main/resources/acl-data.sql deleted file mode 100644 index 6c01eaacc2..0000000000 --- a/spring-security-mvc-boot/src/main/resources/acl-data.sql +++ /dev/null @@ -1,28 +0,0 @@ -INSERT INTO system_message(id,content) VALUES (1,'First Level Message'); -INSERT INTO system_message(id,content) VALUES (2,'Second Level Message'); -INSERT INTO system_message(id,content) VALUES (3,'Third Level Message'); - -INSERT INTO acl_class (id, class) VALUES -(1, 'org.baeldung.acl.persistence.entity.NoticeMessage'); - -INSERT INTO acl_sid (id, principal, sid) VALUES -(1, 1, 'manager'), -(2, 1, 'hr'), -(3, 1, 'admin'), -(4, 0, 'ROLE_EDITOR'); - -INSERT INTO acl_object_identity (id, object_id_class, object_id_identity, parent_object, owner_sid, entries_inheriting) VALUES -(1, 1, 1, NULL, 3, 0), -(2, 1, 2, NULL, 3, 0), -(3, 1, 3, NULL, 3, 0) -; - -INSERT INTO acl_entry (id, acl_object_identity, ace_order, sid, mask, granting, audit_success, audit_failure) VALUES -(1, 1, 1, 1, 1, 1, 1, 1), -(2, 1, 2, 1, 2, 1, 1, 1), -(3, 1, 3, 4, 1, 1, 1, 1), -(4, 2, 1, 2, 1, 1, 1, 1), -(5, 2, 2, 4, 1, 1, 1, 1), -(6, 3, 1, 4, 1, 1, 1, 1), -(7, 3, 2, 4, 2, 1, 1, 1) -; \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/acl-schema.sql b/spring-security-mvc-boot/src/main/resources/acl-schema.sql deleted file mode 100644 index 58e9394b2b..0000000000 --- a/spring-security-mvc-boot/src/main/resources/acl-schema.sql +++ /dev/null @@ -1,58 +0,0 @@ -create table system_message (id integer not null, content varchar(255), primary key (id)); - -CREATE TABLE IF NOT EXISTS acl_sid ( - id bigint(20) NOT NULL AUTO_INCREMENT, - principal tinyint(1) NOT NULL, - sid varchar(100) NOT NULL, - PRIMARY KEY (id), - UNIQUE KEY unique_uk_1 (sid,principal) -); - -CREATE TABLE IF NOT EXISTS acl_class ( - id bigint(20) NOT NULL AUTO_INCREMENT, - class varchar(255) NOT NULL, - PRIMARY KEY (id), - UNIQUE KEY unique_uk_2 (class) -); - -CREATE TABLE IF NOT EXISTS acl_entry ( - id bigint(20) NOT NULL AUTO_INCREMENT, - acl_object_identity bigint(20) NOT NULL, - ace_order int(11) NOT NULL, - sid bigint(20) NOT NULL, - mask int(11) NOT NULL, - granting tinyint(1) NOT NULL, - audit_success tinyint(1) NOT NULL, - audit_failure tinyint(1) NOT NULL, - PRIMARY KEY (id), - UNIQUE KEY unique_uk_4 (acl_object_identity,ace_order) -); - -CREATE TABLE IF NOT EXISTS acl_object_identity ( - id bigint(20) NOT NULL AUTO_INCREMENT, - object_id_class bigint(20) NOT NULL, - object_id_identity bigint(20) NOT NULL, - parent_object bigint(20) DEFAULT NULL, - owner_sid bigint(20) DEFAULT NULL, - entries_inheriting tinyint(1) NOT NULL, - PRIMARY KEY (id), - UNIQUE KEY unique_uk_3 (object_id_class,object_id_identity) -); - -ALTER TABLE acl_entry -ADD FOREIGN KEY (acl_object_identity) REFERENCES acl_object_identity(id); - -ALTER TABLE acl_entry -ADD FOREIGN KEY (sid) REFERENCES acl_sid(id); - --- --- Constraints for table acl_object_identity --- -ALTER TABLE acl_object_identity -ADD FOREIGN KEY (parent_object) REFERENCES acl_object_identity (id); - -ALTER TABLE acl_object_identity -ADD FOREIGN KEY (object_id_class) REFERENCES acl_class (id); - -ALTER TABLE acl_object_identity -ADD FOREIGN KEY (owner_sid) REFERENCES acl_sid (id); \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/application-rolesauthorities.properties b/spring-security-mvc-boot/src/main/resources/application-rolesauthorities.properties deleted file mode 100644 index 030c79c542..0000000000 --- a/spring-security-mvc-boot/src/main/resources/application-rolesauthorities.properties +++ /dev/null @@ -1,10 +0,0 @@ -server.port=8082 -server.context-path=/ -spring.datasource.driver-class-name=org.h2.Driver -spring.datasource.url=jdbc:h2:mem:security_permission;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE -spring.datasource.username=sa -spring.datasource.password= -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.database=H2 -spring.jpa.show-sql=false -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/application.properties b/spring-security-mvc-boot/src/main/resources/application.properties index d29b5f6bf1..f015086a4f 100644 --- a/spring-security-mvc-boot/src/main/resources/application.properties +++ b/spring-security-mvc-boot/src/main/resources/application.properties @@ -1,5 +1,4 @@ server.port=8082 -server.context-path=/spring-security-mvc-boot spring.datasource.driver-class-name=org.h2.Driver spring.datasource.url=jdbc:h2:mem:security_permission;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE spring.datasource.username=sa diff --git a/spring-security-mvc-boot/src/main/resources/org.baeldung.acl.datasource.properties b/spring-security-mvc-boot/src/main/resources/org.baeldung.acl.datasource.properties deleted file mode 100644 index 739dd3f07c..0000000000 --- a/spring-security-mvc-boot/src/main/resources/org.baeldung.acl.datasource.properties +++ /dev/null @@ -1,12 +0,0 @@ -spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE -spring.datasource.username=sa -spring.datasource.password= -spring.datasource.driverClassName=org.h2.Driver -spring.jpa.hibernate.ddl-auto=update -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect - -spring.h2.console.path=/myconsole -spring.h2.console.enabled=true -spring.datasource.initialize=true -spring.datasource.schema=classpath:acl-schema.sql -spring.datasource.data=classpath:acl-data.sql \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/persistence-derby.properties b/spring-security-mvc-boot/src/main/resources/persistence-derby.properties deleted file mode 100644 index e808fdc288..0000000000 --- a/spring-security-mvc-boot/src/main/resources/persistence-derby.properties +++ /dev/null @@ -1,12 +0,0 @@ -# jdbc.X -jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver -jdbc.url=jdbc:derby:memory:spring_custom_user_service;create=true -jdbc.user=tutorialuser -jdbc.pass=tutorialpass - -# hibernate.X -hibernate.dialect=org.hibernate.dialect.DerbyDialect -hibernate.show_sql=false -hibernate.hbm2ddl.auto=create -hibernate.cache.use_second_level_cache=false -hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/spring-security-mvc-boot/src/main/resources/persistence.properties b/spring-security-mvc-boot/src/main/resources/persistence.properties deleted file mode 100644 index b2255cd479..0000000000 --- a/spring-security-mvc-boot/src/main/resources/persistence.properties +++ /dev/null @@ -1,11 +0,0 @@ -####### H2 -#################### DataSource Configuration ########################## -jdbc.driverClassName=org.h2.Driver -jdbc.url=jdbc:h2:mem:registration_02;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE -jdbc.user=sa -jdbc.pass= -init-db=false -#################### Hibernate Configuration ########################## -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=false -hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextIntegrationTest.java index cf1ac7de89..f01cac1c87 100644 --- a/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,5 +1,6 @@ package org.baeldung; +import org.baeldung.custom.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/acl/SpringAclIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/acl/SpringAclIntegrationTest.java deleted file mode 100644 index 38e1a2a9e7..0000000000 --- a/spring-security-mvc-boot/src/test/java/org/baeldung/acl/SpringAclIntegrationTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package org.baeldung.acl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.util.List; - -import org.baeldung.acl.persistence.dao.NoticeMessageRepository; -import org.baeldung.acl.persistence.entity.NoticeMessage; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.access.AccessDeniedException; -import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestExecutionListeners; -import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; -import org.springframework.test.context.support.DirtiesContextTestExecutionListener; -import org.springframework.test.context.transaction.TransactionalTestExecutionListener; -import org.springframework.test.context.web.ServletTestExecutionListener; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration -@TestExecutionListeners(listeners={ServletTestExecutionListener.class, - DependencyInjectionTestExecutionListener.class, - DirtiesContextTestExecutionListener.class, - TransactionalTestExecutionListener.class, - WithSecurityContextTestExecutionListener.class}) -public class SpringAclIntegrationTest extends AbstractJUnit4SpringContextTests{ - - private static Integer FIRST_MESSAGE_ID = 1; - private static Integer SECOND_MESSAGE_ID = 2; - private static Integer THIRD_MESSAGE_ID = 3; - private static String EDITTED_CONTENT = "EDITED"; - - @Configuration - @ComponentScan("org.baeldung.acl.*") - public static class SpringConfig { - - } - - @Autowired - NoticeMessageRepository repo; - - @Test - @WithMockUser(username="manager") - public void givenUsernameManager_whenFindAllMessage_thenReturnFirstMessage(){ - List details = repo.findAll(); - assertNotNull(details); - assertEquals(1,details.size()); - assertEquals(FIRST_MESSAGE_ID,details.get(0).getId()); - } - - @Test - @WithMockUser(username="manager") - public void givenUsernameManager_whenFindFirstMessageByIdAndUpdateFirstMessageContent_thenOK(){ - NoticeMessage firstMessage = repo.findById(FIRST_MESSAGE_ID); - assertNotNull(firstMessage); - assertEquals(FIRST_MESSAGE_ID,firstMessage.getId()); - - firstMessage.setContent(EDITTED_CONTENT); - repo.save(firstMessage); - - NoticeMessage editedFirstMessage = repo.findById(FIRST_MESSAGE_ID); - assertNotNull(editedFirstMessage); - assertEquals(FIRST_MESSAGE_ID,editedFirstMessage.getId()); - assertEquals(EDITTED_CONTENT,editedFirstMessage.getContent()); - } - - @Test - @WithMockUser(username="hr") - public void givenUsernameHr_whenFindMessageById2_thenOK(){ - NoticeMessage secondMessage = repo.findById(SECOND_MESSAGE_ID); - assertNotNull(secondMessage); - assertEquals(SECOND_MESSAGE_ID,secondMessage.getId()); - } - - @Test(expected=AccessDeniedException.class) - @WithMockUser(username="hr") - public void givenUsernameHr_whenUpdateMessageWithId2_thenFail(){ - NoticeMessage secondMessage = new NoticeMessage(); - secondMessage.setId(SECOND_MESSAGE_ID); - secondMessage.setContent(EDITTED_CONTENT); - repo.save(secondMessage); - } - - @Test - @WithMockUser(roles={"EDITOR"}) - public void givenRoleEditor_whenFindAllMessage_thenReturnThreeMessage(){ - List details = repo.findAll(); - assertNotNull(details); - assertEquals(3,details.size()); - } - - @Test - @WithMockUser(roles={"EDITOR"}) - public void givenRoleEditor_whenUpdateThirdMessage_thenOK(){ - NoticeMessage thirdMessage = new NoticeMessage(); - thirdMessage.setId(THIRD_MESSAGE_ID); - thirdMessage.setContent(EDITTED_CONTENT); - repo.save(thirdMessage); - } - - @Test(expected=AccessDeniedException.class) - @WithMockUser(roles={"EDITOR"}) - public void givenRoleEditor_whenFindFirstMessageByIdAndUpdateFirstMessageContent_thenFail(){ - NoticeMessage firstMessage = repo.findById(FIRST_MESSAGE_ID); - assertNotNull(firstMessage); - assertEquals(FIRST_MESSAGE_ID,firstMessage.getId()); - firstMessage.setContent(EDITTED_CONTENT); - repo.save(firstMessage); - } -} - \ No newline at end of file diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/ApplicationLiveTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/ApplicationLiveTest.java index 371e53070d..dfcfcad609 100644 --- a/spring-security-mvc-boot/src/test/java/org/baeldung/web/ApplicationLiveTest.java +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/web/ApplicationLiveTest.java @@ -2,12 +2,14 @@ package org.baeldung.web; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; + +import org.baeldung.custom.persistence.model.Foo; + import io.restassured.RestAssured; import io.restassured.authentication.FormAuthConfig; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; -import org.baeldung.persistence.model.Foo; import org.junit.Test; import org.springframework.http.MediaType; @@ -16,20 +18,20 @@ public class ApplicationLiveTest { @Test public void givenUserWithReadPrivilegeAndHasPermission_whenGetFooById_thenOK() { - final Response response = givenAuth("john", "123").get("http://localhost:8082/spring-security-mvc-boot/foos/1"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/foos/1"); assertEquals(200, response.getStatusCode()); assertTrue(response.asString().contains("id")); } @Test public void givenUserWithNoWritePrivilegeAndHasPermission_whenPostFoo_thenForbidden() { - final Response response = givenAuth("john", "123").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8082/spring-security-mvc-boot/foos"); + final Response response = givenAuth("john", "123").contentType(MediaType.APPLICATION_JSON_VALUE).body(new Foo("sample")).post("http://localhost:8082/foos"); assertEquals(403, response.getStatusCode()); } @Test public void givenUserWithWritePrivilegeAndHasPermission_whenPostFoo_thenOk() { - final Response response = givenAuth("tom", "111").and().body(new Foo("sample")).and().contentType(MediaType.APPLICATION_JSON_VALUE).post("http://localhost:8082/spring-security-mvc-boot/foos"); + final Response response = givenAuth("tom", "111").and().body(new Foo("sample")).and().contentType(MediaType.APPLICATION_JSON_VALUE).post("http://localhost:8082/foos"); assertEquals(201, response.getStatusCode()); assertTrue(response.asString().contains("id")); } @@ -38,14 +40,14 @@ public class ApplicationLiveTest { @Test public void givenUserMemberInOrganization_whenGetOrganization_thenOK() { - final Response response = givenAuth("john", "123").get("http://localhost:8082/spring-security-mvc-boot/organizations/1"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/organizations/1"); assertEquals(200, response.getStatusCode()); assertTrue(response.asString().contains("id")); } @Test public void givenUserMemberNotInOrganization_whenGetOrganization_thenForbidden() { - final Response response = givenAuth("john", "123").get("http://localhost:8082/spring-security-mvc-boot/organizations/2"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/organizations/2"); assertEquals(403, response.getStatusCode()); } @@ -53,13 +55,13 @@ public class ApplicationLiveTest { @Test public void givenDisabledSecurityExpression_whenGetFooByName_thenError() { - final Response response = givenAuth("john", "123").get("http://localhost:8082/spring-security-mvc-boot/foos?name=sample"); + final Response response = givenAuth("john", "123").get("http://localhost:8082/foos?name=sample"); assertEquals(500, response.getStatusCode()); assertTrue(response.asString().contains("method hasAuthority() not allowed")); } // private RequestSpecification givenAuth(String username, String password) { - return RestAssured.given().log().uri().auth().form(username, password, new FormAuthConfig("/spring-security-mvc-boot/login","username","password")); + return RestAssured.given().log().uri().auth().form(username, password, new FormAuthConfig("/login","username","password")); } } \ No newline at end of file diff --git a/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java index 503354256f..fb25175902 100644 --- a/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java @@ -2,11 +2,11 @@ package org.baeldung.web; import static org.junit.Assert.assertEquals; -import org.baeldung.config.MvcConfig; -import org.baeldung.config.PersistenceConfig; -import org.baeldung.config.SecurityConfig; -import org.baeldung.persistence.dao.UserRepository; -import org.baeldung.persistence.model.User; +import org.baeldung.custom.Application; +import org.baeldung.custom.config.MvcConfig; +import org.baeldung.custom.config.SecurityConfig; +import org.baeldung.custom.persistence.dao.UserRepository; +import org.baeldung.custom.persistence.model.User; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; @@ -21,7 +21,7 @@ import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.boot.test.context.SpringBootTest; @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = {MvcConfig.class, SecurityConfig.class, PersistenceConfig.class}) +@SpringBootTest(classes = {Application.class}) @WebAppConfiguration public class CustomUserDetailsServiceIntegrationTest { diff --git a/spring-security-mvc-custom/pom.xml b/spring-security-mvc-custom/pom.xml index a320f6b137..e50304aa1b 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-5 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-5 @@ -193,27 +193,26 @@ - 4.3.4.RELEASE - 4.2.0.RELEASE + 5.0.6.RELEASE 5.2.5.Final 5.1.40 - 5.3.3.Final + 5.4.1.Final 3.1.0 1.2 19.0 3.5 - 2.9.1 + 2.9.4 4.5.2 4.4.5 - 2.9.0 + 3.0.7 2.6 diff --git a/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MvcConfig.java index 3b97afc22d..db6141d43e 100644 --- a/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-security-mvc-custom/src/main/java/org/baeldung/spring/MvcConfig.java @@ -10,14 +10,14 @@ import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration @ComponentScan("org.baeldung.web.controller") -public class MvcConfig extends WebMvcConfigurerAdapter { +public class MvcConfig implements WebMvcConfigurer { public MvcConfig() { super(); @@ -27,8 +27,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); - registry.addViewController("/anonymous.html"); registry.addViewController("/login.html"); diff --git a/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java index 4da114c78b..e9d5bc4f70 100644 --- a/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-custom/src/main/java/org/baeldung/spring/SecSecurityConfig.java @@ -6,6 +6,8 @@ import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource({ "classpath:webSecurityConfig.xml" }) public class SecSecurityConfig { + + public SecSecurityConfig() { super(); diff --git a/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/LoginController.java b/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/LoginController.java index c67a6f667e..99bf345a41 100644 --- a/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/LoginController.java +++ b/spring-security-mvc-custom/src/main/java/org/baeldung/web/controller/LoginController.java @@ -1,5 +1,6 @@ package org.baeldung.web.controller; +import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; @@ -18,7 +19,7 @@ import org.springframework.web.bind.annotation.RequestParam; @RequestMapping(value = "/custom") public class LoginController { - @Autowired + @Resource(name="authenticationManager") private AuthenticationManager authManager; public LoginController() { diff --git a/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml b/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml index f2ecaba5c8..e79e14abeb 100644 --- a/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml +++ b/spring-security-mvc-custom/src/main/resources/webSecurityConfig.xml @@ -2,9 +2,9 @@ @@ -24,11 +24,11 @@ - + - - + + diff --git a/spring-security-mvc-digest-auth/pom.xml b/spring-security-mvc-digest-auth/pom.xml index 9387220b2a..a0a6a9647e 100644 --- a/spring-security-mvc-digest-auth/pom.xml +++ b/spring-security-mvc-digest-auth/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -35,7 +35,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -46,55 +46,55 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} org.springframework spring-oxm - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} @@ -149,7 +149,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -200,8 +200,7 @@ - 4.3.4.RELEASE - 4.2.0.RELEASE + 4.2.6.RELEASE 5.2.5.Final diff --git a/spring-security-mvc-ldap/pom.xml b/spring-security-mvc-ldap/pom.xml index 286b189d87..6a9aa5eebe 100644 --- a/spring-security-mvc-ldap/pom.xml +++ b/spring-security-mvc-ldap/pom.xml @@ -9,10 +9,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-security-mvc-login/pom.xml b/spring-security-mvc-login/pom.xml index ee11bf067c..6f4bd8c8e0 100644 --- a/spring-security-mvc-login/pom.xml +++ b/spring-security-mvc-login/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -40,7 +40,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -51,43 +51,43 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} @@ -111,7 +111,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -167,8 +167,7 @@ - 4.3.6.RELEASE - 4.2.1.RELEASE + 4.2.6.RELEASE 5.2.5.Final diff --git a/spring-security-mvc-persisted-remember-me/pom.xml b/spring-security-mvc-persisted-remember-me/pom.xml index 5c3ac4b7c4..f8fa4400c9 100644 --- a/spring-security-mvc-persisted-remember-me/pom.xml +++ b/spring-security-mvc-persisted-remember-me/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -37,7 +37,7 @@ org.springframework spring-orm - ${org.springframework.version} + ${spring.version} @@ -45,7 +45,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -56,43 +56,43 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} @@ -189,8 +189,7 @@ - 4.3.4.RELEASE - 4.2.0.RELEASE + 4.2.6.RELEASE 5.2.5.Final diff --git a/spring-security-mvc-session/pom.xml b/spring-security-mvc-session/pom.xml index 130778151f..da0bede349 100644 --- a/spring-security-mvc-session/pom.xml +++ b/spring-security-mvc-session/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -40,7 +40,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -51,43 +51,43 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} @@ -160,8 +160,7 @@ - 4.3.4.RELEASE - 4.2.0.RELEASE + 4.2.6.RELEASE 5.2.5.Final diff --git a/spring-security-mvc-socket/pom.xml b/spring-security-mvc-socket/pom.xml index 6168740cb7..5cd2c080d2 100644 --- a/spring-security-mvc-socket/pom.xml +++ b/spring-security-mvc-socket/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -20,7 +20,7 @@ org.springframework spring-core - ${springframework.version} + ${spring.version} commons-logging @@ -31,7 +31,7 @@ org.springframework spring-web - ${springframework.version} + ${spring.version} commons-logging @@ -42,7 +42,7 @@ org.springframework spring-webmvc - ${springframework.version} + ${spring.version} commons-logging @@ -84,12 +84,12 @@ org.springframework spring-websocket - ${springframework.version} + ${spring.version} org.springframework spring-messaging - ${springframework.version} + ${spring.version} org.springframework.security @@ -174,8 +174,7 @@ - 4.3.8.RELEASE - 4.2.3.RELEASE + 4.2.6.RELEASE 2.8.7 1.7.25 5.2.10.Final diff --git a/spring-security-rest-basic-auth/pom.xml b/spring-security-rest-basic-auth/pom.xml index bed3cd033d..a30b783842 100644 --- a/spring-security-rest-basic-auth/pom.xml +++ b/spring-security-rest-basic-auth/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -35,7 +35,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -46,49 +46,49 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} org.springframework spring-oxm - ${org.springframework.version} + ${spring.version} @@ -166,7 +166,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -271,8 +271,7 @@ - 4.3.6.RELEASE - 4.2.1.RELEASE + 4.2.6.RELEASE 5.2.5.Final diff --git a/spring-security-rest-custom/pom.xml b/spring-security-rest-custom/pom.xml index cfa3ad4b99..1ee324bcdb 100644 --- a/spring-security-rest-custom/pom.xml +++ b/spring-security-rest-custom/pom.xml @@ -9,10 +9,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-security-rest/pom.xml b/spring-security-rest/pom.xml index e29012a3a5..e6721c9fc7 100644 --- a/spring-security-rest/pom.xml +++ b/spring-security-rest/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-4 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-4 @@ -35,7 +35,7 @@ org.springframework spring-core - ${org.springframework.version} + ${spring.version} commons-logging @@ -46,43 +46,43 @@ org.springframework spring-context - ${org.springframework.version} + ${spring.version} org.springframework spring-jdbc - ${org.springframework.version} + ${spring.version} org.springframework spring-beans - ${org.springframework.version} + ${spring.version} org.springframework spring-aop - ${org.springframework.version} + ${spring.version} org.springframework spring-tx - ${org.springframework.version} + ${spring.version} org.springframework spring-expression - ${org.springframework.version} + ${spring.version} org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} @@ -138,7 +138,7 @@ org.springframework spring-test - ${org.springframework.version} + ${spring.version} test @@ -284,8 +284,7 @@ - 4.3.4.RELEASE - 4.2.0.RELEASE + 4.2.6.RELEASE 0.21.0.RELEASE diff --git a/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomerController.java b/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomerController.java index 532e6b4d3a..b8f67960f5 100644 --- a/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomerController.java +++ b/spring-security-rest/src/main/java/org/baeldung/web/controller/CustomerController.java @@ -1,23 +1,27 @@ package org.baeldung.web.controller; +import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; +import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; + +import java.util.List; + import org.baeldung.persistence.model.Customer; import org.baeldung.persistence.model.Order; import org.baeldung.web.service.CustomerService; import org.baeldung.web.service.OrderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Link; +import org.springframework.hateoas.Resources; +import org.springframework.hateoas.config.EnableHypermediaSupport; +import org.springframework.hateoas.config.EnableHypermediaSupport.HypermediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import java.util.List; - -import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; -import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; - @RestController @RequestMapping(value = "/customers") +@EnableHypermediaSupport(type = HypermediaType.HAL) public class CustomerController { @Autowired private CustomerService customerService; @@ -35,31 +39,36 @@ public class CustomerController { return orderService.getOrderByIdForCustomer(customerId, orderId); } - @RequestMapping(value = "/{customerId}/orders", method = RequestMethod.GET) - public List getOrdersForCustomer(@PathVariable final String customerId) { + @RequestMapping(value = "/{customerId}/orders", method = RequestMethod.GET , produces = {"application/hal+json"}) + public Resources getOrdersForCustomer(@PathVariable final String customerId) { final List orders = orderService.getAllOrdersForCustomer(customerId); for (final Order order : orders) { final Link selfLink = linkTo(methodOn(CustomerController.class).getOrderById(customerId, order.getOrderId())).withSelfRel(); order.add(selfLink); } - return orders; + + Link link =linkTo(methodOn(CustomerController.class).getOrdersForCustomer(customerId)).withSelfRel(); + Resources result = new Resources(orders,link); + return result; } - @RequestMapping(method = RequestMethod.GET) - public List getAllCustomers() { + @RequestMapping(method = RequestMethod.GET, produces = {"application/hal+json"}) + public Resources getAllCustomers() { final List allCustomers = customerService.allCustomers(); + for (final Customer customer : allCustomers) { String customerId = customer.getCustomerId(); Link selfLink = linkTo(CustomerController.class).slash(customerId).withSelfRel(); customer.add(selfLink); if (orderService.getAllOrdersForCustomer(customerId).size() > 0) { - List methodLinkBuilder = methodOn(CustomerController.class).getOrdersForCustomer(customerId); - final Link ordersLink = linkTo(methodLinkBuilder).withRel("allOrders"); + final Link ordersLink = linkTo(methodOn(CustomerController.class).getOrdersForCustomer(customerId)).withRel("allOrders"); customer.add(ordersLink); } - } - return allCustomers; + + Link link =linkTo(CustomerController.class).withSelfRel(); + Resources result = new Resources(allCustomers,link); + return result; } } diff --git a/spring-security-rest/src/main/java/org/baeldung/web/service/OrderServiceImpl.java b/spring-security-rest/src/main/java/org/baeldung/web/service/OrderServiceImpl.java index 1b8e7b0dde..0a6d4708a1 100644 --- a/spring-security-rest/src/main/java/org/baeldung/web/service/OrderServiceImpl.java +++ b/spring-security-rest/src/main/java/org/baeldung/web/service/OrderServiceImpl.java @@ -3,6 +3,7 @@ package org.baeldung.web.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; import org.baeldung.persistence.model.Customer; import org.baeldung.persistence.model.Order; @@ -49,16 +50,9 @@ public class OrderServiceImpl implements OrderService { @Override public Order getOrderByIdForCustomer(final String customerId, final String orderId) { - - final List orders = (List) customerMap.get(customerId).getOrders().values(); - Order selectedOrder = null; - for (final Order order : orders) { - if (order.getId().equals(orderId)) { - selectedOrder = order; - } - } + final Map orders = customerMap.get(customerId).getOrders(); + Order selectedOrder = orders.get(orderId); return selectedOrder; - } } diff --git a/spring-security-sso/pom.xml b/spring-security-sso/pom.xml index 938636ff18..f68b9addac 100644 --- a/spring-security-sso/pom.xml +++ b/spring-security-sso/pom.xml @@ -9,10 +9,10 @@ pom - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-security-stormpath/pom.xml b/spring-security-stormpath/pom.xml index 17973165ea..71a7123c2c 100644 --- a/spring-security-stormpath/pom.xml +++ b/spring-security-stormpath/pom.xml @@ -9,10 +9,10 @@ http://maven.apache.org - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-security-thymeleaf/pom.xml b/spring-security-thymeleaf/pom.xml index aa36e5f59a..28d6126b55 100644 --- a/spring-security-thymeleaf/pom.xml +++ b/spring-security-thymeleaf/pom.xml @@ -10,10 +10,10 @@ Spring Security with Thymeleaf tutorial - parent-boot-5 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-2 diff --git a/spring-security-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/SecurityConfiguration.java b/spring-security-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/SecurityConfiguration.java index 687c0c2e39..0a4344db4d 100644 --- a/spring-security-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/SecurityConfiguration.java +++ b/spring-security-thymeleaf/src/main/java/com/baeldung/springsecuritythymeleaf/SecurityConfiguration.java @@ -1,11 +1,13 @@ package com.baeldung.springsecuritythymeleaf; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @@ -33,11 +35,16 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter { public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user") - .password("password") + .password(passwordEncoder().encode("password")) .roles("USER") .and() .withUser("admin") - .password("admin") + .password(passwordEncoder().encode("admin")) .roles("ADMIN"); } + + @Bean + public BCryptPasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } } diff --git a/spring-security-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/SpringSecurityThymeleafApplicationTests.java b/spring-security-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/SpringSecurityThymeleafApplicationIntegrationTest.java similarity index 90% rename from spring-security-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/SpringSecurityThymeleafApplicationTests.java rename to spring-security-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/SpringSecurityThymeleafApplicationIntegrationTest.java index dea254dd31..c852d05e73 100644 --- a/spring-security-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/SpringSecurityThymeleafApplicationTests.java +++ b/spring-security-thymeleaf/src/test/java/com/baeldung/springsecuritythymeleaf/SpringSecurityThymeleafApplicationIntegrationTest.java @@ -11,7 +11,7 @@ import org.springframework.web.context.WebApplicationContext; @RunWith(SpringRunner.class) @SpringBootTest -public class SpringSecurityThymeleafApplicationTests { +public class SpringSecurityThymeleafApplicationIntegrationTest { @Autowired ViewController viewController; diff --git a/spring-security-x509/pom.xml b/spring-security-x509/pom.xml index 89fed39920..d6a4b5693b 100644 --- a/spring-security-x509/pom.xml +++ b/spring-security-x509/pom.xml @@ -9,10 +9,10 @@ pom - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-security-x509/spring-security-x509-basic-auth/pom.xml b/spring-security-x509/spring-security-x509-basic-auth/pom.xml index 67a7e29e6f..56600302e0 100644 --- a/spring-security-x509/spring-security-x509-basic-auth/pom.xml +++ b/spring-security-x509/spring-security-x509-basic-auth/pom.xml @@ -30,6 +30,7 @@ **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java diff --git a/spring-security-x509/spring-security-x509-client-auth/pom.xml b/spring-security-x509/spring-security-x509-client-auth/pom.xml index 7dd919973d..ea5521c93d 100644 --- a/spring-security-x509/spring-security-x509-client-auth/pom.xml +++ b/spring-security-x509/spring-security-x509-client-auth/pom.xml @@ -30,6 +30,7 @@ **/*IntegrationTest.java + **/*IntTest.java **/*LiveTest.java @@ -57,6 +58,7 @@ **/*IntegrationTest.java + **/*IntTest.java diff --git a/spring-session/pom.xml b/spring-session/pom.xml index c1c872ca74..4c256663b0 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -7,10 +7,10 @@ jar - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-sleuth/pom.xml b/spring-sleuth/pom.xml index 2fee474dbe..418edeaec7 100644 --- a/spring-sleuth/pom.xml +++ b/spring-sleuth/pom.xml @@ -8,10 +8,10 @@ jar - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/spring-social-login/pom.xml b/spring-social-login/pom.xml index d2e9497bcf..d08600a8e4 100644 --- a/spring-social-login/pom.xml +++ b/spring-social-login/pom.xml @@ -6,10 +6,10 @@ war - parent-boot-5 + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../parent-boot-5 + ../parent-boot-1 diff --git a/handling-spring-static-resources/README.md b/spring-static-resources/README.md similarity index 100% rename from handling-spring-static-resources/README.md rename to spring-static-resources/README.md diff --git a/handling-spring-static-resources/pom.xml b/spring-static-resources/pom.xml similarity index 85% rename from handling-spring-static-resources/pom.xml rename to spring-static-resources/pom.xml index da8f88ee22..a00d03d2a1 100644 --- a/handling-spring-static-resources/pom.xml +++ b/spring-static-resources/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring + parent-spring-5 0.0.1-SNAPSHOT - ../parent-spring + ../parent-spring-5 @@ -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} @@ -174,7 +174,9 @@ - maven-war-plugin + org.apache.maven.plugins + maven-war-plugin + 3.2.2 @@ -190,21 +192,20 @@ 1.8 - 4.3.4.RELEASE - 4.2.0.RELEASE + 5.0.6.RELEASE 1.8.9 2.3.2-b02 - 2.8.5 + 2.9.6 - 5.3.3.Final - 4.0.6 - 2.9.6 + 6.0.10.Final + 4.1.0 + 2.10 1.2 - 3.1.0 + 4.0.1 1 diff --git a/handling-spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java similarity index 100% rename from handling-spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java rename to spring-static-resources/src/main/java/org/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java diff --git a/handling-spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java b/spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java similarity index 100% rename from handling-spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java rename to spring-static-resources/src/main/java/org/baeldung/spring/AppConfig.java diff --git a/handling-spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java b/spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java similarity index 97% rename from handling-spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java rename to spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java index 4a198cf195..dbc548e028 100644 --- a/handling-spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java +++ b/spring-static-resources/src/main/java/org/baeldung/spring/MvcConfig.java @@ -15,7 +15,7 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.resource.GzipResourceResolver; @@ -27,7 +27,7 @@ import org.springframework.web.servlet.view.JstlView; @Configuration @ComponentScan(basePackages = { "org.baeldung.web.controller", "org.baeldung.persistence.service", "org.baeldung.persistence.dao" }) @EnableWebMvc -public class MvcConfig extends WebMvcConfigurerAdapter { +public class MvcConfig implements WebMvcConfigurer { @Autowired Environment env; @@ -39,7 +39,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); registry.addViewController("/login.html"); registry.addViewController("/home.html"); diff --git a/handling-spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java b/spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java similarity index 100% rename from handling-spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java rename to spring-static-resources/src/main/java/org/baeldung/spring/SecSecurityConfig.java diff --git a/handling-spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java b/spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java similarity index 100% rename from handling-spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java rename to spring-static-resources/src/main/java/org/baeldung/web/controller/HomeController.java diff --git a/handling-spring-static-resources/src/main/resources/application.properties b/spring-static-resources/src/main/resources/application.properties similarity index 100% rename from handling-spring-static-resources/src/main/resources/application.properties rename to spring-static-resources/src/main/resources/application.properties diff --git a/spring-custom-aop/spring-custom-aop/src/main/resources/logback.xml b/spring-static-resources/src/main/resources/logback.xml similarity index 100% rename from spring-custom-aop/spring-custom-aop/src/main/resources/logback.xml rename to spring-static-resources/src/main/resources/logback.xml diff --git a/handling-spring-static-resources/src/main/resources/messages_en.properties b/spring-static-resources/src/main/resources/messages_en.properties similarity index 100% rename from handling-spring-static-resources/src/main/resources/messages_en.properties rename to spring-static-resources/src/main/resources/messages_en.properties diff --git a/handling-spring-static-resources/src/main/resources/messages_es_ES.properties b/spring-static-resources/src/main/resources/messages_es_ES.properties similarity index 100% rename from handling-spring-static-resources/src/main/resources/messages_es_ES.properties rename to spring-static-resources/src/main/resources/messages_es_ES.properties diff --git a/spring-static-resources/src/main/resources/webSecurityConfig.xml b/spring-static-resources/src/main/resources/webSecurityConfig.xml new file mode 100644 index 0000000000..ea64ad5aea --- /dev/null +++ b/spring-static-resources/src/main/resources/webSecurityConfig.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/Hello.html b/spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/Hello.html similarity index 100% rename from handling-spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/Hello.html rename to spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/Hello.html diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/bootstrap.css b/spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/bootstrap.css similarity index 100% rename from handling-spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/bootstrap.css rename to spring-static-resources/src/main/webapp/WEB-INF/classes/other-resources/bootstrap.css diff --git a/spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml b/spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml new file mode 100644 index 0000000000..c046aa16a9 --- /dev/null +++ b/spring-static-resources/src/main/webapp/WEB-INF/mvc-servlet.xml @@ -0,0 +1,9 @@ + + + + + diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/view/home.jsp b/spring-static-resources/src/main/webapp/WEB-INF/view/home.jsp similarity index 100% rename from handling-spring-static-resources/src/main/webapp/WEB-INF/view/home.jsp rename to spring-static-resources/src/main/webapp/WEB-INF/view/home.jsp diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp b/spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp similarity index 100% rename from handling-spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp rename to spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/web.xml b/spring-static-resources/src/main/webapp/WEB-INF/web.xml similarity index 97% rename from handling-spring-static-resources/src/main/webapp/WEB-INF/web.xml rename to spring-static-resources/src/main/webapp/WEB-INF/web.xml index e9d784e940..4bb60e4f2c 100644 --- a/handling-spring-static-resources/src/main/webapp/WEB-INF/web.xml +++ b/spring-static-resources/src/main/webapp/WEB-INF/web.xml @@ -1,6 +1,6 @@ - diff --git a/handling-spring-static-resources/src/main/webapp/js/bootstrap.css b/spring-static-resources/src/main/webapp/js/bootstrap.css similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/bootstrap.css rename to spring-static-resources/src/main/webapp/js/bootstrap.css diff --git a/handling-spring-static-resources/src/main/webapp/js/foo.js b/spring-static-resources/src/main/webapp/js/foo.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/foo.js rename to spring-static-resources/src/main/webapp/js/foo.js diff --git a/handling-spring-static-resources/src/main/webapp/js/handlebars-3133af2.js b/spring-static-resources/src/main/webapp/js/handlebars-3133af2.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/handlebars-3133af2.js rename to spring-static-resources/src/main/webapp/js/handlebars-3133af2.js diff --git a/handling-spring-static-resources/src/main/webapp/js/helpers/utils.js b/spring-static-resources/src/main/webapp/js/helpers/utils.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/helpers/utils.js rename to spring-static-resources/src/main/webapp/js/helpers/utils.js diff --git a/handling-spring-static-resources/src/main/webapp/js/jquery-1.11.1.min.js b/spring-static-resources/src/main/webapp/js/jquery-1.11.1.min.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/jquery-1.11.1.min.js rename to spring-static-resources/src/main/webapp/js/jquery-1.11.1.min.js diff --git a/handling-spring-static-resources/src/main/webapp/js/main.js b/spring-static-resources/src/main/webapp/js/main.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/main.js rename to spring-static-resources/src/main/webapp/js/main.js diff --git a/handling-spring-static-resources/src/main/webapp/js/require.gz b/spring-static-resources/src/main/webapp/js/require.gz similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/require.gz rename to spring-static-resources/src/main/webapp/js/require.gz diff --git a/handling-spring-static-resources/src/main/webapp/js/require.js b/spring-static-resources/src/main/webapp/js/require.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/require.js rename to spring-static-resources/src/main/webapp/js/require.js diff --git a/handling-spring-static-resources/src/main/webapp/js/router.js b/spring-static-resources/src/main/webapp/js/router.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/js/router.js rename to spring-static-resources/src/main/webapp/js/router.js diff --git a/handling-spring-static-resources/src/main/webapp/other-resources/Hello.html b/spring-static-resources/src/main/webapp/other-resources/Hello.html similarity index 100% rename from handling-spring-static-resources/src/main/webapp/other-resources/Hello.html rename to spring-static-resources/src/main/webapp/other-resources/Hello.html diff --git a/handling-spring-static-resources/src/main/webapp/other-resources/bootstrap.css b/spring-static-resources/src/main/webapp/other-resources/bootstrap.css similarity index 100% rename from handling-spring-static-resources/src/main/webapp/other-resources/bootstrap.css rename to spring-static-resources/src/main/webapp/other-resources/bootstrap.css diff --git a/handling-spring-static-resources/src/main/webapp/other-resources/foo.js b/spring-static-resources/src/main/webapp/other-resources/foo.js similarity index 100% rename from handling-spring-static-resources/src/main/webapp/other-resources/foo.js rename to spring-static-resources/src/main/webapp/other-resources/foo.js diff --git a/handling-spring-static-resources/src/main/webapp/resources/bootstrap.css b/spring-static-resources/src/main/webapp/resources/bootstrap.css similarity index 100% rename from handling-spring-static-resources/src/main/webapp/resources/bootstrap.css rename to spring-static-resources/src/main/webapp/resources/bootstrap.css diff --git a/handling-spring-static-resources/src/main/webapp/resources/myCss.css b/spring-static-resources/src/main/webapp/resources/myCss.css similarity index 100% rename from handling-spring-static-resources/src/main/webapp/resources/myCss.css rename to spring-static-resources/src/main/webapp/resources/myCss.css diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiLiveTest.java similarity index 99% rename from spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java rename to spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiLiveTest.java index 0b94027df0..42be6b950b 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiTest.java +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/PetApiLiveTest.java @@ -28,7 +28,7 @@ import java.util.Map; * API tests for PetApi */ @Ignore -public class PetApiTest { +public class PetApiLiveTest { private final PetApi api = new PetApi(); diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiLiveTest.java similarity index 98% rename from spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java rename to spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiLiveTest.java index ce332bee0d..be0cb8030d 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiTest.java +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/StoreApiLiveTest.java @@ -26,7 +26,7 @@ import java.util.Map; * API tests for StoreApi */ @Ignore -public class StoreApiTest { +public class StoreApiLiveTest { private final StoreApi api = new StoreApi(); diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiLiveTest.java similarity index 99% rename from spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java rename to spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiLiveTest.java index 59e7a39679..5dae1430a0 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiTest.java +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/src/test/java/com/baeldung/petstore/client/api/UserApiLiveTest.java @@ -26,7 +26,7 @@ import java.util.Map; * API tests for UserApi */ @Ignore -public class UserApiTest { +public class UserApiLiveTest { private final UserApi api = new UserApi(); diff --git a/spring-thymeleaf/README.md b/spring-thymeleaf/README.md index 9346b74c89..27af6c077a 100644 --- a/spring-thymeleaf/README.md +++ b/spring-thymeleaf/README.md @@ -14,6 +14,7 @@ - [Working with Fragments in Thymeleaf](http://www.baeldung.com/spring-thymeleaf-fragments) - [Conditionals in Thymeleaf](http://www.baeldung.com/spring-thymeleaf-conditionals) - [Iteration in Thymeleaf](http://www.baeldung.com/thymeleaf-iteration) +- [Working With Arrays in Thymeleaf](http://www.baeldung.com/thymeleaf-arrays) ### Build the Project diff --git a/spring-thymeleaf/pom.xml b/spring-thymeleaf/pom.xml index d13356b3d7..6e0b7f6545 100644 --- a/spring-thymeleaf/pom.xml +++ b/spring-thymeleaf/pom.xml @@ -173,4 +173,4 @@ 2.2 - \ No newline at end of file + diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BookController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BookController.java new file mode 100644 index 0000000000..4c69a60b8e --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/BookController.java @@ -0,0 +1,48 @@ +package com.baeldung.thymeleaf.controller; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; + +import com.baeldung.thymeleaf.model.Book; +import com.baeldung.thymeleaf.model.Page; +import com.baeldung.thymeleaf.utils.BookUtils; + +@Controller +public class BookController { + + private static int currentPage = 1; + private static int pageSize = 5; + + @RequestMapping(value = "/listBooks", method = RequestMethod.GET) + public String listBooks(Model model, @RequestParam("page") Optional page, @RequestParam("size") Optional size) { + page.ifPresent(p -> currentPage = p); + size.ifPresent(s -> pageSize = s); + + List books = BookUtils.buildBooks(); + Page bookPage = new Page(books, pageSize, currentPage); + + model.addAttribute("books", bookPage.getList()); + model.addAttribute("selectedPage", bookPage.getCurrentPage()); + model.addAttribute("pageSize", pageSize); + + int totalPages = bookPage.getTotalPages(); + model.addAttribute("totalPages", totalPages); + + if (totalPages > 1) { + List pageNumbers = IntStream.rangeClosed(1, totalPages) + .boxed() + .collect(Collectors.toList()); + model.addAttribute("pageNumbers", pageNumbers); + } + + return "listBooks.html"; + } +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Book.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Book.java new file mode 100644 index 0000000000..0203231175 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Book.java @@ -0,0 +1,29 @@ +package com.baeldung.thymeleaf.model; + +public class Book { + private int id; + private String name; + + public Book(int id, String name) { + super(); + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Page.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Page.java new file mode 100644 index 0000000000..e9dd0a8135 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/model/Page.java @@ -0,0 +1,61 @@ +package com.baeldung.thymeleaf.model; + +import java.util.Collections; +import java.util.List; + +public class Page { + + private List list; + + private int pageSize = 0; + + private int currentPage = 0; + + private int totalPages = 0; + + public Page(List list, int pageSize, int currentPage) { + + if (list.isEmpty()) { + this.list = list; + } + + if (pageSize <= 0 || pageSize > list.size() || currentPage <= 0) { + throw new IllegalArgumentException("invalid page size or current page!"); + } + + this.pageSize = pageSize; + + this.currentPage = currentPage; + + if (list.size() % pageSize == 0) { + this.totalPages = list.size() / pageSize; + } else { + this.totalPages = list.size() / pageSize + 1; + } + + int startItem = (currentPage - 1) * pageSize; + if (list.size() < startItem) { + this.list = Collections.emptyList(); + } + + int toIndex = Math.min(startItem + pageSize, list.size()); + this.list = list.subList(startItem, toIndex); + } + + public List getList() { + return list; + } + + public int getPageSize() { + return pageSize; + } + + public int getCurrentPage() { + return currentPage; + } + + public int getTotalPages() { + return totalPages; + } + +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java new file mode 100644 index 0000000000..3cd9e6a92e --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/BookUtils.java @@ -0,0 +1,28 @@ +package com.baeldung.thymeleaf.utils; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.IntStream; + +import com.baeldung.thymeleaf.model.Book; + +public class BookUtils { + + private static List books = new ArrayList(); + + private static final int NUM_BOOKS = 30; + + private static final int MIN_BOOK_NUM = 1000; + + public static List buildBooks() { + if (books.isEmpty()) { + IntStream.range(0, NUM_BOOKS).forEach(n -> { + books.add(new Book(MIN_BOOK_NUM + n + 1, "Spring in Action")); + }); + + } + + return books; + } + +} diff --git a/spring-thymeleaf/src/main/resources/messages_en.properties b/spring-thymeleaf/src/main/resources/messages_en.properties index 373c20f1d1..b534d448b6 100644 --- a/spring-thymeleaf/src/main/resources/messages_en.properties +++ b/spring-thymeleaf/src/main/resources/messages_en.properties @@ -1,12 +1,13 @@ -msg.id=ID -msg.name=Name -msg.gender=Gender -msg.percent=Percentage -welcome.message=Welcome Student !!! -msg.AddStudent=Add Student -msg.ListStudents=List Students -msg.Home=Home -msg.ListTeachers=List Teachers -msg.courses=Courses -msg.skills=Skills +msg.id=ID +msg.name=Name +msg.gender=Gender +msg.percent=Percentage +welcome.message=Welcome Student !!! +msg.AddStudent=Add Student +msg.ListStudents=List Students +msg.Home=Home +msg.ListTeachers=List Teachers +msg.ListBooks=List Books with paging +msg.courses=Courses +msg.skills=Skills msg.active=Active \ No newline at end of file diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html index f3d28d7ef4..34a6dec4da 100644 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/addStudent.html @@ -32,7 +32,9 @@