diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 5e86714a89..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,24 +0,0 @@ -language: java - -before_install: - - echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc - -install: skip -script: travis_wait 60 mvn -q install -Pdefault-first,default-second -Dgib.enabled=true - -sudo: required - -jdk: - - oraclejdk8 - -addons: - apt: - packages: - - oracle-java8-installer - -cache: - directories: - - .autoconf - - $HOME/.m2 - - diff --git a/algorithms-miscellaneous-3/README.md b/algorithms-miscellaneous-3/README.md index 6a38df484a..ce0fde0415 100644 --- a/algorithms-miscellaneous-3/README.md +++ b/algorithms-miscellaneous-3/README.md @@ -7,3 +7,4 @@ - [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted) - [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle) - [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique) +- [Creating a Triangle with for Loops in Java](https://www.baeldung.com/java-print-triangle) diff --git a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/bucketsort/IntegerBucketSorter.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/bucketsort/IntegerBucketSorter.java new file mode 100644 index 0000000000..4d885a6b3a --- /dev/null +++ b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/bucketsort/IntegerBucketSorter.java @@ -0,0 +1,70 @@ +package com.baeldung.bucketsort; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +public class IntegerBucketSorter implements Sorter { + + private final Comparator comparator; + + public IntegerBucketSorter(Comparator comparator) { + this.comparator = comparator; + } + + public IntegerBucketSorter() { + comparator = Comparator.naturalOrder(); + } + + public List sort(List arrayToSort) { + + List> buckets = splitIntoUnsortedBuckets(arrayToSort); + + for(List bucket : buckets){ + bucket.sort(comparator); + } + + return concatenateSortedBuckets(buckets); + } + + private List concatenateSortedBuckets(List> buckets){ + List sortedArray = new ArrayList<>(); + int index = 0; + for(List bucket : buckets){ + for(int number : bucket){ + sortedArray.add(index++, number); + } + } + return sortedArray; + } + + private List> splitIntoUnsortedBuckets(List initialList){ + + final int[] codes = createHashes(initialList); + + List> buckets = new ArrayList<>(codes[1]); + for(int i = 0; i < codes[1]; i++) buckets.add(new ArrayList<>()); + + //distribute the data + for (int i : initialList) { + buckets.get(hash(i, codes)).add(i); + } + return buckets; + + } + + private int[] createHashes(List input){ + int m = input.get(0); + for (int i = 1; i < input.size(); i++) { + if (m < input.get(i)) { + m = input.get(i); + } + } + return new int[]{m, (int) Math.sqrt(input.size())}; + } + + private static int hash(int i, int[] code) { + return (int) ((double) i / code[0] * (code[1] - 1)); + } + +} diff --git a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/bucketsort/Sorter.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/bucketsort/Sorter.java new file mode 100644 index 0000000000..b86f60324f --- /dev/null +++ b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/bucketsort/Sorter.java @@ -0,0 +1,8 @@ +package com.baeldung.bucketsort; + +import java.util.List; + +public interface Sorter { + + List sort(List arrayToSort); +} diff --git a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/printtriangles/PrintTriangleExamples.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/printtriangles/PrintTriangleExamples.java index a67c54a922..156766f382 100644 --- a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/printtriangles/PrintTriangleExamples.java +++ b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/printtriangles/PrintTriangleExamples.java @@ -4,7 +4,7 @@ import org.apache.commons.lang3.StringUtils; public class PrintTriangleExamples { - public static String printARightAngledTriangle(int N) { + public static String printARightTriangle(int N) { StringBuilder result = new StringBuilder(); for (int r = 1; r <= N; r++) { for (int j = 1; j <= r; j++) { @@ -29,6 +29,17 @@ public class PrintTriangleExamples { return result.toString(); } + public static String printAnIsoscelesTriangleUsingStringUtils(int N) { + StringBuilder result = new StringBuilder(); + + for (int r = 1; r <= N; r++) { + result.append(StringUtils.repeat(' ', N - r)); + result.append(StringUtils.repeat('*', 2 * r - 1)); + result.append(System.lineSeparator()); + } + return result.toString(); + } + public static String printAnIsoscelesTriangleUsingSubstring(int N) { StringBuilder result = new StringBuilder(); String helperString = StringUtils.repeat(' ', N - 1) + StringUtils.repeat('*', N * 2 - 1); @@ -41,8 +52,9 @@ public class PrintTriangleExamples { } public static void main(String[] args) { - System.out.println(printARightAngledTriangle(5)); + System.out.println(printARightTriangle(5)); System.out.println(printAnIsoscelesTriangle(5)); + System.out.println(printAnIsoscelesTriangleUsingStringUtils(5)); System.out.println(printAnIsoscelesTriangleUsingSubstring(5)); } diff --git a/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/bucketsort/IntegerBucketSorterUnitTest.java b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/bucketsort/IntegerBucketSorterUnitTest.java new file mode 100644 index 0000000000..2773d8a68f --- /dev/null +++ b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/bucketsort/IntegerBucketSorterUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.bucketsort; + +import com.baeldung.bucketsort.IntegerBucketSorter; +import org.junit.Before; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class IntegerBucketSorterUnitTest { + + private IntegerBucketSorter sorter; + + @Before + public void setUp() throws Exception { + sorter = new IntegerBucketSorter(); + } + + @Test + public void givenUnsortedList_whenSortedUsingBucketSorter_checkSortingCorrect() { + + List unsorted = Arrays.asList(80,50,60,30,20,10,70,0,40,500,600,602,200,15); + List expected = Arrays.asList(0,10,15,20,30,40,50,60,70,80,200,500,600,602); + + List actual = sorter.sort(unsorted); + + assertEquals(expected, actual); + + + } +} \ No newline at end of file diff --git a/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/printtriangles/PrintTriangleExamplesUnitTest.java b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/printtriangles/PrintTriangleExamplesUnitTest.java index 6fa6584b8e..97e99290c9 100644 --- a/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/printtriangles/PrintTriangleExamplesUnitTest.java +++ b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/printtriangles/PrintTriangleExamplesUnitTest.java @@ -9,9 +9,9 @@ import static org.junit.Assert.assertEquals; @RunWith(JUnitParamsRunner.class) public class PrintTriangleExamplesUnitTest { - - private static Object[][] rightAngledTriangles() { - String expected0 = ""; + + private static Object[][] rightTriangles() { + String expected0 = ""; String expected2 = "*" + System.lineSeparator() + "**" + System.lineSeparator(); @@ -39,9 +39,9 @@ public class PrintTriangleExamplesUnitTest { } @Test - @Parameters(method = "rightAngledTriangles") - public void whenPrintARightAngledTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) { - String actual = PrintTriangleExamples.printARightAngledTriangle(nrOfRows); + @Parameters(method = "rightTriangles") + public void whenPrintARightTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) { + String actual = PrintTriangleExamples.printARightTriangle(nrOfRows); assertEquals(expected, actual); } @@ -81,6 +81,14 @@ public class PrintTriangleExamplesUnitTest { assertEquals(expected, actual); } + + @Test + @Parameters(method = "isoscelesTriangles") + public void whenPrintAnIsoscelesTriangleUsingStringUtilsIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) { + String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingStringUtils(nrOfRows); + + assertEquals(expected, actual); + } @Test @Parameters(method = "isoscelesTriangles") diff --git a/algorithms-sorting/README.md b/algorithms-sorting/README.md index 48c75f88cd..968d51aecf 100644 --- a/algorithms-sorting/README.md +++ b/algorithms-sorting/README.md @@ -6,3 +6,4 @@ - [Insertion Sort in Java](https://www.baeldung.com/java-insertion-sort) - [Heap Sort in Java](https://www.baeldung.com/java-heap-sort) - [Shell Sort in Java](https://www.baeldung.com/java-shell-sort) +- [Counting Sort in Java](https://www.baeldung.com/java-counting-sort) diff --git a/algorithms-sorting/src/main/java/com/baeldung/algorithms/counting/CountingSort.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/counting/CountingSort.java new file mode 100644 index 0000000000..823f372849 --- /dev/null +++ b/algorithms-sorting/src/main/java/com/baeldung/algorithms/counting/CountingSort.java @@ -0,0 +1,48 @@ +package com.baeldung.algorithms.counting; + +import java.util.Arrays; +import java.util.stream.IntStream; + +public class CountingSort { + + public static int[] sort(int[] input, int k) { + verifyPreconditions(input, k); + if (input.length == 0) return input; + + int[] c = countElements(input, k); + int[] sorted = new int[input.length]; + for (int i = input.length - 1; i >= 0; i--) { + int current = input[i]; + sorted[c[current] - 1] = current; + c[current] -= 1; + } + + return sorted; + } + + static int[] countElements(int[] input, int k) { + int[] c = new int[k + 1]; + Arrays.fill(c, 0); + for (int i : input) { + c[i] += 1; + } + + for (int i = 1; i < c.length; i++) { + c[i] += c[i - 1]; + } + return c; + } + + private static void verifyPreconditions(int[] input, int k) { + if (input == null) { + throw new IllegalArgumentException("Input is required"); + } + + int min = IntStream.of(input).min().getAsInt(); + int max = IntStream.of(input).max().getAsInt(); + + if (min < 0 || max > k) { + throw new IllegalArgumentException("The input numbers should be between zero and " + k); + } + } +} diff --git a/algorithms-sorting/src/main/java/com/baeldung/algorithms/radixsort/RadixSort.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/radixsort/RadixSort.java new file mode 100644 index 0000000000..26c5c9a486 --- /dev/null +++ b/algorithms-sorting/src/main/java/com/baeldung/algorithms/radixsort/RadixSort.java @@ -0,0 +1,53 @@ +package com.baeldung.algorithms.radixsort; + +import java.util.Arrays; + +public class RadixSort { + + public static void sort(int numbers[]) { + int maximumNumber = findMaximumNumberIn(numbers); + + int numberOfDigits = calculateNumberOfDigitsIn(maximumNumber); + + int placeValue = 1; + + while (numberOfDigits-- > 0) { + applyCountingSortOn(numbers, placeValue); + placeValue *= 10; + } + } + + private static void applyCountingSortOn(int[] numbers, int placeValue) { + int range = 10; // radix or the base + + int length = numbers.length; + int[] frequency = new int[range]; + int[] sortedValues = new int[length]; + + for (int i = 0; i < length; i++) { + int digit = (numbers[i] / placeValue) % range; + frequency[digit]++; + } + + for (int i = 1; i < 10; i++) { + frequency[i] += frequency[i - 1]; + } + + for (int i = length - 1; i >= 0; i--) { + int digit = (numbers[i] / placeValue) % range; + sortedValues[frequency[digit] - 1] = numbers[i]; + frequency[digit]--; + } + + System.arraycopy(sortedValues, 0, numbers, 0, length); + } + + private static int calculateNumberOfDigitsIn(int number) { + return (int) Math.log10(number) + 1; // valid only if number > 0 + } + + private static int findMaximumNumberIn(int[] arr) { + return Arrays.stream(arr).max().getAsInt(); + } + +} diff --git a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparators.java b/algorithms-sorting/src/main/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparators.java similarity index 93% rename from algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparators.java rename to algorithms-sorting/src/main/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparators.java index 376b196aa1..b177bd60fc 100644 --- a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparators.java +++ b/algorithms-sorting/src/main/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparators.java @@ -1,4 +1,4 @@ -package com.baeldung.algorithms.stringsortingbynumber; +package com.baeldung.algorithms.sort.bynumber; import java.util.Comparator; diff --git a/algorithms-sorting/src/test/java/com/baeldung/algorithms/counting/CountingSortUnitTest.java b/algorithms-sorting/src/test/java/com/baeldung/algorithms/counting/CountingSortUnitTest.java new file mode 100644 index 0000000000..ec6cf0784e --- /dev/null +++ b/algorithms-sorting/src/test/java/com/baeldung/algorithms/counting/CountingSortUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.algorithms.counting; + +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +import org.junit.jupiter.api.Test; + +class CountingSortUnitTest { + + @Test + void countElements_GivenAnArray_ShouldCalculateTheFrequencyArrayAsExpected() { + int k = 5; + int[] input = { 4, 3, 2, 5, 4, 3, 5, 1, 0, 2, 5 }; + + int[] c = CountingSort.countElements(input, k); + int[] expected = { 1, 2, 4, 6, 8, 11 }; + assertArrayEquals(expected, c); + } + + @Test + void sort_GivenAnArray_ShouldSortTheInputAsExpected() { + int k = 5; + int[] input = { 4, 3, 2, 5, 4, 3, 5, 1, 0, 2, 5 }; + + int[] sorted = CountingSort.sort(input, k); + + // Our sorting algorithm and Java's should return the same result + Arrays.sort(input); + assertArrayEquals(input, sorted); + } +} \ No newline at end of file diff --git a/algorithms-sorting/src/test/java/com/baeldung/algorithms/radixsort/RadixSortUnitTest.java b/algorithms-sorting/src/test/java/com/baeldung/algorithms/radixsort/RadixSortUnitTest.java new file mode 100644 index 0000000000..f1b50f5c99 --- /dev/null +++ b/algorithms-sorting/src/test/java/com/baeldung/algorithms/radixsort/RadixSortUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.algorithms.radixsort; + +import static org.junit.Assert.assertArrayEquals; + +import org.junit.Test; + +public class RadixSortUnitTest { + + @Test + public void givenUnsortedArrayWhenRadixSortThenArraySorted() { + int[] numbers = { 387, 468, 134, 123, 68, 221, 769, 37, 7 }; + RadixSort.sort(numbers); + int[] numbersSorted = { 7, 37, 68, 123, 134, 221, 387, 468, 769 }; + assertArrayEquals(numbersSorted, numbers); + } +} diff --git a/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparatorsUnitTest.java b/algorithms-sorting/src/test/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparatorsUnitTest.java similarity index 94% rename from algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparatorsUnitTest.java rename to algorithms-sorting/src/test/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparatorsUnitTest.java index 549151bc93..2f05f62147 100644 --- a/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/stringsortingbynumber/NaturalOrderComparatorsUnitTest.java +++ b/algorithms-sorting/src/test/java/com/baeldung/algorithms/sort/bynumber/NaturalOrderComparatorsUnitTest.java @@ -1,6 +1,6 @@ -package com.baeldung.algorithms.stringsortingbynumber; +package com.baeldung.algorithms.sort.bynumber; -import com.baeldung.algorithms.stringsortingbynumber.NaturalOrderComparators; +import com.baeldung.algorithms.sort.bynumber.NaturalOrderComparators; import org.junit.Test; import java.util.ArrayList; diff --git a/apache-olingo/olingo2/pom.xml b/apache-olingo/olingo2/pom.xml index 24e7b4e0b2..727e6ca484 100644 --- a/apache-olingo/olingo2/pom.xml +++ b/apache-olingo/olingo2/pom.xml @@ -4,9 +4,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 org.baeldung.examples.olingo2 - olingo2-sample + olingo2 0.0.1-SNAPSHOT - olingo2-sample + olingo2 Sample Olingo 2 Project diff --git a/apache-spark/data/iris.data b/apache-spark/data/iris.data new file mode 100644 index 0000000000..396653cc98 --- /dev/null +++ b/apache-spark/data/iris.data @@ -0,0 +1,150 @@ +5.1,3.5,1.4,0.2,Iris-setosa +4.9,3.0,1.4,0.2,Iris-setosa +4.7,3.2,1.3,0.2,Iris-setosa +4.6,3.1,1.5,0.2,Iris-setosa +5.0,3.6,1.4,0.2,Iris-setosa +5.4,3.9,1.7,0.4,Iris-setosa +4.6,3.4,1.4,0.3,Iris-setosa +5.0,3.4,1.5,0.2,Iris-setosa +4.4,2.9,1.4,0.2,Iris-setosa +4.9,3.1,1.5,0.1,Iris-setosa +5.4,3.7,1.5,0.2,Iris-setosa +4.8,3.4,1.6,0.2,Iris-setosa +4.8,3.0,1.4,0.1,Iris-setosa +4.3,3.0,1.1,0.1,Iris-setosa +5.8,4.0,1.2,0.2,Iris-setosa +5.7,4.4,1.5,0.4,Iris-setosa +5.4,3.9,1.3,0.4,Iris-setosa +5.1,3.5,1.4,0.3,Iris-setosa +5.7,3.8,1.7,0.3,Iris-setosa +5.1,3.8,1.5,0.3,Iris-setosa +5.4,3.4,1.7,0.2,Iris-setosa +5.1,3.7,1.5,0.4,Iris-setosa +4.6,3.6,1.0,0.2,Iris-setosa +5.1,3.3,1.7,0.5,Iris-setosa +4.8,3.4,1.9,0.2,Iris-setosa +5.0,3.0,1.6,0.2,Iris-setosa +5.0,3.4,1.6,0.4,Iris-setosa +5.2,3.5,1.5,0.2,Iris-setosa +5.2,3.4,1.4,0.2,Iris-setosa +4.7,3.2,1.6,0.2,Iris-setosa +4.8,3.1,1.6,0.2,Iris-setosa +5.4,3.4,1.5,0.4,Iris-setosa +5.2,4.1,1.5,0.1,Iris-setosa +5.5,4.2,1.4,0.2,Iris-setosa +4.9,3.1,1.5,0.1,Iris-setosa +5.0,3.2,1.2,0.2,Iris-setosa +5.5,3.5,1.3,0.2,Iris-setosa +4.9,3.1,1.5,0.1,Iris-setosa +4.4,3.0,1.3,0.2,Iris-setosa +5.1,3.4,1.5,0.2,Iris-setosa +5.0,3.5,1.3,0.3,Iris-setosa +4.5,2.3,1.3,0.3,Iris-setosa +4.4,3.2,1.3,0.2,Iris-setosa +5.0,3.5,1.6,0.6,Iris-setosa +5.1,3.8,1.9,0.4,Iris-setosa +4.8,3.0,1.4,0.3,Iris-setosa +5.1,3.8,1.6,0.2,Iris-setosa +4.6,3.2,1.4,0.2,Iris-setosa +5.3,3.7,1.5,0.2,Iris-setosa +5.0,3.3,1.4,0.2,Iris-setosa +7.0,3.2,4.7,1.4,Iris-versicolor +6.4,3.2,4.5,1.5,Iris-versicolor +6.9,3.1,4.9,1.5,Iris-versicolor +5.5,2.3,4.0,1.3,Iris-versicolor +6.5,2.8,4.6,1.5,Iris-versicolor +5.7,2.8,4.5,1.3,Iris-versicolor +6.3,3.3,4.7,1.6,Iris-versicolor +4.9,2.4,3.3,1.0,Iris-versicolor +6.6,2.9,4.6,1.3,Iris-versicolor +5.2,2.7,3.9,1.4,Iris-versicolor +5.0,2.0,3.5,1.0,Iris-versicolor +5.9,3.0,4.2,1.5,Iris-versicolor +6.0,2.2,4.0,1.0,Iris-versicolor +6.1,2.9,4.7,1.4,Iris-versicolor +5.6,2.9,3.6,1.3,Iris-versicolor +6.7,3.1,4.4,1.4,Iris-versicolor +5.6,3.0,4.5,1.5,Iris-versicolor +5.8,2.7,4.1,1.0,Iris-versicolor +6.2,2.2,4.5,1.5,Iris-versicolor +5.6,2.5,3.9,1.1,Iris-versicolor +5.9,3.2,4.8,1.8,Iris-versicolor +6.1,2.8,4.0,1.3,Iris-versicolor +6.3,2.5,4.9,1.5,Iris-versicolor +6.1,2.8,4.7,1.2,Iris-versicolor +6.4,2.9,4.3,1.3,Iris-versicolor +6.6,3.0,4.4,1.4,Iris-versicolor +6.8,2.8,4.8,1.4,Iris-versicolor +6.7,3.0,5.0,1.7,Iris-versicolor +6.0,2.9,4.5,1.5,Iris-versicolor +5.7,2.6,3.5,1.0,Iris-versicolor +5.5,2.4,3.8,1.1,Iris-versicolor +5.5,2.4,3.7,1.0,Iris-versicolor +5.8,2.7,3.9,1.2,Iris-versicolor +6.0,2.7,5.1,1.6,Iris-versicolor +5.4,3.0,4.5,1.5,Iris-versicolor +6.0,3.4,4.5,1.6,Iris-versicolor +6.7,3.1,4.7,1.5,Iris-versicolor +6.3,2.3,4.4,1.3,Iris-versicolor +5.6,3.0,4.1,1.3,Iris-versicolor +5.5,2.5,4.0,1.3,Iris-versicolor +5.5,2.6,4.4,1.2,Iris-versicolor +6.1,3.0,4.6,1.4,Iris-versicolor +5.8,2.6,4.0,1.2,Iris-versicolor +5.0,2.3,3.3,1.0,Iris-versicolor +5.6,2.7,4.2,1.3,Iris-versicolor +5.7,3.0,4.2,1.2,Iris-versicolor +5.7,2.9,4.2,1.3,Iris-versicolor +6.2,2.9,4.3,1.3,Iris-versicolor +5.1,2.5,3.0,1.1,Iris-versicolor +5.7,2.8,4.1,1.3,Iris-versicolor +6.3,3.3,6.0,2.5,Iris-virginica +5.8,2.7,5.1,1.9,Iris-virginica +7.1,3.0,5.9,2.1,Iris-virginica +6.3,2.9,5.6,1.8,Iris-virginica +6.5,3.0,5.8,2.2,Iris-virginica +7.6,3.0,6.6,2.1,Iris-virginica +4.9,2.5,4.5,1.7,Iris-virginica +7.3,2.9,6.3,1.8,Iris-virginica +6.7,2.5,5.8,1.8,Iris-virginica +7.2,3.6,6.1,2.5,Iris-virginica +6.5,3.2,5.1,2.0,Iris-virginica +6.4,2.7,5.3,1.9,Iris-virginica +6.8,3.0,5.5,2.1,Iris-virginica +5.7,2.5,5.0,2.0,Iris-virginica +5.8,2.8,5.1,2.4,Iris-virginica +6.4,3.2,5.3,2.3,Iris-virginica +6.5,3.0,5.5,1.8,Iris-virginica +7.7,3.8,6.7,2.2,Iris-virginica +7.7,2.6,6.9,2.3,Iris-virginica +6.0,2.2,5.0,1.5,Iris-virginica +6.9,3.2,5.7,2.3,Iris-virginica +5.6,2.8,4.9,2.0,Iris-virginica +7.7,2.8,6.7,2.0,Iris-virginica +6.3,2.7,4.9,1.8,Iris-virginica +6.7,3.3,5.7,2.1,Iris-virginica +7.2,3.2,6.0,1.8,Iris-virginica +6.2,2.8,4.8,1.8,Iris-virginica +6.1,3.0,4.9,1.8,Iris-virginica +6.4,2.8,5.6,2.1,Iris-virginica +7.2,3.0,5.8,1.6,Iris-virginica +7.4,2.8,6.1,1.9,Iris-virginica +7.9,3.8,6.4,2.0,Iris-virginica +6.4,2.8,5.6,2.2,Iris-virginica +6.3,2.8,5.1,1.5,Iris-virginica +6.1,2.6,5.6,1.4,Iris-virginica +7.7,3.0,6.1,2.3,Iris-virginica +6.3,3.4,5.6,2.4,Iris-virginica +6.4,3.1,5.5,1.8,Iris-virginica +6.0,3.0,4.8,1.8,Iris-virginica +6.9,3.1,5.4,2.1,Iris-virginica +6.7,3.1,5.6,2.4,Iris-virginica +6.9,3.1,5.1,2.3,Iris-virginica +5.8,2.7,5.1,1.9,Iris-virginica +6.8,3.2,5.9,2.3,Iris-virginica +6.7,3.3,5.7,2.5,Iris-virginica +6.7,3.0,5.2,2.3,Iris-virginica +6.3,2.5,5.0,1.9,Iris-virginica +6.5,3.0,5.2,2.0,Iris-virginica +6.2,3.4,5.4,2.3,Iris-virginica +5.9,3.0,5.1,1.8,Iris-virginica \ No newline at end of file diff --git a/apache-spark/model/logistic-regression/data/._SUCCESS.crc b/apache-spark/model/logistic-regression/data/._SUCCESS.crc new file mode 100644 index 0000000000..3b7b044936 Binary files /dev/null and b/apache-spark/model/logistic-regression/data/._SUCCESS.crc differ diff --git a/apache-spark/model/logistic-regression/data/.part-00000-f3a3ee61-f200-41ff-80d9-8e1edf399601-c000.snappy.parquet.crc b/apache-spark/model/logistic-regression/data/.part-00000-f3a3ee61-f200-41ff-80d9-8e1edf399601-c000.snappy.parquet.crc new file mode 100644 index 0000000000..46311024cf Binary files /dev/null and b/apache-spark/model/logistic-regression/data/.part-00000-f3a3ee61-f200-41ff-80d9-8e1edf399601-c000.snappy.parquet.crc differ diff --git a/apache-spark/model/logistic-regression/data/_SUCCESS b/apache-spark/model/logistic-regression/data/_SUCCESS new file mode 100644 index 0000000000..e69de29bb2 diff --git a/apache-spark/model/logistic-regression/data/part-00000-f3a3ee61-f200-41ff-80d9-8e1edf399601-c000.snappy.parquet b/apache-spark/model/logistic-regression/data/part-00000-f3a3ee61-f200-41ff-80d9-8e1edf399601-c000.snappy.parquet new file mode 100644 index 0000000000..07f442ef34 Binary files /dev/null and b/apache-spark/model/logistic-regression/data/part-00000-f3a3ee61-f200-41ff-80d9-8e1edf399601-c000.snappy.parquet differ diff --git a/apache-spark/model/logistic-regression/metadata/._SUCCESS.crc b/apache-spark/model/logistic-regression/metadata/._SUCCESS.crc new file mode 100644 index 0000000000..3b7b044936 Binary files /dev/null and b/apache-spark/model/logistic-regression/metadata/._SUCCESS.crc differ diff --git a/apache-spark/model/logistic-regression/metadata/.part-00000.crc b/apache-spark/model/logistic-regression/metadata/.part-00000.crc new file mode 100644 index 0000000000..35d5043fbe Binary files /dev/null and b/apache-spark/model/logistic-regression/metadata/.part-00000.crc differ diff --git a/apache-spark/model/logistic-regression/metadata/_SUCCESS b/apache-spark/model/logistic-regression/metadata/_SUCCESS new file mode 100644 index 0000000000..e69de29bb2 diff --git a/apache-spark/model/logistic-regression/metadata/part-00000 b/apache-spark/model/logistic-regression/metadata/part-00000 new file mode 100644 index 0000000000..e3f27fec10 --- /dev/null +++ b/apache-spark/model/logistic-regression/metadata/part-00000 @@ -0,0 +1 @@ +{"class":"org.apache.spark.mllib.classification.LogisticRegressionModel","version":"1.0","numFeatures":4,"numClasses":3} diff --git a/apache-spark/pom.xml b/apache-spark/pom.xml index b8c1962dd4..3df81e5aee 100644 --- a/apache-spark/pom.xml +++ b/apache-spark/pom.xml @@ -1,31 +1,32 @@ - - 4.0.0 - com.baeldung - apache-spark - 1.0-SNAPSHOT - apache-spark - jar - http://maven.apache.org + + 4.0.0 + com.baeldung + apache-spark + 1.0-SNAPSHOT + apache-spark + jar + http://maven.apache.org - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - - org.apache.spark - spark-core_2.11 - ${org.apache.spark.spark-core.version} - provided - + - org.apache.spark - spark-sql_2.11 - ${org.apache.spark.spark-sql.version} - provided + org.apache.spark + spark-core_2.11 + ${org.apache.spark.spark-core.version} + provided + + + org.apache.spark + spark-sql_2.11 + ${org.apache.spark.spark-sql.version} + provided org.apache.spark @@ -33,6 +34,12 @@ ${org.apache.spark.spark-streaming.version} provided + + org.apache.spark + spark-mllib_2.11 + ${org.apache.spark.spark-mllib.version} + provided + org.apache.spark spark-streaming-kafka-0-10_2.11 @@ -48,46 +55,47 @@ spark-cassandra-connector-java_2.11 ${com.datastax.spark.spark-cassandra-connector-java.version} - + - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - - - - maven-assembly-plugin - - - package - - single - - - - - - jar-with-dependencies - - - - - + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${java.version} + ${java.version} + + + + maven-assembly-plugin + + + package + + single + + + + + + jar-with-dependencies + + + + + - - 2.3.0 - 2.3.0 - 2.3.0 - 2.3.0 - 2.3.0 - 1.5.2 + + 2.3.0 + 2.3.0 + 2.3.0 + 2.3.0 + 2.3.0 + 2.3.0 + 1.5.2 3.2 - + diff --git a/apache-spark/src/main/java/com/baeldung/ml/MachineLearningApp.java b/apache-spark/src/main/java/com/baeldung/ml/MachineLearningApp.java new file mode 100644 index 0000000000..6094683031 --- /dev/null +++ b/apache-spark/src/main/java/com/baeldung/ml/MachineLearningApp.java @@ -0,0 +1,111 @@ +package com.baeldung.ml; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.log4j.Level; +import org.apache.log4j.Logger; +import org.apache.spark.SparkConf; +import org.apache.spark.api.java.JavaPairRDD; +import org.apache.spark.api.java.JavaRDD; +import org.apache.spark.api.java.JavaSparkContext; +import org.apache.spark.mllib.classification.LogisticRegressionModel; +import org.apache.spark.mllib.classification.LogisticRegressionWithLBFGS; +import org.apache.spark.mllib.evaluation.MulticlassMetrics; +import org.apache.spark.mllib.linalg.Matrix; +import org.apache.spark.mllib.linalg.Vector; +import org.apache.spark.mllib.linalg.Vectors; +import org.apache.spark.mllib.regression.LabeledPoint; +import org.apache.spark.mllib.stat.MultivariateStatisticalSummary; +import org.apache.spark.mllib.stat.Statistics; + +import scala.Tuple2; + +public class MachineLearningApp { + + public static void main(String[] args) { + + // 1. Setting the Spark Context + SparkConf conf = new SparkConf().setAppName("Main") + .setMaster("local[2]") + .set("spark.executor.memory", "3g") + .set("spark.driver.memory", "3g"); + JavaSparkContext sc = new JavaSparkContext(conf); + Logger.getLogger("org") + .setLevel(Level.OFF); + Logger.getLogger("akka") + .setLevel(Level.OFF); + + // 2. Loading the Data-set + String dataFile = "data\\iris.data"; + JavaRDD data = sc.textFile(dataFile); + + // 3. Exploratory Data Analysis + // 3.1. Creating Vector of Input Data + JavaRDD inputData = data.map(line -> { + String[] parts = line.split(","); + double[] v = new double[parts.length - 1]; + for (int i = 0; i < parts.length - 1; i++) { + v[i] = Double.parseDouble(parts[i]); + } + return Vectors.dense(v); + }); + // 3.2. Performing Statistical Analysis + MultivariateStatisticalSummary summary = Statistics.colStats(inputData.rdd()); + System.out.println("Summary Mean:"); + System.out.println(summary.mean()); + System.out.println("Summary Variance:"); + System.out.println(summary.variance()); + System.out.println("Summary Non-zero:"); + System.out.println(summary.numNonzeros()); + // 3.3. Performing Correlation Analysis + Matrix correlMatrix = Statistics.corr(inputData.rdd(), "pearson"); + System.out.println("Correlation Matrix:"); + System.out.println(correlMatrix.toString()); + + // 4. Data Preparation + // 4.1. Creating Map for Textual Output Labels + Map map = new HashMap(); + map.put("Iris-setosa", 0); + map.put("Iris-versicolor", 1); + map.put("Iris-virginica", 2); + // 4.2. Creating LabeledPoint of Input and Output Data + JavaRDD parsedData = data.map(line -> { + String[] parts = line.split(","); + double[] v = new double[parts.length - 1]; + for (int i = 0; i < parts.length - 1; i++) { + v[i] = Double.parseDouble(parts[i]); + } + return new LabeledPoint(map.get(parts[parts.length - 1]), Vectors.dense(v)); + }); + + // 5. Data Splitting into 80% Training and 20% Test Sets + JavaRDD[] splits = parsedData.randomSplit(new double[] { 0.8, 0.2 }, 11L); + JavaRDD trainingData = splits[0].cache(); + JavaRDD testData = splits[1]; + + // 6. Modeling + // 6.1. Model Training + LogisticRegressionModel model = new LogisticRegressionWithLBFGS().setNumClasses(3) + .run(trainingData.rdd()); + // 6.2. Model Evaluation + JavaPairRDD predictionAndLabels = testData.mapToPair(p -> new Tuple2<>(model.predict(p.features()), p.label())); + MulticlassMetrics metrics = new MulticlassMetrics(predictionAndLabels.rdd()); + double accuracy = metrics.accuracy(); + System.out.println("Model Accuracy on Test Data: " + accuracy); + + // 7. Model Saving and Loading + // 7.1. Model Saving + model.save(sc.sc(), "model\\logistic-regression"); + // 7.2. Model Loading + LogisticRegressionModel sameModel = LogisticRegressionModel.load(sc.sc(), "model\\logistic-regression"); + // 7.3. Prediction on New Data + Vector newData = Vectors.dense(new double[] { 1, 1, 1, 1 }); + double prediction = sameModel.predict(newData); + System.out.println("Model Prediction on New Data = " + prediction); + + // 8. Clean-up + sc.close(); + } + +} diff --git a/bazel/README.md b/bazel/README.md new file mode 100644 index 0000000000..d1f8f1af5b --- /dev/null +++ b/bazel/README.md @@ -0,0 +1,3 @@ +## Relevant Articles: + +- [Building Java Applications with Bazel](https://www.baeldung.com/bazel-build-tool) diff --git a/bazel/WORKSPACE b/bazel/WORKSPACE new file mode 100644 index 0000000000..415aa398f9 --- /dev/null +++ b/bazel/WORKSPACE @@ -0,0 +1,31 @@ + +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_jar") +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") + + +RULES_JVM_EXTERNAL_TAG = "2.0.1" +RULES_JVM_EXTERNAL_SHA = "55e8d3951647ae3dffde22b4f7f8dee11b3f70f3f89424713debd7076197eaca" + +http_archive( + name = "rules_jvm_external", + strip_prefix = "rules_jvm_external-%s" % RULES_JVM_EXTERNAL_TAG, + sha256 = RULES_JVM_EXTERNAL_SHA, + url = "https://github.com/bazelbuild/rules_jvm_external/archive/%s.zip" % RULES_JVM_EXTERNAL_TAG, +) + +load("@rules_jvm_external//:defs.bzl", "maven_install") + +maven_install( + artifacts = [ + "org.apache.commons:commons-lang3:3.9" + ], + repositories = [ + "https://repo1.maven.org/maven2", + ] +) + +http_jar ( + name = "apache-commons-lang", + url = "https://repo1.maven.org/maven2/org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar" +) + diff --git a/bazel/bazelapp/BUILD b/bazel/bazelapp/BUILD new file mode 100644 index 0000000000..1de95aada5 --- /dev/null +++ b/bazel/bazelapp/BUILD @@ -0,0 +1,7 @@ + +java_binary ( + name = "BazelApp", + srcs = glob(["src/main/java/com/baeldung/*.java"]), + main_class = "com.baeldung.BazelApp", + deps = ["//bazelgreeting:greeter", "@maven//:org_apache_commons_commons_lang3"] +) diff --git a/bazel/bazelapp/pom.xml b/bazel/bazelapp/pom.xml new file mode 100644 index 0000000000..9c9fb59619 --- /dev/null +++ b/bazel/bazelapp/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + bazelapp + bazelapp + + + bazel + com.baeldung + 1.0.0-SNAPSHOT + + + + + com.baeldung + bazelgreeting + 1.0.0-SNAPSHOT + + + org.apache.commons + commons-lang3 + 3.9 + + + + + \ No newline at end of file diff --git a/bazel/bazelapp/src/main/java/com/baeldung/BazelApp.java b/bazel/bazelapp/src/main/java/com/baeldung/BazelApp.java new file mode 100644 index 0000000000..e92d85018b --- /dev/null +++ b/bazel/bazelapp/src/main/java/com/baeldung/BazelApp.java @@ -0,0 +1,15 @@ +package com.baeldung; + +import com.baeldung.Greetings; +import org.apache.commons.lang3.StringUtils; + +public class BazelApp { + + public static void main(String ... args) { + Greetings greetings = new Greetings(); + + System.out.println(greetings.greet("Bazel")); + + System.out.println(StringUtils.lowerCase("Bazel")); + } +} diff --git a/bazel/bazelgreeting/BUILD b/bazel/bazelgreeting/BUILD new file mode 100644 index 0000000000..6cd8bc13f7 --- /dev/null +++ b/bazel/bazelgreeting/BUILD @@ -0,0 +1,6 @@ + +java_library ( + name = "greeter", + srcs = glob(["src/main/java/com/baeldung/*.java"]), + visibility = ["//bazelapp:__pkg__"] +) diff --git a/bazel/bazelgreeting/pom.xml b/bazel/bazelgreeting/pom.xml new file mode 100644 index 0000000000..e688a55bd5 --- /dev/null +++ b/bazel/bazelgreeting/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + bazelgreeting + bazelgreeting + + + bazel + com.baeldung + 1.0.0-SNAPSHOT + + + + \ No newline at end of file diff --git a/bazel/bazelgreeting/src/main/java/com/baeldung/Greetings.java b/bazel/bazelgreeting/src/main/java/com/baeldung/Greetings.java new file mode 100644 index 0000000000..0e8fae7fbe --- /dev/null +++ b/bazel/bazelgreeting/src/main/java/com/baeldung/Greetings.java @@ -0,0 +1,8 @@ +package com.baeldung; + +public class Greetings { + + public String greet(String name) { + return "Hello ".concat(name); + } +} diff --git a/bazel/pom.xml b/bazel/pom.xml new file mode 100644 index 0000000000..cb784ec6e6 --- /dev/null +++ b/bazel/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + bazel + pom + bazel + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + bazelgreeting + bazelapp + + + + \ No newline at end of file diff --git a/core-groovy-2/pom.xml b/core-groovy-2/pom.xml index ba3fd0802b..91e31d4cba 100644 --- a/core-groovy-2/pom.xml +++ b/core-groovy-2/pom.xml @@ -48,6 +48,11 @@ ${spock-core.version} test + + com.github.groovy-wslite + groovy-wslite + ${groovy-wslite.version} + @@ -175,6 +180,7 @@ 1.0.0 2.4.0 1.1-groovy-2.4 + 1.1.3 3.8.1 1.2.3 2.5.7 diff --git a/core-groovy-2/src/test/groovy/com/baeldung/webservice/WebserviceUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/webservice/WebserviceUnitTest.groovy new file mode 100644 index 0000000000..302959d0d9 --- /dev/null +++ b/core-groovy-2/src/test/groovy/com/baeldung/webservice/WebserviceUnitTest.groovy @@ -0,0 +1,152 @@ +package com.baeldung.webservice + +import groovy.json.JsonSlurper +import wslite.rest.ContentType +import wslite.rest.RESTClient +import wslite.rest.RESTClientException +import wslite.soap.SOAPClient +import wslite.soap.SOAPMessageBuilder +import wslite.http.auth.HTTPBasicAuthorization +import org.junit.Test + +class WebserviceUnitTest extends GroovyTestCase { + + JsonSlurper jsonSlurper = new JsonSlurper() + + static RESTClient client = new RESTClient("https://postman-echo.com") + + static { + client.defaultAcceptHeader = ContentType.JSON + client.httpClient.sslTrustAllCerts = true + } + + void test_whenSendingGet_thenRespose200() { + def postmanGet = new URL('https://postman-echo.com/get') + def getConnection = postmanGet.openConnection() + getConnection.requestMethod = 'GET' + assert getConnection.responseCode == 200 + if (getConnection.responseCode == 200) { + assert jsonSlurper.parseText(getConnection.content.text)?.headers?.host == "postman-echo.com" + } + } + + void test_whenSendingPost_thenRespose200() { + def postmanPost = new URL('https://postman-echo.com/post') + def query = "q=This is post request form parameter." + def postConnection = postmanPost.openConnection() + postConnection.requestMethod = 'POST' + assert postConnection.responseCode == 200 + } + + void test_whenSendingPostWithParams_thenRespose200() { + def postmanPost = new URL('https://postman-echo.com/post') + def form = "param1=This is request parameter." + def postConnection = postmanPost.openConnection() + postConnection.requestMethod = 'POST' + postConnection.doOutput = true + def text + postConnection.with { + outputStream.withWriter { outputStreamWriter -> + outputStreamWriter << form + } + text = content.text + } + assert postConnection.responseCode == 200 + assert jsonSlurper.parseText(text)?.json.param1 == "This is request parameter." + } + + void test_whenReadingRSS_thenReceiveFeed() { + def rssFeed = new XmlParser().parse("https://news.google.com/rss?hl=en-US&gl=US&ceid=US:en") + def stories = [] + (0..4).each { + def item = rssFeed.channel.item.get(it) + stories << item.title.text() + } + assert stories.size() == 5 + } + + void test_whenReadingAtom_thenReceiveFeed() { + def atomFeed = new XmlParser().parse("https://news.google.com/atom?hl=en-US&gl=US&ceid=US:en") + def stories = [] + (0..4).each { + def entry = atomFeed.entry.get(it) + stories << entry.title.text() + } + assert stories.size() == 5 + } + + void test_whenConsumingSoap_thenReceiveResponse() { + def url = "http://www.dataaccess.com/webservicesserver/numberconversion.wso" + def soapClient = new SOAPClient(url) + def message = new SOAPMessageBuilder().build({ + body { + NumberToWords(xmlns: "http://www.dataaccess.com/webservicesserver/") { + ubiNum(1234) + } + } + }) + def response = soapClient.send(message.toString()); + def words = response.NumberToWordsResponse + assert words == "one thousand two hundred and thirty four " + } + + void test_whenConsumingRestGet_thenReceiveResponse() { + def path = "/get" + def response + try { + response = client.get(path: path) + assert response.statusCode == 200 + assert response.json?.headers?.host == "postman-echo.com" + } catch (RESTClientException e) { + assert e?.response?.statusCode != 200 + } + } + + void test_whenConsumingRestPost_thenReceiveResponse() { + def path = "/post" + def params = ["foo":1,"bar":2] + def response + try { + response = client.post(path: path) { + type ContentType.JSON + json params + } + assert response.json?.data == params + } catch (RESTClientException e) { + e.printStackTrace() + assert e?.response?.statusCode != 200 + } + } + + void test_whenBasicAuthentication_thenReceive200() { + def path = "/basic-auth" + def response + try { + client.authorization = new HTTPBasicAuthorization("postman", "password") + response = client.get(path: path) + assert response.statusCode == 200 + assert response.json?.authenticated == true + } catch (RESTClientException e) { + e.printStackTrace() + assert e?.response?.statusCode != 200 + } + } + + void test_whenOAuth_thenReceive200() { + RESTClient oAuthClient = new RESTClient("https://postman-echo.com") + oAuthClient.defaultAcceptHeader = ContentType.JSON + oAuthClient.httpClient.sslTrustAllCerts = true + + def path = "/oauth1" + def params = [oauth_consumer_key: "RKCGzna7bv9YD57c", oauth_signature_method: "HMAC-SHA1", oauth_timestamp:1567089944, oauth_nonce: "URT7v4", oauth_version: 1.0, oauth_signature: 'RGgR/ktDmclkM0ISWaFzebtlO0A='] + def response + try { + response = oAuthClient.get(path: path, query: params) + assert response.statusCode == 200 + assert response.statusMessage == "OK" + assert response.json.status == "pass" + } catch (RESTClientException e) { + assert e?.response?.statusCode != 200 + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-8/README.md b/core-java-modules/core-java-8/README.md index 6e79eddd16..aee7121fb3 100644 --- a/core-java-modules/core-java-8/README.md +++ b/core-java-modules/core-java-8/README.md @@ -20,7 +20,6 @@ - [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max) - [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization) - [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get) -- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection) - [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic) - [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference) - [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time) diff --git a/core-java-modules/core-java-8/pom.xml b/core-java-modules/core-java-8/pom.xml index 28182e515b..6e547b7fad 100644 --- a/core-java-modules/core-java-8/pom.xml +++ b/core-java-modules/core-java-8/pom.xml @@ -134,16 +134,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - -parameters - - org.springframework.boot spring-boot-maven-plugin @@ -192,7 +182,6 @@ 1.19 2.0.4.RELEASE - 3.8.0 2.22.1 diff --git a/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java_8_features/groupingby/Java8GroupingByCollectorUnitTest.java similarity index 99% rename from core-java-modules/core-java-8/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java_8_features/groupingby/Java8GroupingByCollectorUnitTest.java index eea019da2c..323586b85f 100644 --- a/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java +++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/java_8_features/groupingby/Java8GroupingByCollectorUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java8; +package com.baeldung.java_8_features.groupingby; import com.baeldung.java_8_features.groupingby.BlogPost; import com.baeldung.java_8_features.groupingby.BlogPostType; diff --git a/core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/java/list/RemoveFromList.java b/core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/java/list/RemoveFromList.java new file mode 100644 index 0000000000..df9b3d987d --- /dev/null +++ b/core-java-modules/core-java-collections-array-list/src/main/java/com/baeldung/java/list/RemoveFromList.java @@ -0,0 +1,40 @@ +package com.baeldung.java.list; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class RemoveFromList { + + public static void main(String[] args) { + List sports = new ArrayList<>(); + sports.add("Football"); + sports.add("Basketball"); + sports.add("Baseball"); + sports.add("Boxing"); + sports.add("Cycling"); + + System.out.println("List before removing: " + sports); + + // Remove with index + sports.remove(1); + + // Remove with an element + sports.remove("Baseball"); + + // Iterator remove method + Iterator iterator = sports.iterator(); + while (iterator.hasNext()) { + if (iterator.next().equals("Boxing")) { + iterator.remove(); + break; + } + } + + // ArrayList removeIf method (Java 8) + sports.removeIf(p -> p.equals("Cycling")); + + System.out.println("List after removing: " + sports); + } + +} diff --git a/core-java-modules/core-java-collections-list-2/README.md b/core-java-modules/core-java-collections-list-2/README.md index be10a0210c..6192442edd 100644 --- a/core-java-modules/core-java-collections-list-2/README.md +++ b/core-java-modules/core-java-collections-list-2/README.md @@ -10,8 +10,4 @@ - [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line) - [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list) - [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections) -- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection) -- [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal) -- [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int) -- [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance) -- [Filtering a Java Collection by a List](https://www.baeldung.com/java-filter-collection-by-list) \ No newline at end of file +- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection) \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-2/pom.xml b/core-java-modules/core-java-collections-list-2/pom.xml index d200a3c90c..727de0818a 100644 --- a/core-java-modules/core-java-collections-list-2/pom.xml +++ b/core-java-modules/core-java-collections-list-2/pom.xml @@ -36,41 +36,11 @@ ${lombok.version} provided - - - net.sf.trove4j - trove4j - ${trove4j.version} - - - it.unimi.dsi - fastutil - ${fastutil.version} - - - colt - colt - ${colt.version} - - - - org.openjdk.jmh - jmh-core - ${jmh-core.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh-core.version} - 4.1 3.8.1 3.11.1 - 3.0.2 - 8.1.0 - 1.2.0 diff --git a/core-java-modules/core-java-collections-list-3/README.md b/core-java-modules/core-java-collections-list-3/README.md new file mode 100644 index 0000000000..267996044c --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/README.md @@ -0,0 +1,11 @@ +========= + +## Core Java Collections List Cookbooks and Examples + +### Relevant Articles: +- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list) +- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another) +- [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal) +- [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int) +- [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance) +- [Filtering a Java Collection by a List](https://www.baeldung.com/java-filter-collection-by-list) diff --git a/core-java-modules/core-java-collections-list-3/pom.xml b/core-java-modules/core-java-collections-list-3/pom.xml new file mode 100644 index 0000000000..064b65d19e --- /dev/null +++ b/core-java-modules/core-java-collections-list-3/pom.xml @@ -0,0 +1,76 @@ + + 4.0.0 + core-java-collections-list-3 + 0.1.0-SNAPSHOT + core-java-collections-list-3 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + net.sf.trove4j + trove4j + ${trove4j.version} + + + it.unimi.dsi + fastutil + ${fastutil.version} + + + colt + colt + ${colt.version} + + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-core.version} + + + + + 4.1 + 3.8.1 + 3.11.1 + 3.0.2 + 8.1.0 + 1.2.0 + + diff --git a/core-java-modules/core-java-collections-list-2/src/main/java/com/baeldung/allequalelements/VerifyAllEqualListElements.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/allequalelements/VerifyAllEqualListElements.java similarity index 100% rename from core-java-modules/core-java-collections-list-2/src/main/java/com/baeldung/allequalelements/VerifyAllEqualListElements.java rename to core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/allequalelements/VerifyAllEqualListElements.java diff --git a/core-java-modules/core-java-collections-list-2/src/main/java/com/baeldung/collection/filtering/Employee.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/collection/filtering/Employee.java similarity index 100% rename from core-java-modules/core-java-collections-list-2/src/main/java/com/baeldung/collection/filtering/Employee.java rename to core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/collection/filtering/Employee.java diff --git a/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java/list/CopyListService.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/java/list/CopyListService.java similarity index 100% rename from core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java/list/CopyListService.java rename to core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/java/list/CopyListService.java diff --git a/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java/list/Flower.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/java/list/Flower.java similarity index 100% rename from core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java/list/Flower.java rename to core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/java/list/Flower.java diff --git a/core-java-modules/core-java-collections-list-2/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java similarity index 100% rename from core-java-modules/core-java-collections-list-2/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java rename to core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/primitive/PrimitiveCollections.java diff --git a/core-java-modules/core-java-collections-list-2/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java b/core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java similarity index 100% rename from core-java-modules/core-java-collections-list-2/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java rename to core-java-modules/core-java-collections-list-3/src/main/java/com/baeldung/list/primitive/PrimitivesListPerformance.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/logback.xml b/core-java-modules/core-java-collections-list-3/src/main/resources/logback.xml similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/logback.xml rename to core-java-modules/core-java-collections-list-3/src/main/resources/logback.xml diff --git a/core-java-modules/core-java-collections-list-2/src/test/java/com/baeldung/allequalelements/VerifyAllEqualListElementsUnitTest.java b/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/allequalelements/VerifyAllEqualListElementsUnitTest.java similarity index 100% rename from core-java-modules/core-java-collections-list-2/src/test/java/com/baeldung/allequalelements/VerifyAllEqualListElementsUnitTest.java rename to core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/allequalelements/VerifyAllEqualListElementsUnitTest.java diff --git a/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/collection/CollectionsEmpty.java b/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/collection/CollectionsEmpty.java similarity index 100% rename from core-java-modules/core-java-collections-list/src/test/java/com/baeldung/collection/CollectionsEmpty.java rename to core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/collection/CollectionsEmpty.java diff --git a/core-java-modules/core-java-collections-list-2/src/test/java/com/baeldung/collection/filtering/CollectionFilteringUnitTest.java b/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/collection/filtering/CollectionFilteringUnitTest.java similarity index 100% rename from core-java-modules/core-java-collections-list-2/src/test/java/com/baeldung/collection/filtering/CollectionFilteringUnitTest.java rename to core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/collection/filtering/CollectionFilteringUnitTest.java diff --git a/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java b/core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java similarity index 100% rename from core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java rename to core-java-modules/core-java-collections-list-3/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java diff --git a/core-java-modules/core-java-collections-list/README.md b/core-java-modules/core-java-collections-list/README.md index 4bc1c5fb57..e83fcce5ff 100644 --- a/core-java-modules/core-java-collections-list/README.md +++ b/core-java-modules/core-java-collections-list/README.md @@ -10,7 +10,5 @@ - [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards) - [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list) - [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java) -- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another) - [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max) -- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list) - [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list) \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGenerator.java b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGenerator.java index 97d44e5156..26354de0a9 100644 --- a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGenerator.java +++ b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGenerator.java @@ -1,11 +1,12 @@ package com.baeldung.concurrent.mutex; public class SequenceGenerator { + private int currentValue = 0; - public int getNextSequence() throws InterruptedException { + public int getNextSequence() { currentValue = currentValue + 1; - Thread.sleep(500); return currentValue; } + } diff --git a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingMonitor.java b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingMonitor.java index 30c8da4865..2824237e24 100644 --- a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingMonitor.java +++ b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingMonitor.java @@ -4,15 +4,16 @@ import com.google.common.util.concurrent.Monitor; public class SequenceGeneratorUsingMonitor extends SequenceGenerator { - private Monitor monitor = new Monitor(); + private Monitor mutex = new Monitor(); @Override - public int getNextSequence() throws InterruptedException { - monitor.enter(); + public int getNextSequence() { + mutex.enter(); try { return super.getNextSequence(); } finally { - monitor.leave(); + mutex.leave(); } } + } diff --git a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingReentrantLock.java b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingReentrantLock.java index 85ce780bda..d57b0c4a52 100644 --- a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingReentrantLock.java +++ b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingReentrantLock.java @@ -7,7 +7,7 @@ public class SequenceGeneratorUsingReentrantLock extends SequenceGenerator { private ReentrantLock mutex = new ReentrantLock(); @Override - public int getNextSequence() throws InterruptedException { + public int getNextSequence() { try { mutex.lock(); return super.getNextSequence(); @@ -15,4 +15,5 @@ public class SequenceGeneratorUsingReentrantLock extends SequenceGenerator { mutex.unlock(); } } + } diff --git a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingSemaphore.java b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingSemaphore.java index fdece049e6..50f2538646 100644 --- a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingSemaphore.java +++ b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingSemaphore.java @@ -7,12 +7,15 @@ public class SequenceGeneratorUsingSemaphore extends SequenceGenerator { private Semaphore mutex = new Semaphore(1); @Override - public int getNextSequence() throws InterruptedException { + public int getNextSequence() { try { mutex.acquire(); return super.getNextSequence(); + } catch (InterruptedException e) { + throw new RuntimeException("Exception in critical section.", e); } finally { mutex.release(); } } + } diff --git a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingSynchronizedBlock.java b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingSynchronizedBlock.java index d485eae21c..9933c302cb 100644 --- a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingSynchronizedBlock.java +++ b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingSynchronizedBlock.java @@ -2,9 +2,11 @@ package com.baeldung.concurrent.mutex; public class SequenceGeneratorUsingSynchronizedBlock extends SequenceGenerator { + private Object mutex = new Object(); + @Override - public int getNextSequence() throws InterruptedException { - synchronized (this) { + public int getNextSequence() { + synchronized (mutex) { return super.getNextSequence(); } } diff --git a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingSynchronizedMethod.java b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingSynchronizedMethod.java index 441b33dc43..6de8725d73 100644 --- a/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingSynchronizedMethod.java +++ b/core-java-modules/core-java-concurrency-basic/src/main/java/com/baeldung/concurrent/mutex/SequenceGeneratorUsingSynchronizedMethod.java @@ -3,7 +3,7 @@ package com.baeldung.concurrent.mutex; public class SequenceGeneratorUsingSynchronizedMethod extends SequenceGenerator { @Override - public synchronized int getNextSequence() throws InterruptedException { + public synchronized int getNextSequence() { return super.getNextSequence(); } diff --git a/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java b/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/executorservice/Java8ExecutorServiceIntegrationTest.java similarity index 99% rename from core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java rename to core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/executorservice/Java8ExecutorServiceIntegrationTest.java index a1f5b6f1e2..998152c452 100644 --- a/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java +++ b/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/executorservice/Java8ExecutorServiceIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java8; +package com.baeldung.concurrent.executorservice; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; diff --git a/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/mutex/MutexUnitTest.java b/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/mutex/MutexUnitTest.java index 620179800a..462f910718 100644 --- a/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/mutex/MutexUnitTest.java +++ b/core-java-modules/core-java-concurrency-basic/src/test/java/com/baeldung/concurrent/mutex/MutexUnitTest.java @@ -1,7 +1,7 @@ package com.baeldung.concurrent.mutex; import java.util.ArrayList; -import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutorService; @@ -12,59 +12,58 @@ import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test; -import com.baeldung.concurrent.mutex.SequenceGenerator; -import com.baeldung.concurrent.mutex.SequenceGeneratorUsingMonitor; -import com.baeldung.concurrent.mutex.SequenceGeneratorUsingReentrantLock; -import com.baeldung.concurrent.mutex.SequenceGeneratorUsingSemaphore; -import com.baeldung.concurrent.mutex.SequenceGeneratorUsingSynchronizedBlock; -import com.baeldung.concurrent.mutex.SequenceGeneratorUsingSynchronizedMethod; - public class MutexUnitTest { - private final int RANGE = 30; - - @Test + // @Test + // This test verifies the race condition use case, it may pass or fail based on execution environment + // Uncomment @Test to run it public void givenUnsafeSequenceGenerator_whenRaceCondition_thenUnexpectedBehavior() throws Exception { - Set uniqueSequences = getASetOFUniqueSequences(new SequenceGenerator()); - Assert.assertNotEquals(RANGE, uniqueSequences.size()); + int count = 1000; + Set uniqueSequences = getUniqueSequences(new SequenceGenerator(), count); + Assert.assertNotEquals(count, uniqueSequences.size()); } @Test public void givenSequenceGeneratorUsingSynchronizedMethod_whenRaceCondition_thenSuccess() throws Exception { - Set uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingSynchronizedMethod()); - Assert.assertEquals(RANGE, uniqueSequences.size()); + int count = 1000; + Set uniqueSequences = getUniqueSequences(new SequenceGeneratorUsingSynchronizedMethod(), count); + Assert.assertEquals(count, uniqueSequences.size()); } @Test public void givenSequenceGeneratorUsingSynchronizedBlock_whenRaceCondition_thenSuccess() throws Exception { - Set uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingSynchronizedBlock()); - Assert.assertEquals(RANGE, uniqueSequences.size()); + int count = 1000; + Set uniqueSequences = getUniqueSequences(new SequenceGeneratorUsingSynchronizedBlock(), count); + Assert.assertEquals(count, uniqueSequences.size()); } @Test public void givenSequenceGeneratorUsingReentrantLock_whenRaceCondition_thenSuccess() throws Exception { - Set uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingReentrantLock()); - Assert.assertEquals(RANGE, uniqueSequences.size()); + int count = 1000; + Set uniqueSequences = getUniqueSequences(new SequenceGeneratorUsingReentrantLock(), count); + Assert.assertEquals(count, uniqueSequences.size()); } @Test public void givenSequenceGeneratorUsingSemaphore_whenRaceCondition_thenSuccess() throws Exception { - Set uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingSemaphore()); - Assert.assertEquals(RANGE, uniqueSequences.size()); + int count = 1000; + Set uniqueSequences = getUniqueSequences(new SequenceGeneratorUsingSemaphore(), count); + Assert.assertEquals(count, uniqueSequences.size()); } @Test public void givenSequenceGeneratorUsingMonitor_whenRaceCondition_thenSuccess() throws Exception { - Set uniqueSequences = getASetOFUniqueSequences(new SequenceGeneratorUsingMonitor()); - Assert.assertEquals(RANGE, uniqueSequences.size()); + int count = 1000; + Set uniqueSequences = getUniqueSequences(new SequenceGeneratorUsingMonitor(), count); + Assert.assertEquals(count, uniqueSequences.size()); } - private Set getASetOFUniqueSequences(SequenceGenerator generator) throws Exception { + private Set getUniqueSequences(SequenceGenerator generator, int count) throws Exception { ExecutorService executor = Executors.newFixedThreadPool(3); - Set uniqueSequences = new HashSet<>(); + Set uniqueSequences = new LinkedHashSet<>(); List> futures = new ArrayList<>(); - for (int i = 0; i < RANGE; i++) { + for (int i = 0; i < count; i++) { futures.add(executor.submit(generator::getNextSequence)); } @@ -72,7 +71,7 @@ public class MutexUnitTest { uniqueSequences.add(future.get()); } - executor.awaitTermination(15, TimeUnit.SECONDS); + executor.awaitTermination(1, TimeUnit.SECONDS); executor.shutdown(); return uniqueSequences; diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/CheckedUncheckedExceptions.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/CheckedUncheckedExceptions.java new file mode 100644 index 0000000000..780189b654 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/CheckedUncheckedExceptions.java @@ -0,0 +1,43 @@ +package com.baeldung.exceptions; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; + +public class CheckedUncheckedExceptions { + public static void checkedExceptionWithThrows() throws FileNotFoundException { + File file = new File("not_existing_file.txt"); + FileInputStream stream = new FileInputStream(file); + } + + public static void checkedExceptionWithTryCatch() { + File file = new File("not_existing_file.txt"); + try { + FileInputStream stream = new FileInputStream(file); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + public static int divideByZero() { + int numerator = 1; + int denominator = 0; + return numerator / denominator; + } + + public static void checkFile(String fileName) throws IncorrectFileNameException { + if (fileName == null || fileName.isEmpty()) { + throw new NullOrEmptyException("The filename is null."); + } + if (!isCorrectFileName(fileName)) { + throw new IncorrectFileNameException("Incorrect filename : " + fileName); + } + } + + private static boolean isCorrectFileName(String fileName) { + if (fileName.equals("wrongFileName.txt")) + return false; + else + return true; + } +} diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/IncorrectFileNameException.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/IncorrectFileNameException.java new file mode 100644 index 0000000000..9877fe25ca --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/IncorrectFileNameException.java @@ -0,0 +1,13 @@ +package com.baeldung.exceptions; + +public class IncorrectFileNameException extends Exception { + private static final long serialVersionUID = 1L; + + public IncorrectFileNameException(String errorMessage) { + super(errorMessage); + } + + public IncorrectFileNameException(String errorMessage, Throwable thr) { + super(errorMessage, thr); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/NullOrEmptyException.java b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/NullOrEmptyException.java new file mode 100644 index 0000000000..d4ee9c0d6f --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/main/java/com/baeldung/exceptions/NullOrEmptyException.java @@ -0,0 +1,14 @@ +package com.baeldung.exceptions; + +public class NullOrEmptyException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public NullOrEmptyException(String errorMessage) { + super(errorMessage); + } + + public NullOrEmptyException(String errorMessage, Throwable thr) { + super(errorMessage, thr); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/CheckedUncheckedExceptionsUnitTest.java b/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/CheckedUncheckedExceptionsUnitTest.java new file mode 100644 index 0000000000..d82b1349d8 --- /dev/null +++ b/core-java-modules/core-java-exceptions/src/test/java/com/baeldung/exceptions/CheckedUncheckedExceptionsUnitTest.java @@ -0,0 +1,55 @@ +package com.baeldung.exceptions; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.FileNotFoundException; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +/** + * Tests the {@link CheckedUncheckedExceptions}. + */ +public class CheckedUncheckedExceptionsUnitTest { + + @Test + public void whenFileNotExist_thenThrowException() { + assertThrows(FileNotFoundException.class, () -> { + CheckedUncheckedExceptions.checkedExceptionWithThrows(); + }); + } + + @Test + public void whenTryCatchExcetpion_thenSuccess() { + try { + CheckedUncheckedExceptions.checkedExceptionWithTryCatch(); + } catch (Exception e) { + Assertions.fail(e.getMessage()); + } + } + + @Test + public void whenDivideByZero_thenThrowException() { + assertThrows(ArithmeticException.class, () -> { + CheckedUncheckedExceptions.divideByZero(); + }); + } + + @Test + public void whenInvalidFile_thenThrowException() { + + assertThrows(IncorrectFileNameException.class, () -> { + CheckedUncheckedExceptions.checkFile("wrongFileName.txt"); + }); + } + + @Test + public void whenNullOrEmptyFile_thenThrowException() { + assertThrows(NullOrEmptyException.class, () -> { + CheckedUncheckedExceptions.checkFile(null); + }); + assertThrows(NullOrEmptyException.class, () -> { + CheckedUncheckedExceptions.checkFile(""); + }); + } +} diff --git a/core-java-modules/core-java-io-2/.gitignore b/core-java-modules/core-java-io-2/.gitignore new file mode 100644 index 0000000000..de044ef20f --- /dev/null +++ b/core-java-modules/core-java-io-2/.gitignore @@ -0,0 +1,3 @@ +# Intellij +.idea/ +*.iml diff --git a/core-java-modules/core-java-io-2/pom.xml b/core-java-modules/core-java-io-2/pom.xml new file mode 100644 index 0000000000..64d9434beb --- /dev/null +++ b/core-java-modules/core-java-io-2/pom.xml @@ -0,0 +1,279 @@ + + 4.0.0 + core-java-io-2 + 0.1.0-SNAPSHOT + core-java-io-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + + net.sourceforge.collections + collections-generic + ${collections-generic.version} + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + commons-io + commons-io + ${commons-io.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + org.decimal4j + decimal4j + ${decimal4j.version} + + + org.bouncycastle + bcprov-jdk15on + ${bouncycastle.version} + + + org.unix4j + unix4j-command + ${unix4j.version} + + + com.googlecode.grep4j + grep4j + ${grep4j.version} + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + + log4j + log4j + ${log4j.version} + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + org.assertj + assertj-core + ${assertj.version} + test + + + com.jayway.awaitility + awaitility + ${avaitility.version} + test + + + commons-codec + commons-codec + ${commons-codec.version} + + + org.javamoney + moneta + ${moneta.version} + + + org.owasp.esapi + esapi + ${esapi.version} + + + com.sun.messaging.mq + fscontext + ${fscontext.version} + + + com.codepoetics + protonpack + ${protonpack.version} + + + one.util + streamex + ${streamex.version} + + + io.vavr + vavr + ${vavr.version} + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator-annprocess.version} + + + org.hsqldb + hsqldb + ${hsqldb.version} + runtime + + + + org.asynchttpclient + async-http-client + ${async-http-client.version} + + + com.opencsv + opencsv + ${opencsv.version} + test + + + + org.apache.tika + tika-core + ${tika.version} + + + net.sf.jmimemagic + jmimemagic + ${jmime-magic.version} + + + + + core-java-io-2 + + + src/main/resources + true + + + + + org.codehaus.mojo + exec-maven-plugin + ${exec-maven-plugin.version} + + java + com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed + + -Xmx300m + -XX:+UseParallelGC + -classpath + + com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed + + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven-javadoc-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + + integration + + + + org.codehaus.mojo + exec-maven-plugin + + + + run-benchmarks + + none + + exec + + + test + java + + -classpath + + org.openjdk.jmh.Main + .* + + + + + + + + + + + + + + 1.55 + 1.10 + 3.6.1 + 1.0.3 + 4.1 + 4.01 + 0.4 + 1.8.7 + 4.6-b01 + 1.13 + 0.6.5 + 0.9.0 + 4.1 + + 3.6.1 + 1.7.0 + + + 3.0.0-M1 + 2.4.0 + 2.1.0.1 + 1.19 + 2.4.5 + + 1.18 + 0.1.5 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-io-2/src/main/java/com/baeldung/filereader/FileReaderExample.java b/core-java-modules/core-java-io-2/src/main/java/com/baeldung/filereader/FileReaderExample.java new file mode 100644 index 0000000000..34a8f61615 --- /dev/null +++ b/core-java-modules/core-java-io-2/src/main/java/com/baeldung/filereader/FileReaderExample.java @@ -0,0 +1,57 @@ +package com.baeldung.filereader; + +import java.io.*; + +public class FileReaderExample { + + public static String readAllCharactersOneByOne(Reader reader) throws IOException { + StringBuilder content = new StringBuilder(); + int nextChar; + while ((nextChar = reader.read()) != -1) { + content.append((char) nextChar); + } + return String.valueOf(content); + } + + public static String readMultipleCharacters(Reader reader, int length) throws IOException { + char[] buffer = new char[length]; + int charactersRead = reader.read(buffer, 0, length); + + + if (charactersRead != -1) { + return new String(buffer, 0, charactersRead); + } else { + return ""; + } + } + + public static String readFile(String path) { + FileReader fileReader = null; + try { + fileReader = new FileReader(path); + return readAllCharactersOneByOne(fileReader); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (fileReader != null) { + try { + fileReader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + return null; + } + + public static String readFileUsingTryWithResources(String path) { + try (FileReader fileReader = new FileReader(path)) { + return readAllCharactersOneByOne(fileReader); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + +} \ No newline at end of file diff --git a/core-java-modules/core-java-io-2/src/test/java/com/baeldung/filereader/FileReaderExampleUnitTest.java b/core-java-modules/core-java-io-2/src/test/java/com/baeldung/filereader/FileReaderExampleUnitTest.java new file mode 100644 index 0000000000..4f893fb327 --- /dev/null +++ b/core-java-modules/core-java-io-2/src/test/java/com/baeldung/filereader/FileReaderExampleUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.filereader; + +import org.junit.Assert; +import org.junit.Test; + +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class FileReaderExampleUnitTest { + + + private static final String FILE_PATH = "src/test/resources/HelloWorld.txt"; + + + @Test + public void givenFileReader_whenReadAllCharacters_thenReturnsContent() throws IOException { + String expectedText = "Hello, World!"; + File file = new File(FILE_PATH); + try (FileReader fileReader = new FileReader(file)) { + String content = FileReaderExample.readAllCharactersOneByOne(fileReader); + Assert.assertEquals(expectedText, content); + } + } + + @Test + public void givenFileReader_whenReadMultipleCharacters_thenReturnsContent() throws IOException { + String expectedText = "Hello"; + File file = new File(FILE_PATH); + try (FileReader fileReader = new FileReader(file)) { + String content = FileReaderExample.readMultipleCharacters(fileReader, 5); + Assert.assertEquals(expectedText, content); + } + } + + @Test + public void whenReadFile_thenReturnsContent() { + String expectedText = "Hello, World!"; + String content = FileReaderExample.readFile(FILE_PATH); + Assert.assertEquals(expectedText, content); + } + + @Test + public void whenReadFileUsingTryWithResources_thenReturnsContent() { + String expectedText = "Hello, World!"; + String content = FileReaderExample.readFileUsingTryWithResources(FILE_PATH); + Assert.assertEquals(expectedText, content); + } + +} diff --git a/core-java-modules/core-java-io-2/src/test/resources/HelloWorld.txt b/core-java-modules/core-java-io-2/src/test/resources/HelloWorld.txt new file mode 100644 index 0000000000..b45ef6fec8 --- /dev/null +++ b/core-java-modules/core-java-io-2/src/test/resources/HelloWorld.txt @@ -0,0 +1 @@ +Hello, World! \ No newline at end of file diff --git a/core-java-modules/core-java-io/pom.xml b/core-java-modules/core-java-io/pom.xml index 1a133d2cbe..84bf3baeed 100644 --- a/core-java-modules/core-java-io/pom.xml +++ b/core-java-modules/core-java-io/pom.xml @@ -207,6 +207,21 @@ ${maven.compiler.target} + + + + org.apache.maven.plugins + maven-jar-plugin + ${maven-jar-plugin.version} + + + + true + com.baeldung.resource.MyResourceLoader + + + + @@ -274,6 +289,8 @@ 1.18 0.1.5 + 3.1.0 + \ No newline at end of file diff --git a/core-java-modules/core-java-io/src/main/java/com/baeldung/resource/MyResourceLoader.java b/core-java-modules/core-java-io/src/main/java/com/baeldung/resource/MyResourceLoader.java new file mode 100644 index 0000000000..7512b177df --- /dev/null +++ b/core-java-modules/core-java-io/src/main/java/com/baeldung/resource/MyResourceLoader.java @@ -0,0 +1,42 @@ +package com.baeldung.resource; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.stream.Collectors; + +public class MyResourceLoader { + + private void loadFileWithReader() throws IOException { + + try (FileReader fileReader = new FileReader("src/main/resources/input.txt"); + BufferedReader reader = new BufferedReader(fileReader)) { + String contents = reader.lines() + .collect(Collectors.joining(System.lineSeparator())); + System.out.println(contents); + } + + } + + private void loadFileAsResource() throws IOException { + + try (InputStream inputStream = getClass().getResourceAsStream("/input.txt"); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { + String contents = reader.lines() + .collect(Collectors.joining(System.lineSeparator())); + System.out.println(contents); + } + } + + public static void main(String[] args) throws IOException { + + MyResourceLoader resourceLoader = new MyResourceLoader(); + + resourceLoader.loadFileAsResource(); + resourceLoader.loadFileWithReader(); + + } + +} diff --git a/core-java-modules/core-java-io/src/test/java/org/baeldung/java/io/JavaWriteToFileUnitTest.java b/core-java-modules/core-java-io/src/test/java/org/baeldung/writetofile/JavaWriteToFileUnitTest.java similarity index 99% rename from core-java-modules/core-java-io/src/test/java/org/baeldung/java/io/JavaWriteToFileUnitTest.java rename to core-java-modules/core-java-io/src/test/java/org/baeldung/writetofile/JavaWriteToFileUnitTest.java index 9ff95c4e16..bdc6b34b5c 100644 --- a/core-java-modules/core-java-io/src/test/java/org/baeldung/java/io/JavaWriteToFileUnitTest.java +++ b/core-java-modules/core-java-io/src/test/java/org/baeldung/writetofile/JavaWriteToFileUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.java.io; +package org.baeldung.writetofile; import static org.junit.Assert.assertEquals; diff --git a/core-java-modules/core-java-jndi/pom.xml b/core-java-modules/core-java-jndi/pom.xml index eb363f8598..7f621af21d 100644 --- a/core-java-modules/core-java-jndi/pom.xml +++ b/core-java-modules/core-java-jndi/pom.xml @@ -7,6 +7,7 @@ com.baeldung.jndi core-java-jndi 1.0-SNAPSHOT + core-java-jndi com.baeldung diff --git a/core-java-modules/core-java-jvm/src/main/java/com/baeldung/systemgc/DemoApplication.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/systemgc/DemoApplication.java new file mode 100644 index 0000000000..8bca55c5f0 --- /dev/null +++ b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/systemgc/DemoApplication.java @@ -0,0 +1,33 @@ +package com.baeldung.systemgc; + +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; + +import static java.util.UUID.randomUUID; + +public class DemoApplication { + + private static final Map cache = new HashMap(); + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + while (scanner.hasNext()) { + final String next = scanner.next(); + if ("fill".equals(next)) { + for (int i = 0; i < 1000000; i++) { + cache.put(randomUUID().toString(), randomUUID().toString()); + } + } else if ("invalidate".equals(next)) { + cache.clear(); + } else if ("gc".equals(next)) { + System.gc(); + } else if ("exit".equals(next)) { + System.exit(0); + } else { + System.out.println("unknown"); + } + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lambdas/pom.xml b/core-java-modules/core-java-lambdas/pom.xml index 9e6e81ed40..433db0a9ca 100644 --- a/core-java-modules/core-java-lambdas/pom.xml +++ b/core-java-modules/core-java-lambdas/pom.xml @@ -5,7 +5,7 @@ 4.0.0 core-java-lambdas 0.1.0-SNAPSHOT - core-java + core-java-lambdas jar diff --git a/core-java-modules/core-java-lang-2/.gitignore b/core-java-modules/core-java-lang-2/.gitignore new file mode 100644 index 0000000000..374c8bf907 --- /dev/null +++ b/core-java-modules/core-java-lang-2/.gitignore @@ -0,0 +1,25 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/core-java-modules/core-java-lang-2/README.md b/core-java-modules/core-java-lang-2/README.md new file mode 100644 index 0000000000..88a48661a0 --- /dev/null +++ b/core-java-modules/core-java-lang-2/README.md @@ -0,0 +1,5 @@ +========= + +## Core Java Lang Cookbooks and Examples + +### Relevant Articles: diff --git a/core-java-modules/core-java-lang-2/pom.xml b/core-java-modules/core-java-lang-2/pom.xml new file mode 100644 index 0000000000..4b02e06be4 --- /dev/null +++ b/core-java-modules/core-java-lang-2/pom.xml @@ -0,0 +1,33 @@ + + 4.0.0 + com.baeldung + core-java-lang-2 + 0.1.0-SNAPSHOT + core-java-lang-2 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../../parent-java + + + + + + + core-java-lang-2 + + + src/main/resources + true + + + + + + + + diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/commandlinearguments/CliExample.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/commandlinearguments/CliExample.java new file mode 100644 index 0000000000..d6a7dec8aa --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/commandlinearguments/CliExample.java @@ -0,0 +1,12 @@ +package com.baeldung.commandlinearguments; + +public class CliExample { + + public static void main(String[] args) { + System.out.println("Argument count: " + args.length); + for (int i = 0; i < args.length; i++) { + System.out.println("Argument " + i + ": " + args[i]); + } + } + +} diff --git a/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/commandlinearguments/CliExampleWithVarargs.java b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/commandlinearguments/CliExampleWithVarargs.java new file mode 100644 index 0000000000..899e03416e --- /dev/null +++ b/core-java-modules/core-java-lang-2/src/main/java/com/baeldung/commandlinearguments/CliExampleWithVarargs.java @@ -0,0 +1,12 @@ +package com.baeldung.commandlinearguments; + +public class CliExampleWithVarargs { + + public static void main(String... args) { + System.out.println("Argument count: " + args.length); + for (int i = 0; i < args.length; i++) { + System.out.println("Argument " + i + ": " + args[i]); + } + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/pom.xml b/core-java-modules/core-java-lang-oop-2/pom.xml index 669a37b0f5..b7bd72372b 100644 --- a/core-java-modules/core-java-lang-oop-2/pom.xml +++ b/core-java-modules/core-java-lang-oop-2/pom.xml @@ -14,6 +14,19 @@ ../../parent-java + + + com.h2database + h2 + ${h2.version} + test + + + + + 1.4.199 + + core-java-lang-oop-2 diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/accessmodifiers/publicmodifier/ListOfThree.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/accessmodifiers/publicmodifier/ListOfThree.java new file mode 100644 index 0000000000..2ded0ba5d3 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/accessmodifiers/publicmodifier/ListOfThree.java @@ -0,0 +1,31 @@ +package com.baeldung.accessmodifiers.publicmodifier; + +import java.util.AbstractList; +import java.util.Arrays; + +public class ListOfThree extends AbstractList { + + private static final int LENGTH = 3; + private Object[] elements; + + public ListOfThree(E[] data) { + if(data == null + || data.length != LENGTH) + throw new IllegalArgumentException(); + + this.elements = Arrays.copyOf(data, data.length); //shallow copy + + } + + @Override + @SuppressWarnings("unchecked") + public E get(int index) { + return (E)elements[index]; + } + + @Override + public int size() { + return LENGTH; + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/accessmodifiers/publicmodifier/SpecialCharacters.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/accessmodifiers/publicmodifier/SpecialCharacters.java new file mode 100644 index 0000000000..5556e9aa57 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/accessmodifiers/publicmodifier/SpecialCharacters.java @@ -0,0 +1,7 @@ +package com.baeldung.accessmodifiers.publicmodifier; + +public class SpecialCharacters { + + public static final String SLASH = "/"; + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/accessmodifiers/publicmodifier/Student.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/accessmodifiers/publicmodifier/Student.java new file mode 100644 index 0000000000..83a0dcb30f --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/accessmodifiers/publicmodifier/Student.java @@ -0,0 +1,67 @@ +package com.baeldung.accessmodifiers.publicmodifier; + +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Date; + +public class Student { + + private StudentGrade grade; //new data representation +// private int grade; //old data representation + private String name; + private int age; + + public void setGrade(int grade) { + this.grade = new StudentGrade(grade); + } + + public int getGrade() { + return this.grade.getGrade().intValue(); //int is returned for backward compatibility + } + + public Connection getConnection() throws SQLException { + + final String URL = "jdbc:h2:~/test"; + return DriverManager.getConnection(URL, "sa", ""); + + } + + public void setAge(int age) { + if (age < 0 || age > 150) { + throw new IllegalArgumentException(); + } + + this.age = age; + } + + public int getAge() { + return age; + } + + @Override + public String toString() { + return this.name; + } + + private class StudentGrade { + private BigDecimal grade = BigDecimal.ZERO; + private Date updatedAt; + + public StudentGrade(int grade) { + this.grade = new BigDecimal(grade); + this.updatedAt = new Date(); + } + + public BigDecimal getGrade() { + return grade; + } + + public Date getDate() { + return updatedAt; + } + + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/copyconstructor/Employee.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/copyconstructor/Employee.java new file mode 100644 index 0000000000..7ad445e8ee --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/copyconstructor/Employee.java @@ -0,0 +1,30 @@ +package com.baeldung.copyconstructor; + +import java.util.Date; + +public class Employee { + + protected int id; + protected String name; + protected Date startDate; + + public Employee(int id, String name, Date startDate) { + this.id = id; + this.name = name; + this.startDate = startDate; + } + + public Employee(Employee employee) { + this.id = employee.id; + this.name = employee.name; + this.startDate = new Date(employee.startDate.getTime()); + } + + Date getStartDate() { + return startDate; + } + + public Employee copy() { + return new Employee(this); + } +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/copyconstructor/Manager.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/copyconstructor/Manager.java new file mode 100644 index 0000000000..97b8580b8e --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/copyconstructor/Manager.java @@ -0,0 +1,31 @@ +package com.baeldung.copyconstructor; + +import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; + +public class Manager extends Employee { + + private List directReports; + + public Manager(int id, String name, Date startDate, List directReports) { + super(id, name, startDate); + this.directReports = directReports; + } + + public Manager(Manager manager) { + super(manager.id, manager.name, manager.startDate); + this.directReports = manager.directReports.stream() + .collect(Collectors.toList()); + } + + @Override + public Employee copy() { + return new Manager(this); + } + + List getDirectReport() { + return this.directReports; + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/core/modifiers/Employee.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/core/modifiers/Employee.java new file mode 100644 index 0000000000..6ec68d6ebb --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/core/modifiers/Employee.java @@ -0,0 +1,59 @@ +package com.baeldung.core.modifiers; + +public class Employee { + + private String privateId; + private String name; + private boolean manager; + + public Employee(String id, String name) { + setPrivateId(id); + setName(name); + } + + private Employee(String id, String name, boolean managerAttribute) { + this.privateId = id; + this.name = name; + this.privateId = id + "_ID-MANAGER"; + } + + public void setPrivateId(String customId) { + if (customId.endsWith("_ID")) { + this.privateId = customId; + } else { + this.privateId = customId + "_ID"; + } + } + + public String getPrivateId() { + return privateId; + } + + public boolean isManager() { + return manager; + } + + public void elevateToManager() { + if ("Carl".equals(this.name)) { + setManager(true); + } + } + + private void setManager(boolean manager) { + this.manager = manager; + } + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public static Employee buildManager(String id, String name) { + return new Employee(id, name, true); + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/core/modifiers/ExampleClass.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/core/modifiers/ExampleClass.java new file mode 100644 index 0000000000..41f0b7a690 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/core/modifiers/ExampleClass.java @@ -0,0 +1,10 @@ +package com.baeldung.core.modifiers; + +public class ExampleClass { + + public static void main(String[] args) { + Employee employee = new Employee("Bob","ABC123"); + employee.setPrivateId("BCD234"); + System.out.println(employee.getPrivateId()); + } +} diff --git a/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/core/modifiers/PublicOuterClass.java b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/core/modifiers/PublicOuterClass.java new file mode 100644 index 0000000000..329ebf3bb6 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/main/java/com/baeldung/core/modifiers/PublicOuterClass.java @@ -0,0 +1,16 @@ +package com.baeldung.core.modifiers; + +public class PublicOuterClass { + + public PrivateInnerClass getInnerClassInstance() { + PrivateInnerClass myPrivateClassInstance = this.new PrivateInnerClass(); + myPrivateClassInstance.id = "ID1"; + myPrivateClassInstance.name = "Bob"; + return myPrivateClassInstance; + } + + private class PrivateInnerClass { + public String name; + public String id; + } +} diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/accessmodifiers/PublicAccessModifierUnitTest.java b/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/accessmodifiers/PublicAccessModifierUnitTest.java new file mode 100644 index 0000000000..a2d891ac93 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/accessmodifiers/PublicAccessModifierUnitTest.java @@ -0,0 +1,93 @@ +package com.baeldung.accessmodifiers; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestInstance.Lifecycle; +import com.baeldung.accessmodifiers.publicmodifier.ListOfThree; +import com.baeldung.accessmodifiers.publicmodifier.Student; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.math.BigDecimal; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@TestInstance(Lifecycle.PER_CLASS) +public class PublicAccessModifierUnitTest { + + @Test + public void whenUsingBigDecimalIntValueMethod_correspondingIntIsReturned() { + assertEquals(0, new BigDecimal(0).intValue()); //instance member + } + + @Test + public void whenUsingIntegerMaxValueField_maxPossibleIntValueIsReturned() { + assertEquals(2147483647, Integer.MAX_VALUE); //static field + } + + @Test + public void whenChangingStudentInternalRepresentation_clientCodeWillNotBreak() { + + Student student = new Student(); + student.setGrade(100); + + assertEquals(100, student.getGrade()); + } + + @Test + public void whenUsingEntrySet_keyValuePairsAreReturned() { + + Map mapObject = new HashMap(); + mapObject.put("name", "Alex"); + + for(Map.Entry entry : mapObject.entrySet()) { + assertEquals("name", entry.getKey()); + assertEquals("Alex", entry.getValue()); + } + + } + + @Test + public void whenUsingStringToLowerCase_stringTurnsToLowerCase() { + assertEquals("alex", "ALEX".toLowerCase()); + } + + @Test + public void whenParsingStringOne_parseIntReturns1() { + assertEquals(1, Integer.parseInt("1")); + } + + @Test + public void whenConnectingToH2_connectionInstanceIsReturned() throws SQLException { + + final String url = "jdbc:h2:~/test"; + Connection conn = DriverManager.getConnection(url, "sa", ""); + assertNotNull(conn); + } + + @Test + public void whenCreatingCustomList_concreteAndInheritedMethodsWork() { + + String[] dataSet1 = new String[] {"zero", "one", "two"}; + + List list1 = new ListOfThree(dataSet1); + + //our implemented methods + assertEquals("one", list1.get(1)); + assertEquals(3, list1.size()); + + //inherited implementations + assertEquals(1, list1.indexOf("one")); + + String[] dataSet2 = new String[] {"two", "zero", "one"}; + List list2 = new ListOfThree(dataSet2); + + assertTrue(list1.containsAll(list2)); + } + +} diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/copyconstructor/EmployeeUnitTest.java b/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/copyconstructor/EmployeeUnitTest.java new file mode 100644 index 0000000000..19a4001b62 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/copyconstructor/EmployeeUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.copyconstructor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +import java.util.Date; + +import org.junit.Test; + +public class EmployeeUnitTest { + @Test + public void givenCopyConstructor_whenDeepCopy_thenDistinct() { + Date d1 = new Date(123); + Employee e1 = new Employee(1, "Baeldung", d1); + Employee e2 = new Employee(e1); + assertEquals(d1, e1.getStartDate()); + assertEquals(d1, e2.getStartDate()); + + d1.setTime(456); + assertEquals(d1, e1.getStartDate()); + assertNotEquals(d1, e2.getStartDate()); + } + + @Test + public void givenCopyMethod_whenCopy_thenDistinct() { + Date d1 = new Date(123); + Employee e1 = new Employee(1, "Baeldung", d1); + Employee e2 = e1.copy(); + assertEquals(d1, e1.getStartDate()); + assertEquals(d1, e2.getStartDate()); + + d1.setTime(456); + assertEquals(d1, e1.getStartDate()); + assertNotEquals(d1, e2.getStartDate()); + } +} diff --git a/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/copyconstructor/ManagerUnitTest.java b/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/copyconstructor/ManagerUnitTest.java new file mode 100644 index 0000000000..ef9f261360 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-2/src/test/java/com/baeldung/copyconstructor/ManagerUnitTest.java @@ -0,0 +1,67 @@ +package com.baeldung.copyconstructor; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.junit.Test; + +public class ManagerUnitTest { + @Test + public void givenCopyConstructor_whenDeepCopy_thenDistinct() { + Date startDate = new Date(123); + Employee e1 = new Employee(1, "Baeldung", startDate); + Employee e2 = new Employee(e1); + List directReports = new ArrayList(); + directReports.add(e1); + directReports.add(e2); + + Manager m1 = new Manager(1, "Baeldung Manager", startDate, directReports); + Manager m2 = new Manager(m1); + List directReports1 = m1.getDirectReport(); + List directReports2 = m2.getDirectReport(); + assertEquals(directReports1.size(), directReports2.size()); + assertArrayEquals(directReports1.toArray(), directReports2.toArray()); + + // clear m1's direct reports list. m2's list should not be affected + directReports.clear(); + directReports1 = m1.getDirectReport(); + directReports2 = m2.getDirectReport(); + assertEquals(0, directReports1.size()); + assertEquals(2, directReports2.size()); + + } + + @Test + public void givenCopyMethod_whenCopy_thenDistinct() { + Date startDate = new Date(123); + Employee e1 = new Employee(1, "Baeldung", startDate); + Employee e2 = new Employee(e1); + List directReports = new ArrayList(); + directReports.add(e1); + directReports.add(e2); + + // a Manager object whose declaration type is Employee. + Employee source = new Manager(1, "Baeldung Manager", startDate, directReports); + Employee clone = source.copy(); + + // after copy, clone should be still a Manager object. + assertTrue(clone instanceof Manager); + List directReports1 = ((Manager) source).getDirectReport(); + List directReports2 = ((Manager) clone).getDirectReport(); + assertEquals(directReports1.size(), directReports2.size()); + assertArrayEquals(directReports1.toArray(), directReports2.toArray()); + + // clear source's direct reports list. clone's list should not be affected + directReports.clear(); + directReports1 = ((Manager) source).getDirectReport(); + directReports2 = ((Manager) clone).getDirectReport(); + assertEquals(0, directReports1.size()); + assertEquals(2, directReports2.size()); + + } +} diff --git a/core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/booleanoperators/Car.java b/core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/booleanoperators/Car.java new file mode 100644 index 0000000000..37fb139917 --- /dev/null +++ b/core-java-modules/core-java-lang-operators/src/main/java/com/baeldung/booleanoperators/Car.java @@ -0,0 +1,36 @@ +package com.baeldung.booleanoperators; + +public class Car { + + private boolean diesel; + private boolean manual; + + public Car(boolean diesel, boolean manual) { + this.diesel = diesel; + this.manual = manual; + } + + public boolean isDiesel() { + return diesel; + } + + public boolean isManual() { + return manual; + } + + static Car dieselAndManualCar() { + return new Car(true, true); + } + + static Car dieselAndAutomaticCar() { + return new Car(true, false); + } + + static Car oilAndManualCar() { + return new Car(false, true); + } + + static Car oilAndAutomaticCar() { + return new Car(false, false); + } +} diff --git a/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/booleanoperators/XorUnitTest.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/booleanoperators/XorUnitTest.java new file mode 100644 index 0000000000..efe38c6f45 --- /dev/null +++ b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/booleanoperators/XorUnitTest.java @@ -0,0 +1,69 @@ +package com.baeldung.booleanoperators; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class XorUnitTest { + + @Test + void givenDieselManualCar_whenXorOldSchool_thenFalse() { + Car car = Car.dieselAndManualCar(); + boolean dieselXorManual = (car.isDiesel() && !car.isManual()) || (!car.isDiesel() && car.isManual()); + assertThat(dieselXorManual).isFalse(); + } + + @Test + void givenDieselAutomaticCar_whenXorOldSchool_thenTrue() { + Car car = Car.dieselAndAutomaticCar(); + boolean dieselXorManual = (car.isDiesel() && !car.isManual()) || (!car.isDiesel() && car.isManual()); + assertThat(dieselXorManual).isTrue(); + } + + @Test + void givenNonDieselManualCar_whenXorOldSchool_thenTrue() { + Car car = Car.oilAndManualCar(); + boolean dieselXorManual = (car.isDiesel() && !car.isManual()) || (!car.isDiesel() && car.isManual()); + assertThat(dieselXorManual).isTrue(); + } + + @Test + void givenNonDieselAutomaticCar_whenXorOldSchool_thenFalse() { + Car car = Car.oilAndAutomaticCar(); + boolean dieselXorManual = (car.isDiesel() && !car.isManual()) || (!car.isDiesel() && car.isManual()); + assertThat(dieselXorManual).isFalse(); + } + + @Test + void givenDieselManualCar_whenXor_thenFalse() { + Car car = Car.dieselAndManualCar(); + boolean dieselXorManual = car.isDiesel() ^ car.isManual(); + assertThat(dieselXorManual).isFalse(); + } + + @Test + void givenDieselAutomaticCar_whenXor_thenTrue() { + Car car = Car.dieselAndAutomaticCar(); + boolean dieselXorManual = car.isDiesel() ^ car.isManual(); + assertThat(dieselXorManual).isTrue(); + } + + @Test + void givenNonDieselManualCar_whenXor_thenTrue() { + Car car = Car.oilAndManualCar(); + boolean dieselXorManual = car.isDiesel() ^ car.isManual(); + assertThat(dieselXorManual).isTrue(); + } + + @Test + void givenNonDieselAutomaticCar_whenXor_thenFalse() { + Car car = Car.oilAndAutomaticCar(); + boolean dieselXorManual = car.isDiesel() ^ car.isManual(); + assertThat(dieselXorManual).isFalse(); + } + + @Test + void givenNumbersOneAndThree_whenXor_thenTwo() { + assertThat(1 ^ 3).isEqualTo(2); + } +} diff --git a/core-java-modules/core-java-lang/README.md b/core-java-modules/core-java-lang/README.md index 74936eac21..f3b6d3d8e5 100644 --- a/core-java-modules/core-java-lang/README.md +++ b/core-java-modules/core-java-lang/README.md @@ -3,13 +3,10 @@ ## Core Java Lang Cookbooks and Examples ### Relevant Articles: -- [Guide to Java Reflection](http://www.baeldung.com/java-reflection) + - [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode) - [Chained Exceptions in Java](http://www.baeldung.com/java-chained-exceptions) -- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection) - [Iterating Over Enum Values in Java](http://www.baeldung.com/java-enum-iteration) -- [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params) -- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies) - [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization) - [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator) - [Comparator and Comparable in Java](http://www.baeldung.com/java-comparator-comparable) diff --git a/core-java-modules/core-java-networking/src/main/java/com/baeldung/http/FullResponseBuilder.java b/core-java-modules/core-java-networking/src/main/java/com/baeldung/httprequest/FullResponseBuilder.java similarity index 98% rename from core-java-modules/core-java-networking/src/main/java/com/baeldung/http/FullResponseBuilder.java rename to core-java-modules/core-java-networking/src/main/java/com/baeldung/httprequest/FullResponseBuilder.java index 394255bd70..cc9d79aa65 100644 --- a/core-java-modules/core-java-networking/src/main/java/com/baeldung/http/FullResponseBuilder.java +++ b/core-java-modules/core-java-networking/src/main/java/com/baeldung/httprequest/FullResponseBuilder.java @@ -1,4 +1,4 @@ -package com.baeldung.http; +package com.baeldung.httprequest; import java.io.BufferedReader; import java.io.IOException; diff --git a/core-java-modules/core-java-networking/src/main/java/com/baeldung/http/ParameterStringBuilder.java b/core-java-modules/core-java-networking/src/main/java/com/baeldung/httprequest/ParameterStringBuilder.java similarity index 95% rename from core-java-modules/core-java-networking/src/main/java/com/baeldung/http/ParameterStringBuilder.java rename to core-java-modules/core-java-networking/src/main/java/com/baeldung/httprequest/ParameterStringBuilder.java index bed4195faa..f91ab332c7 100644 --- a/core-java-modules/core-java-networking/src/main/java/com/baeldung/http/ParameterStringBuilder.java +++ b/core-java-modules/core-java-networking/src/main/java/com/baeldung/httprequest/ParameterStringBuilder.java @@ -1,4 +1,4 @@ -package com.baeldung.http; +package com.baeldung.httprequest; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; diff --git a/core-java-modules/core-java-networking/src/test/java/com/baeldung/http/HttpRequestLiveTest.java b/core-java-modules/core-java-networking/src/test/java/com/baeldung/httprequest/HttpRequestLiveTest.java similarity index 97% rename from core-java-modules/core-java-networking/src/test/java/com/baeldung/http/HttpRequestLiveTest.java rename to core-java-modules/core-java-networking/src/test/java/com/baeldung/httprequest/HttpRequestLiveTest.java index bd6c0a4410..77bf9bc8db 100644 --- a/core-java-modules/core-java-networking/src/test/java/com/baeldung/http/HttpRequestLiveTest.java +++ b/core-java-modules/core-java-networking/src/test/java/com/baeldung/httprequest/HttpRequestLiveTest.java @@ -1,8 +1,11 @@ -package com.baeldung.http; +package com.baeldung.httprequest; import org.apache.commons.lang3.StringUtils; import org.junit.Test; +import com.baeldung.httprequest.FullResponseBuilder; +import com.baeldung.httprequest.ParameterStringBuilder; + import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; diff --git a/core-java-modules/core-java-optional/pom.xml b/core-java-modules/core-java-optional/pom.xml index eb981c0907..ca6158ef5a 100644 --- a/core-java-modules/core-java-optional/pom.xml +++ b/core-java-modules/core-java-optional/pom.xml @@ -3,6 +3,7 @@ core-java-optional 0.1.0-SNAPSHOT jar + core-java-optional com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-os/src/main/java/com/baeldung/system/exit/SystemExitExample.java b/core-java-modules/core-java-os/src/main/java/com/baeldung/system/exit/SystemExitExample.java new file mode 100644 index 0000000000..a9738a0448 --- /dev/null +++ b/core-java-modules/core-java-os/src/main/java/com/baeldung/system/exit/SystemExitExample.java @@ -0,0 +1,20 @@ +package com.baeldung.system.exit; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; + +public class SystemExitExample { + + public void readFile() { + try { + BufferedReader br = new BufferedReader(new FileReader("file.txt")); + System.out.println(br.readLine()); + br.close(); + } catch (IOException e) { + System.exit(2); + } finally { + System.out.println("Exiting the program"); + } + } +} diff --git a/core-java-modules/core-java-os/src/test/java/com/baeldung/system/exit/SystemExitUnitTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/system/exit/SystemExitUnitTest.java new file mode 100644 index 0000000000..6d5f9c2f34 --- /dev/null +++ b/core-java-modules/core-java-os/src/test/java/com/baeldung/system/exit/SystemExitUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.system.exit; + +import static org.junit.Assert.assertEquals; + +import java.security.Permission; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class SystemExitUnitTest { + + protected static class ExitException extends SecurityException { + + private static final long serialVersionUID = 1L; + public final int status; + + public ExitException(int status) { + this.status = status; + } + } + + private static class NoExitSecurityManager extends SecurityManager { + @Override + public void checkPermission(Permission perm) { + } + + @Override + public void checkPermission(Permission perm, Object context) { + } + + @Override + public void checkExit(int status) { + super.checkExit(status); + throw new ExitException(status); + } + } + + private SecurityManager securityManager; + + private SystemExitExample example; + + @Before + public void setUp() throws Exception { + example = new SystemExitExample(); + securityManager = System.getSecurityManager(); + System.setSecurityManager(new NoExitSecurityManager()); + } + + @After + public void tearDown() throws Exception { + System.setSecurityManager(securityManager); + } + + @Test + public void testExit() throws Exception { + try { + example.readFile(); + } catch (ExitException e) { + assertEquals("Exit status", 2, e.status); + } + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-reflection/README.MD b/core-java-modules/core-java-reflection/README.MD index c8766d6858..e46a97cd3d 100644 --- a/core-java-modules/core-java-reflection/README.MD +++ b/core-java-modules/core-java-reflection/README.MD @@ -1,3 +1,8 @@ ## Relevant Articles - [Void Type in Java](https://www.baeldung.com/java-void-type) +- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection) +- [Guide to Java Reflection](http://www.baeldung.com/java-reflection) +- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection) +- [Changing Annotation Parameters At Runtime](http://www.baeldung.com/java-reflection-change-annotation-params) +- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies) diff --git a/core-java-modules/core-java-reflection/pom.xml b/core-java-modules/core-java-reflection/pom.xml index e6c7f81d6c..b3c3390df8 100644 --- a/core-java-modules/core-java-reflection/pom.xml +++ b/core-java-modules/core-java-reflection/pom.xml @@ -23,7 +23,30 @@ + + core-java-reflection + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + -parameters + + + + + + 3.8.0 3.10.0 \ No newline at end of file diff --git a/core-java-modules/core-java-lang/src/main/java/com/baeldung/dynamicproxy/DynamicInvocationHandler.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/dynamicproxy/DynamicInvocationHandler.java similarity index 100% rename from core-java-modules/core-java-lang/src/main/java/com/baeldung/dynamicproxy/DynamicInvocationHandler.java rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/dynamicproxy/DynamicInvocationHandler.java diff --git a/core-java-modules/core-java-lang/src/main/java/com/baeldung/dynamicproxy/TimingDynamicInvocationHandler.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/dynamicproxy/TimingDynamicInvocationHandler.java similarity index 100% rename from core-java-modules/core-java-lang/src/main/java/com/baeldung/dynamicproxy/TimingDynamicInvocationHandler.java rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/dynamicproxy/TimingDynamicInvocationHandler.java diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/reflect/Person.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflect/Person.java similarity index 100% rename from core-java-modules/core-java-8/src/main/java/com/baeldung/reflect/Person.java rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflect/Person.java diff --git a/core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/Animal.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/Animal.java similarity index 100% rename from core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/Animal.java rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/Animal.java diff --git a/core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/Bird.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/Bird.java similarity index 100% rename from core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/Bird.java rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/Bird.java diff --git a/core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/DynamicGreeter.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/DynamicGreeter.java similarity index 100% rename from core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/DynamicGreeter.java rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/DynamicGreeter.java diff --git a/core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/Eating.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/Eating.java similarity index 100% rename from core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/Eating.java rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/Eating.java diff --git a/core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/Goat.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/Goat.java similarity index 100% rename from core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/Goat.java rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/Goat.java diff --git a/core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/Greeter.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/Greeter.java similarity index 100% rename from core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/Greeter.java rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/Greeter.java diff --git a/core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/GreetingAnnotation.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/GreetingAnnotation.java similarity index 100% rename from core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/GreetingAnnotation.java rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/GreetingAnnotation.java diff --git a/core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/Greetings.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/Greetings.java similarity index 100% rename from core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/Greetings.java rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/Greetings.java diff --git a/core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/Locomotion.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/Locomotion.java similarity index 100% rename from core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/Locomotion.java rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/Locomotion.java diff --git a/core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/Operations.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/Operations.java similarity index 100% rename from core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/Operations.java rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/Operations.java diff --git a/core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/Person.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/Person.java similarity index 100% rename from core-java-modules/core-java-lang/src/main/java/com/baeldung/java/reflection/Person.java rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/java/reflection/Person.java diff --git a/core-java-modules/core-java-lang/src/test/java/com/baeldung/dynamicproxy/DynamicProxyIntegrationTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/dynamicproxy/DynamicProxyIntegrationTest.java similarity index 100% rename from core-java-modules/core-java-lang/src/test/java/com/baeldung/dynamicproxy/DynamicProxyIntegrationTest.java rename to core-java-modules/core-java-reflection/src/test/java/com/baeldung/dynamicproxy/DynamicProxyIntegrationTest.java diff --git a/core-java-modules/core-java-8/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java similarity index 100% rename from core-java-modules/core-java-8/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java rename to core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java diff --git a/core-java-modules/core-java-lang/src/test/java/com/baeldung/java/reflection/OperationsUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/java/reflection/OperationsUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang/src/test/java/com/baeldung/java/reflection/OperationsUnitTest.java rename to core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/java/reflection/OperationsUnitTest.java diff --git a/core-java-modules/core-java-lang/src/test/java/com/baeldung/java/reflection/ReflectionUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/java/reflection/ReflectionUnitTest.java similarity index 100% rename from core-java-modules/core-java-lang/src/test/java/com/baeldung/java/reflection/ReflectionUnitTest.java rename to core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/java/reflection/ReflectionUnitTest.java diff --git a/core-java-modules/core-java-security-manager/pom.xml b/core-java-modules/core-java-security-manager/pom.xml new file mode 100644 index 0000000000..51d5e7d78f --- /dev/null +++ b/core-java-modules/core-java-security-manager/pom.xml @@ -0,0 +1,34 @@ + + 4.0.0 + core-java-security-manager + 0.1.0-SNAPSHOT + jar + core-java-security-manager + + + com.baeldung.core-java-modules + core-java-modules + 1.0.0-SNAPSHOT + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + + UTF-8 + 1.8 + 1.8 + + diff --git a/core-java-modules/core-java-security-manager/src/main/java/com/baeldung/security/manager/CustomPermission.java b/core-java-modules/core-java-security-manager/src/main/java/com/baeldung/security/manager/CustomPermission.java new file mode 100644 index 0000000000..5f9c43336f --- /dev/null +++ b/core-java-modules/core-java-security-manager/src/main/java/com/baeldung/security/manager/CustomPermission.java @@ -0,0 +1,13 @@ +package com.baeldung.security.manager; + +import java.security.BasicPermission; + +public class CustomPermission extends BasicPermission { + public CustomPermission(String name) { + super(name); + } + + public CustomPermission(String name, String actions) { + super(name, actions); + } +} diff --git a/core-java-modules/core-java-security-manager/src/main/java/com/baeldung/security/manager/Service.java b/core-java-modules/core-java-security-manager/src/main/java/com/baeldung/security/manager/Service.java new file mode 100644 index 0000000000..1b9f14e3b8 --- /dev/null +++ b/core-java-modules/core-java-security-manager/src/main/java/com/baeldung/security/manager/Service.java @@ -0,0 +1,18 @@ +package com.baeldung.security.manager; + +public class Service { + + public static final String OPERATION = "my-operation"; + + public void operation() { + SecurityManager securityManager = System.getSecurityManager(); + if (securityManager != null) { + securityManager.checkPermission(new CustomPermission(OPERATION)); + } + System.out.println("Operation is executed"); + } + + public static void main(String[] args) { + new Service().operation(); + } +} diff --git a/core-java-modules/core-java-security-manager/src/test/java/com/baeldung/security/manager/SecurityManagerUnitTest.java b/core-java-modules/core-java-security-manager/src/test/java/com/baeldung/security/manager/SecurityManagerUnitTest.java new file mode 100644 index 0000000000..a845f233b5 --- /dev/null +++ b/core-java-modules/core-java-security-manager/src/test/java/com/baeldung/security/manager/SecurityManagerUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.security.manager; + +import org.junit.Test; + +import java.net.URL; +import java.security.AccessControlException; +import java.util.concurrent.Callable; + +public class SecurityManagerUnitTest { + + @Test(expected = AccessControlException.class) + public void whenSecurityManagerIsActive_thenNetworkIsNotAccessibleByDefault() throws Exception { + doTest(() -> { + new URL("http://www.google.com").openConnection().connect(); + return null; + }); + } + + @Test(expected = AccessControlException.class) + public void whenUnauthorizedClassTriesToAccessProtectedOperation_thenAnExceptionIsThrown() throws Exception { + doTest(() -> { + new Service().operation(); + return null; + }); + } + + private void doTest(Callable action) throws Exception { + System.setSecurityManager(new SecurityManager()); + try { + action.call(); + } finally { + System.setSecurityManager(null); + } + } +} diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java b/core-java-modules/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java index dcf186de93..2659b29491 100644 --- a/core-java-modules/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java +++ b/core-java-modules/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java @@ -3,6 +3,7 @@ package com.baeldung.uuid; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.Arrays; import java.util.UUID; public class UUIDGenerator { @@ -65,9 +66,9 @@ public class UUIDGenerator { try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { - throw new InternalError("MD5 not supported", nsae); + throw new InternalError("SHA-1 not supported", nsae); } - byte[] bytes = md.digest(name); + byte[] bytes = Arrays.copyOfRange(md.digest(name), 0, 16); bytes[6] &= 0x0f; /* clear version */ bytes[6] |= 0x50; /* set to version 5 */ bytes[8] &= 0x3f; /* clear variant */ diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index ecf1f4147e..082ffbef53 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -19,6 +19,7 @@ core-java-optional core-java-lang-operators core-java-networking-2 + core-java-security-manager diff --git a/gradle-5/build.gradle b/gradle-5/build.gradle new file mode 100644 index 0000000000..a728845dff --- /dev/null +++ b/gradle-5/build.gradle @@ -0,0 +1,54 @@ +plugins { + id "application" +} +apply plugin :"java" + +description = "Java MainClass execution examples" +group = "com.baeldung" +version = "0.0.1" +sourceCompatibility = "1.8" +targetCompatibility = "1.8" + +ext { + javaMainClass = "com.baeldung.gradle.exec.MainClass" +} + +jar { + manifest { + attributes( + "Main-Class": javaMainClass + ) + } +} + +application { + mainClassName = javaMainClass +} + +task runWithJavaExec(type: JavaExec) { + group = "Execution" + description = "Run the main class with JavaExecTask" + classpath = sourceSets.main.runtimeClasspath + main = javaMainClass +} + +task runWithExec(type: Exec) { + dependsOn build + group = "Execution" + description = "Run the main class with ExecTask" + commandLine "java", "-classpath", sourceSets.main.runtimeClasspath.getAsPath(), javaMainClass +} + +task runWithExecJarExecutable(type: Exec) { + dependsOn jar + group = "Execution" + description = "Run the output executable jar with ExecTask" + commandLine "java", "-jar", jar.archiveFile.get() +} + +task runWithExecJarOnClassPath(type: Exec) { + dependsOn jar + group = "Execution" + description = "Run the mainClass from the output jar in classpath with ExecTask" + commandLine "java", "-classpath", jar.archiveFile.get() , javaMainClass +} \ No newline at end of file diff --git a/gradle-5/gradle/wrapper/gradle-wrapper.jar b/gradle-5/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..736fb7d3f9 Binary files /dev/null and b/gradle-5/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle-5/gradle/wrapper/gradle-wrapper.properties b/gradle-5/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..b33419deee --- /dev/null +++ b/gradle-5/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-5.5.1-bin.zip diff --git a/gradle-5/gradlew b/gradle-5/gradlew new file mode 100755 index 0000000000..27309d9231 --- /dev/null +++ b/gradle-5/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## 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 + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradle-5/gradlew.bat b/gradle-5/gradlew.bat new file mode 100644 index 0000000000..832fdb6079 --- /dev/null +++ b/gradle-5/gradlew.bat @@ -0,0 +1,90 @@ +@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 +if "%@eval[2+2]" == "4" goto 4NT_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=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +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/gradle-5/src/main/java/com/baeldung/gradle/exec/MainClass.java b/gradle-5/src/main/java/com/baeldung/gradle/exec/MainClass.java new file mode 100644 index 0000000000..1e0c05389c --- /dev/null +++ b/gradle-5/src/main/java/com/baeldung/gradle/exec/MainClass.java @@ -0,0 +1,8 @@ +package com.baeldung.gradle.exec; + +public class MainClass { + + public static void main(String[] args) { + System.out.println("Goodbye cruel world ..."); + } +} diff --git a/guava-collections/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/maps/initialize/GuavaMapInitializeUnitTest.java similarity index 95% rename from guava-collections/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java rename to guava-collections/src/test/java/org/baeldung/guava/maps/initialize/GuavaMapInitializeUnitTest.java index 69a7505316..2414afb720 100644 --- a/guava-collections/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java +++ b/guava-collections/src/test/java/org/baeldung/guava/maps/initialize/GuavaMapInitializeUnitTest.java @@ -1,4 +1,4 @@ -package org.baeldung.guava; +package org.baeldung.guava.maps.initialize; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.*; diff --git a/jackson-2/README.md b/jackson-2/README.md index bb2a58483f..920eaa91e8 100644 --- a/jackson-2/README.md +++ b/jackson-2/README.md @@ -11,3 +11,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Working with Tree Model Nodes in Jackson](https://www.baeldung.com/jackson-json-node-tree-model) - [Converting JSON to CSV in Java](https://www.baeldung.com/java-converting-json-to-csv) - [Compare Two JSON Objects with Jackson](https://www.baeldung.com/jackson-compare-two-json-objects) +- [Calling Default Serializer from Custom Serializer in Jackson](https://www.baeldung.com/jackson-call-default-serializer-from-custom-serializer) diff --git a/jackson-simple/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java b/jackson-simple/src/test/java/com/baeldung/jackson/ignore/JacksonSerializationIgnoreUnitTest.java similarity index 98% rename from jackson-simple/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java rename to jackson-simple/src/test/java/com/baeldung/jackson/ignore/JacksonSerializationIgnoreUnitTest.java index 146f274380..da8b464d03 100644 --- a/jackson-simple/src/test/java/com/baeldung/jackson/test/JacksonSerializationIgnoreUnitTest.java +++ b/jackson-simple/src/test/java/com/baeldung/jackson/ignore/JacksonSerializationIgnoreUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jackson.test; +package com.baeldung.jackson.ignore; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; @@ -15,9 +15,9 @@ import com.baeldung.jackson.dtos.MyDtoIncludeNonDefault; import com.baeldung.jackson.dtos.MyDtoWithFilter; import com.baeldung.jackson.dtos.MyDtoWithSpecialField; import com.baeldung.jackson.dtos.MyMixInForIgnoreType; -import com.baeldung.jackson.dtos.ignore.MyDtoIgnoreField; -import com.baeldung.jackson.dtos.ignore.MyDtoIgnoreFieldByName; -import com.baeldung.jackson.dtos.ignore.MyDtoIgnoreNull; +import com.baeldung.jackson.ignore.dtos.MyDtoIgnoreField; +import com.baeldung.jackson.ignore.dtos.MyDtoIgnoreFieldByName; +import com.baeldung.jackson.ignore.dtos.MyDtoIgnoreNull; import com.baeldung.jackson.serialization.MyDtoNullKeySerializer; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonGenerator; diff --git a/jackson-simple/src/test/java/com/baeldung/jackson/dtos/ignore/MyDtoIgnoreField.java b/jackson-simple/src/test/java/com/baeldung/jackson/ignore/dtos/MyDtoIgnoreField.java similarity index 94% rename from jackson-simple/src/test/java/com/baeldung/jackson/dtos/ignore/MyDtoIgnoreField.java rename to jackson-simple/src/test/java/com/baeldung/jackson/ignore/dtos/MyDtoIgnoreField.java index f573501e85..8cbcb773cc 100644 --- a/jackson-simple/src/test/java/com/baeldung/jackson/dtos/ignore/MyDtoIgnoreField.java +++ b/jackson-simple/src/test/java/com/baeldung/jackson/ignore/dtos/MyDtoIgnoreField.java @@ -1,4 +1,4 @@ -package com.baeldung.jackson.dtos.ignore; +package com.baeldung.jackson.ignore.dtos; import com.fasterxml.jackson.annotation.JsonIgnore; diff --git a/jackson-simple/src/test/java/com/baeldung/jackson/dtos/ignore/MyDtoIgnoreFieldByName.java b/jackson-simple/src/test/java/com/baeldung/jackson/ignore/dtos/MyDtoIgnoreFieldByName.java similarity index 95% rename from jackson-simple/src/test/java/com/baeldung/jackson/dtos/ignore/MyDtoIgnoreFieldByName.java rename to jackson-simple/src/test/java/com/baeldung/jackson/ignore/dtos/MyDtoIgnoreFieldByName.java index e7b8ea2a8e..1aee31a1b3 100644 --- a/jackson-simple/src/test/java/com/baeldung/jackson/dtos/ignore/MyDtoIgnoreFieldByName.java +++ b/jackson-simple/src/test/java/com/baeldung/jackson/ignore/dtos/MyDtoIgnoreFieldByName.java @@ -1,4 +1,4 @@ -package com.baeldung.jackson.dtos.ignore; +package com.baeldung.jackson.ignore.dtos; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; diff --git a/jackson-simple/src/test/java/com/baeldung/jackson/dtos/ignore/MyDtoIgnoreNull.java b/jackson-simple/src/test/java/com/baeldung/jackson/ignore/dtos/MyDtoIgnoreNull.java similarity index 96% rename from jackson-simple/src/test/java/com/baeldung/jackson/dtos/ignore/MyDtoIgnoreNull.java rename to jackson-simple/src/test/java/com/baeldung/jackson/ignore/dtos/MyDtoIgnoreNull.java index bc443500a1..75532f18c2 100644 --- a/jackson-simple/src/test/java/com/baeldung/jackson/dtos/ignore/MyDtoIgnoreNull.java +++ b/jackson-simple/src/test/java/com/baeldung/jackson/ignore/dtos/MyDtoIgnoreNull.java @@ -1,4 +1,4 @@ -package com.baeldung.jackson.dtos.ignore; +package com.baeldung.jackson.ignore.dtos; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; diff --git a/java-blockchain/.gitignore b/java-blockchain/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/java-blockchain/.gitignore @@ -0,0 +1,26 @@ +*.class + +0.* + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* +.resourceCache + +# Packaged files # +*.jar +*.war +*.ear + +# Files generated by integration tests +*.txt +backup-pom.xml +/bin/ +/temp + +#IntelliJ specific +.idea/ +*.iml \ No newline at end of file diff --git a/java-blockchain/README.md b/java-blockchain/README.md new file mode 100644 index 0000000000..600f4dd610 --- /dev/null +++ b/java-blockchain/README.md @@ -0,0 +1,6 @@ +========= + +## Basic Implementation of Blockchian in Java + +### Relevant Articles: +- []() diff --git a/java-blockchain/pom.xml b/java-blockchain/pom.xml new file mode 100644 index 0000000000..2f9e011aa7 --- /dev/null +++ b/java-blockchain/pom.xml @@ -0,0 +1,40 @@ + + 4.0.0 + com.baeldung.blockchain + java-blockchain + 0.1.0-SNAPSHOT + java-blockchain + jar + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + java-blockchain + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + 1.8 + 1.8 + + \ No newline at end of file diff --git a/java-blockchain/src/main/java/com/baeldung/blockchain/Block.java b/java-blockchain/src/main/java/com/baeldung/blockchain/Block.java new file mode 100644 index 0000000000..6b4e971cd7 --- /dev/null +++ b/java-blockchain/src/main/java/com/baeldung/blockchain/Block.java @@ -0,0 +1,64 @@ +package com.baeldung.blockchain; + +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class Block { + + private static Logger logger = Logger.getLogger(Block.class.getName()); + + private String hash; + private String previousHash; + private String data; + private long timeStamp; + private int nonce; + + public Block(String data, String previousHash, long timeStamp) { + this.data = data; + this.previousHash = previousHash; + this.timeStamp = timeStamp; + this.hash = calculateBlockHash(); + } + + public String mineBlock(int prefix) { + String prefixString = new String(new char[prefix]).replace('\0', '0'); + while (!hash.substring(0, prefix) + .equals(prefixString)) { + nonce++; + hash = calculateBlockHash(); + } + return hash; + } + + public String calculateBlockHash() { + String dataToHash = previousHash + Long.toString(timeStamp) + Integer.toString(nonce) + data; + MessageDigest digest = null; + byte[] bytes = null; + try { + digest = MessageDigest.getInstance("SHA-256"); + bytes = digest.digest(dataToHash.getBytes("UTF-8")); + } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) { + logger.log(Level.SEVERE, ex.getMessage()); + } + StringBuffer buffer = new StringBuffer(); + for (byte b : bytes) { + buffer.append(String.format("%02x", b)); + } + return buffer.toString(); + } + + public String getHash() { + return this.hash; + } + + public String getPreviousHash() { + return this.previousHash; + } + + public void setData(String data) { + this.data = data; + } +} diff --git a/testing-modules/mocks/jmockit/src/main/resources/logback.xml b/java-blockchain/src/main/resources/logback.xml similarity index 100% rename from testing-modules/mocks/jmockit/src/main/resources/logback.xml rename to java-blockchain/src/main/resources/logback.xml diff --git a/java-blockchain/src/test/java/com/baeldung/blockchain/BlockchainUnitTest.java b/java-blockchain/src/test/java/com/baeldung/blockchain/BlockchainUnitTest.java new file mode 100644 index 0000000000..883e55c351 --- /dev/null +++ b/java-blockchain/src/test/java/com/baeldung/blockchain/BlockchainUnitTest.java @@ -0,0 +1,68 @@ +package com.baeldung.blockchain; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +public class BlockchainUnitTest { + + public static List blockchain = new ArrayList(); + public static int prefix = 4; + public static String prefixString = new String(new char[prefix]).replace('\0', '0'); + + @BeforeClass + public static void setUp() { + Block genesisBlock = new Block("The is the Genesis Block.", "0", new Date().getTime()); + genesisBlock.mineBlock(prefix); + blockchain.add(genesisBlock); + Block firstBlock = new Block("The is the First Block.", genesisBlock.getHash(), new Date().getTime()); + firstBlock.mineBlock(prefix); + blockchain.add(firstBlock); + } + + @Test + public void givenBlockchain_whenNewBlockAdded_thenSuccess() { + Block newBlock = new Block("The is a New Block.", blockchain.get(blockchain.size() - 1) + .getHash(), new Date().getTime()); + newBlock.mineBlock(prefix); + assertTrue(newBlock.getHash() + .substring(0, prefix) + .equals(prefixString)); + blockchain.add(newBlock); + } + + @Test + public void givenBlockchain_whenValidated_thenSuccess() { + boolean flag = true; + for (int i = 0; i < blockchain.size(); i++) { + String previousHash = i == 0 ? "0" + : blockchain.get(i - 1) + .getHash(); + flag = blockchain.get(i) + .getHash() + .equals(blockchain.get(i) + .calculateBlockHash()) + && previousHash.equals(blockchain.get(i) + .getPreviousHash()) + && blockchain.get(i) + .getHash() + .substring(0, prefix) + .equals(prefixString); + if (!flag) + break; + } + assertTrue(flag); + } + + @AfterClass + public static void tearDown() { + blockchain.clear(); + } + +} diff --git a/java-blockchain/src/test/resources/.gitignore b/java-blockchain/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/java-blockchain/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/java-dates/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java b/java-dates/src/main/java/com/baeldung/datetolocaldate/DateToLocalDateConverter.java similarity index 96% rename from java-dates/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java rename to java-dates/src/main/java/com/baeldung/datetolocaldate/DateToLocalDateConverter.java index c794c57e87..80bccb399a 100644 --- a/java-dates/src/main/java/com/baeldung/java9/datetime/DateToLocalDateConverter.java +++ b/java-dates/src/main/java/com/baeldung/datetolocaldate/DateToLocalDateConverter.java @@ -1,7 +1,7 @@ /** * */ -package com.baeldung.java9.datetime; +package com.baeldung.datetolocaldate; import java.time.Instant; import java.time.LocalDate; diff --git a/java-dates/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java b/java-dates/src/main/java/com/baeldung/datetolocaldate/DateToLocalDateTimeConverter.java similarity index 96% rename from java-dates/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java rename to java-dates/src/main/java/com/baeldung/datetolocaldate/DateToLocalDateTimeConverter.java index 17ca5b1122..1d1e3b7d92 100644 --- a/java-dates/src/main/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverter.java +++ b/java-dates/src/main/java/com/baeldung/datetolocaldate/DateToLocalDateTimeConverter.java @@ -1,7 +1,7 @@ /** * */ -package com.baeldung.java9.datetime; +package com.baeldung.datetolocaldate; import java.time.Instant; import java.time.LocalDateTime; diff --git a/java-dates/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java b/java-dates/src/main/java/com/baeldung/datetolocaldate/LocalDateTimeToDateConverter.java similarity index 94% rename from java-dates/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java rename to java-dates/src/main/java/com/baeldung/datetolocaldate/LocalDateTimeToDateConverter.java index f219dcf038..9a6bb248fa 100644 --- a/java-dates/src/main/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverter.java +++ b/java-dates/src/main/java/com/baeldung/datetolocaldate/LocalDateTimeToDateConverter.java @@ -1,7 +1,7 @@ /** * */ -package com.baeldung.java9.datetime; +package com.baeldung.datetolocaldate; import java.time.LocalDateTime; import java.time.ZoneId; diff --git a/java-dates/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java b/java-dates/src/main/java/com/baeldung/datetolocaldate/LocalDateToDateConverter.java similarity index 94% rename from java-dates/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java rename to java-dates/src/main/java/com/baeldung/datetolocaldate/LocalDateToDateConverter.java index f9893da5d0..f679ffb77a 100644 --- a/java-dates/src/main/java/com/baeldung/java9/datetime/LocalDateToDateConverter.java +++ b/java-dates/src/main/java/com/baeldung/datetolocaldate/LocalDateToDateConverter.java @@ -1,7 +1,7 @@ /** * */ -package com.baeldung.java9.datetime; +package com.baeldung.datetolocaldate; import java.time.LocalDate; import java.time.ZoneId; diff --git a/java-dates/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterUnitTest.java b/java-dates/src/test/java/com/baeldung/datetolocaldate/DateToLocalDateConverterUnitTest.java similarity index 96% rename from java-dates/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetolocaldate/DateToLocalDateConverterUnitTest.java index f7f07500f1..b5a54e28eb 100644 --- a/java-dates/src/test/java/com/baeldung/java9/datetime/DateToLocalDateConverterUnitTest.java +++ b/java-dates/src/test/java/com/baeldung/datetolocaldate/DateToLocalDateConverterUnitTest.java @@ -1,7 +1,7 @@ /** * */ -package com.baeldung.java9.datetime; +package com.baeldung.datetolocaldate; import static org.junit.Assert.assertEquals; @@ -12,7 +12,7 @@ import java.util.Date; import org.junit.Test; -import com.baeldung.java9.datetime.DateToLocalDateConverter; +import com.baeldung.datetolocaldate.DateToLocalDateConverter; /** * JUnits for {@link DateToLocalDateConverter} class. diff --git a/java-dates/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterUnitTest.java b/java-dates/src/test/java/com/baeldung/datetolocaldate/DateToLocalDateTimeConverterUnitTest.java similarity index 97% rename from java-dates/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetolocaldate/DateToLocalDateTimeConverterUnitTest.java index 9ad29ea673..e6098cec1c 100644 --- a/java-dates/src/test/java/com/baeldung/java9/datetime/DateToLocalDateTimeConverterUnitTest.java +++ b/java-dates/src/test/java/com/baeldung/datetolocaldate/DateToLocalDateTimeConverterUnitTest.java @@ -1,7 +1,7 @@ /** * */ -package com.baeldung.java9.datetime; +package com.baeldung.datetolocaldate; import static org.junit.Assert.assertEquals; @@ -12,7 +12,7 @@ import java.util.Date; import org.junit.Test; -import com.baeldung.java9.datetime.DateToLocalDateTimeConverter; +import com.baeldung.datetolocaldate.DateToLocalDateTimeConverter; /** * JUnits for {@link DateToLocalDateTimeConverter} class. diff --git a/java-dates/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterUnitTest.java b/java-dates/src/test/java/com/baeldung/datetolocaldate/LocalDateTimeToDateConverterUnitTest.java similarity index 94% rename from java-dates/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetolocaldate/LocalDateTimeToDateConverterUnitTest.java index e5a541c546..c8e596c220 100644 --- a/java-dates/src/test/java/com/baeldung/java9/datetime/LocalDateTimeToDateConverterUnitTest.java +++ b/java-dates/src/test/java/com/baeldung/datetolocaldate/LocalDateTimeToDateConverterUnitTest.java @@ -1,7 +1,7 @@ /** * */ -package com.baeldung.java9.datetime; +package com.baeldung.datetolocaldate; import static org.junit.Assert.assertEquals; @@ -11,6 +11,8 @@ import java.util.Date; import org.junit.Test; +import com.baeldung.datetolocaldate.LocalDateTimeToDateConverter; + /** * * JUnits for {@link LocalDateTimeToDateConverter} class. diff --git a/java-dates/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterUnitTest.java b/java-dates/src/test/java/com/baeldung/datetolocaldate/LocalDateToDateConverterUnitTest.java similarity index 93% rename from java-dates/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterUnitTest.java rename to java-dates/src/test/java/com/baeldung/datetolocaldate/LocalDateToDateConverterUnitTest.java index 4e4dd20f2f..4ff3682158 100644 --- a/java-dates/src/test/java/com/baeldung/java9/datetime/LocalDateToDateConverterUnitTest.java +++ b/java-dates/src/test/java/com/baeldung/datetolocaldate/LocalDateToDateConverterUnitTest.java @@ -1,7 +1,7 @@ /** * */ -package com.baeldung.java9.datetime; +package com.baeldung.datetolocaldate; import static org.junit.Assert.assertEquals; @@ -11,6 +11,8 @@ import java.util.Date; import org.junit.Test; +import com.baeldung.datetolocaldate.LocalDateToDateConverter; + /** * * JUnits for {@link LocalDateToDateConverter} class. diff --git a/java-jdi/pom.xml b/java-jdi/pom.xml new file mode 100644 index 0000000000..3d70461dce --- /dev/null +++ b/java-jdi/pom.xml @@ -0,0 +1,130 @@ + + 4.0.0 + java-jdi + 0.1.0-SNAPSHOT + java-jdi + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + log4j + log4j + ${log4j.version} + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh-generator.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + com.sun + tools + ${tools.version} + system + ${java.home}/../lib/tools.jar + + + + + java-jdi + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven-javadoc-plugin.version} + + 1.8 + 1.8 + + + + + + + + integration + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + + + + + + + json + + + + + + + + + + 3.5 + + 3.6.1 + 1.8 + 1.7.21 + 1.1.7 + 1.8 + 2.21.0 + 3.0.0-M1 + 3.0.2 + + diff --git a/java-jdi/src/main/java/com/baeldung/jdi/JDIExampleDebuggee.java b/java-jdi/src/main/java/com/baeldung/jdi/JDIExampleDebuggee.java new file mode 100644 index 0000000000..4fb49024fb --- /dev/null +++ b/java-jdi/src/main/java/com/baeldung/jdi/JDIExampleDebuggee.java @@ -0,0 +1,14 @@ +package com.baeldung.jdi; + +public class JDIExampleDebuggee { + + public static void main(String[] args) { + String jpda = "Java Platform Debugger Architecture"; + System.out.println("Hi Everyone, Welcome to " + jpda); //add a break point here + + String jdi = "Java Debug Interface"; //add a break point here and also stepping in here + String text = "Today, we'll dive into " + jdi; + System.out.println(text); + } + +} diff --git a/java-jdi/src/main/java/com/baeldung/jdi/JDIExampleDebugger.java b/java-jdi/src/main/java/com/baeldung/jdi/JDIExampleDebugger.java new file mode 100644 index 0000000000..41a568e55f --- /dev/null +++ b/java-jdi/src/main/java/com/baeldung/jdi/JDIExampleDebugger.java @@ -0,0 +1,171 @@ +package com.baeldung.jdi; + +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.util.Map; + +import com.sun.jdi.AbsentInformationException; +import com.sun.jdi.Bootstrap; +import com.sun.jdi.ClassType; +import com.sun.jdi.IncompatibleThreadStateException; +import com.sun.jdi.LocalVariable; +import com.sun.jdi.Location; +import com.sun.jdi.StackFrame; +import com.sun.jdi.VMDisconnectedException; +import com.sun.jdi.Value; +import com.sun.jdi.VirtualMachine; +import com.sun.jdi.connect.Connector; +import com.sun.jdi.connect.IllegalConnectorArgumentsException; +import com.sun.jdi.connect.LaunchingConnector; +import com.sun.jdi.connect.VMStartException; +import com.sun.jdi.event.BreakpointEvent; +import com.sun.jdi.event.ClassPrepareEvent; +import com.sun.jdi.event.Event; +import com.sun.jdi.event.EventSet; +import com.sun.jdi.event.LocatableEvent; +import com.sun.jdi.event.StepEvent; +import com.sun.jdi.request.BreakpointRequest; +import com.sun.jdi.request.ClassPrepareRequest; +import com.sun.jdi.request.StepRequest; + +public class JDIExampleDebugger { + + private Class debugClass; + private int[] breakPointLines; + + public Class getDebugClass() { + return debugClass; + } + + public void setDebugClass(Class debugClass) { + this.debugClass = debugClass; + } + + public int[] getBreakPointLines() { + return breakPointLines; + } + + public void setBreakPointLines(int[] breakPointLines) { + this.breakPointLines = breakPointLines; + } + + /** + * Sets the debug class as the main argument in the connector and launches the VM + * @return VirtualMachine + * @throws IOException + * @throws IllegalConnectorArgumentsException + * @throws VMStartException + */ + public VirtualMachine connectAndLaunchVM() throws IOException, IllegalConnectorArgumentsException, VMStartException { + LaunchingConnector launchingConnector = Bootstrap.virtualMachineManager().defaultConnector(); + Map arguments = launchingConnector.defaultArguments(); + arguments.get("main").setValue(debugClass.getName()); + VirtualMachine vm = launchingConnector.launch(arguments); + return vm; + } + + /** + * Creates a request to prepare the debug class, add filter as the debug class and enables it + * @param vm + */ + public void enableClassPrepareRequest(VirtualMachine vm) { + ClassPrepareRequest classPrepareRequest = vm.eventRequestManager().createClassPrepareRequest(); + classPrepareRequest.addClassFilter(debugClass.getName()); + classPrepareRequest.enable(); + } + + /** + * Sets the break points at the line numbers mentioned in breakPointLines array + * @param vm + * @param event + * @throws AbsentInformationException + */ + public void setBreakPoints(VirtualMachine vm, ClassPrepareEvent event) throws AbsentInformationException { + ClassType classType = (ClassType) event.referenceType(); + for(int lineNumber: breakPointLines) { + Location location = classType.locationsOfLine(lineNumber).get(0); + BreakpointRequest bpReq = vm.eventRequestManager().createBreakpointRequest(location); + bpReq.enable(); + } + } + + /** + * Displays the visible variables + * @param event + * @throws IncompatibleThreadStateException + * @throws AbsentInformationException + */ + public void displayVariables(LocatableEvent event) throws IncompatibleThreadStateException, AbsentInformationException { + StackFrame stackFrame = event.thread().frame(0); + if(stackFrame.location().toString().contains(debugClass.getName())) { + Map visibleVariables = stackFrame.getValues(stackFrame.visibleVariables()); + System.out.println("Variables at " +stackFrame.location().toString() + " > "); + for (Map.Entry entry : visibleVariables.entrySet()) { + System.out.println(entry.getKey().name() + " = " + entry.getValue()); + } + } + } + + /** + * Enables step request for a break point + * @param vm + * @param event + */ + public void enableStepRequest(VirtualMachine vm, BreakpointEvent event) { + //enable step request for last break point + if(event.location().toString().contains(debugClass.getName()+":"+breakPointLines[breakPointLines.length-1])) { + StepRequest stepRequest = vm.eventRequestManager().createStepRequest(event.thread(), StepRequest.STEP_LINE, StepRequest.STEP_OVER); + stepRequest.enable(); + } + } + + public static void main(String[] args) throws Exception { + + JDIExampleDebugger debuggerInstance = new JDIExampleDebugger(); + debuggerInstance.setDebugClass(JDIExampleDebuggee.class); + int[] breakPoints = {6, 9}; + debuggerInstance.setBreakPointLines(breakPoints); + VirtualMachine vm = null; + + try { + vm = debuggerInstance.connectAndLaunchVM(); + debuggerInstance.enableClassPrepareRequest(vm); + + EventSet eventSet = null; + while ((eventSet = vm.eventQueue().remove()) != null) { + for (Event event : eventSet) { + if (event instanceof ClassPrepareEvent) { + debuggerInstance.setBreakPoints(vm, (ClassPrepareEvent)event); + } + + if (event instanceof BreakpointEvent) { + event.request().disable(); + debuggerInstance.displayVariables((BreakpointEvent) event); + debuggerInstance.enableStepRequest(vm, (BreakpointEvent)event); + } + + if (event instanceof StepEvent) { + debuggerInstance.displayVariables((StepEvent) event); + } + vm.resume(); + } + } + } catch (VMDisconnectedException e) { + System.out.println("Virtual Machine is disconnected."); + } catch (Exception e) { + e.printStackTrace(); + } + finally { + InputStreamReader reader = new InputStreamReader(vm.process().getInputStream()); + OutputStreamWriter writer = new OutputStreamWriter(System.out); + char[] buf = new char[512]; + + reader.read(buf); + writer.write(buf); + writer.flush(); + } + + } + +} diff --git a/java-math/README.md b/java-math/README.md index d821348204..244417d1a5 100644 --- a/java-math/README.md +++ b/java-math/README.md @@ -7,4 +7,5 @@ - [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines) - [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred) - [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage) -- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude) \ No newline at end of file +- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude) +- [Debugging with Eclipse](https://www.baeldung.com/eclipse-debugging) diff --git a/java-numbers-2/src/main/java/com/baeldung/lcm/BigIntegerLCM.java b/java-numbers-2/src/main/java/com/baeldung/lcm/BigIntegerLCM.java new file mode 100644 index 0000000000..affface9c0 --- /dev/null +++ b/java-numbers-2/src/main/java/com/baeldung/lcm/BigIntegerLCM.java @@ -0,0 +1,13 @@ +package com.baeldung.lcm; + +import java.math.BigInteger; + +public class BigIntegerLCM { + + public static BigInteger lcm(BigInteger number1, BigInteger number2) { + BigInteger gcd = number1.gcd(number2); + BigInteger absProduct = number1.multiply(number2).abs(); + return absProduct.divide(gcd); + } + +} diff --git a/java-numbers-2/src/main/java/com/baeldung/lcm/EuclideanAlgorithm.java b/java-numbers-2/src/main/java/com/baeldung/lcm/EuclideanAlgorithm.java new file mode 100644 index 0000000000..4032d119fa --- /dev/null +++ b/java-numbers-2/src/main/java/com/baeldung/lcm/EuclideanAlgorithm.java @@ -0,0 +1,40 @@ +package com.baeldung.lcm; + +import java.util.Arrays; + +public class EuclideanAlgorithm { + + public static int gcd(int number1, int number2) { + if (number1 == 0 || number2 == 0) { + return number1 + number2; + } else { + int absNumber1 = Math.abs(number1); + int absNumber2 = Math.abs(number2); + int biggerValue = Math.max(absNumber1, absNumber2); + int smallerValue = Math.min(absNumber1, absNumber2); + return gcd(biggerValue % smallerValue, smallerValue); + } + } + + public static int lcm(int number1, int number2) { + if (number1 == 0 || number2 == 0) + return 0; + else { + int gcd = gcd(number1, number2); + return Math.abs(number1 * number2) / gcd; + } + } + + public static int lcmForArray(int[] numbers) { + int lcm = numbers[0]; + for (int i = 1; i <= numbers.length - 1; i++) { + lcm = lcm(lcm, numbers[i]); + } + return lcm; + } + + public static int lcmByLambda(int... numbers) { + return Arrays.stream(numbers).reduce(1, (lcmSoFar, currentNumber) -> Math.abs(lcmSoFar * currentNumber) / gcd(lcmSoFar, currentNumber)); + } + +} diff --git a/java-numbers-2/src/main/java/com/baeldung/lcm/PrimeFactorizationAlgorithm.java b/java-numbers-2/src/main/java/com/baeldung/lcm/PrimeFactorizationAlgorithm.java new file mode 100644 index 0000000000..cfdc3bfe96 --- /dev/null +++ b/java-numbers-2/src/main/java/com/baeldung/lcm/PrimeFactorizationAlgorithm.java @@ -0,0 +1,42 @@ +package com.baeldung.lcm; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class PrimeFactorizationAlgorithm { + + public static Map getPrimeFactors(int number) { + int absNumber = Math.abs(number); + Map primeFactorsMap = new HashMap(); + for (int factor = 2; factor <= absNumber; factor++) { + while (absNumber % factor == 0) { + Integer power = primeFactorsMap.get(factor); + if (power == null) { + power = 0; + } + primeFactorsMap.put(factor, power + 1); + absNumber /= factor; + } + } + return primeFactorsMap; + } + + public static int lcm(int number1, int number2) { + if (number1 == 0 || number2 == 0) { + return 0; + } + Map primeFactorsForNum1 = getPrimeFactors(number1); + Map primeFactorsForNum2 = getPrimeFactors(number2); + Set primeFactorsUnionSet = new HashSet(primeFactorsForNum1.keySet()); + primeFactorsUnionSet.addAll(primeFactorsForNum2.keySet()); + int lcm = 1; + for (Integer primeFactor : primeFactorsUnionSet) { + lcm *= Math.pow(primeFactor, Math.max(primeFactorsForNum1.getOrDefault(primeFactor, 0), + primeFactorsForNum2.getOrDefault(primeFactor, 0))); + } + return lcm; + } + +} diff --git a/java-numbers-2/src/main/java/com/baeldung/lcm/SimpleAlgorithm.java b/java-numbers-2/src/main/java/com/baeldung/lcm/SimpleAlgorithm.java new file mode 100644 index 0000000000..6ba4966dc7 --- /dev/null +++ b/java-numbers-2/src/main/java/com/baeldung/lcm/SimpleAlgorithm.java @@ -0,0 +1,18 @@ +package com.baeldung.lcm; + +public class SimpleAlgorithm { + public static int lcm(int number1, int number2) { + if (number1 == 0 || number2 == 0) { + return 0; + } + int absNumber1 = Math.abs(number1); + int absNumber2 = Math.abs(number2); + int absHigherNumber = Math.max(absNumber1, absNumber2); + int absLowerNumber = Math.min(absNumber1, absNumber2); + int lcm = absHigherNumber; + while (lcm % absLowerNumber != 0) { + lcm += absHigherNumber; + } + return lcm; + } +} diff --git a/java-numbers-2/src/main/java/com/baeldung/numbersinrange/NumbersInARange.java b/java-numbers-2/src/main/java/com/baeldung/numbersinrange/NumbersInARange.java new file mode 100644 index 0000000000..937583cdb5 --- /dev/null +++ b/java-numbers-2/src/main/java/com/baeldung/numbersinrange/NumbersInARange.java @@ -0,0 +1,36 @@ +package com.baeldung.numbersinrange; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class NumbersInARange { + + public List getNumbersInRange(int start, int end) { + List result = new ArrayList<>(); + for (int i = start; i < end; i++) { + result.add(i); + } + return result; + } + + public List getNumbersUsingIntStreamRange(int start, int end) { + return IntStream.range(start, end) + .boxed() + .collect(Collectors.toList()); + } + + public List getNumbersUsingIntStreamRangeClosed(int start, int end) { + return IntStream.rangeClosed(start, end) + .boxed() + .collect(Collectors.toList()); + } + + public List getNumbersUsingIntStreamIterate(int start, int limit) { + return IntStream.iterate(start, i -> i + 1) + .limit(limit) + .boxed() + .collect(Collectors.toList()); + } +} diff --git a/java-numbers-2/src/main/java/com/baeldung/numbersinrange/RandomNumbersInARange.java b/java-numbers-2/src/main/java/com/baeldung/numbersinrange/RandomNumbersInARange.java new file mode 100644 index 0000000000..dc6ddfe781 --- /dev/null +++ b/java-numbers-2/src/main/java/com/baeldung/numbersinrange/RandomNumbersInARange.java @@ -0,0 +1,22 @@ +package com.baeldung.numbersinrange; + +import java.util.Random; + +public class RandomNumbersInARange { + + public int getRandomNumber(int min, int max) { + return (int) ((Math.random() * (max - min)) + min); + } + + public int getRandomNumberUsingNextInt(int min, int max) { + Random random = new Random(); + return random.nextInt(max - min) + min; + } + + public int getRandomNumberUsingInts(int min, int max) { + Random random = new Random(); + return random.ints(min, max) + .findFirst() + .getAsInt(); + } +} diff --git a/java-numbers-2/src/test/java/com/baeldung/lcm/BigIntegerLCMUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/lcm/BigIntegerLCMUnitTest.java new file mode 100644 index 0000000000..10bee4c087 --- /dev/null +++ b/java-numbers-2/src/test/java/com/baeldung/lcm/BigIntegerLCMUnitTest.java @@ -0,0 +1,18 @@ +package com.baeldung.lcm; + + +import org.junit.Assert; +import org.junit.Test; + +import java.math.BigInteger; + +public class BigIntegerLCMUnitTest { + + @Test + public void testLCM() { + BigInteger number1 = new BigInteger("12"); + BigInteger number2 = new BigInteger("18"); + BigInteger expectedLCM = new BigInteger("36"); + Assert.assertEquals(expectedLCM, BigIntegerLCM.lcm(number1, number2)); + } +} diff --git a/java-numbers-2/src/test/java/com/baeldung/lcm/EuclideanAlgorithmUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/lcm/EuclideanAlgorithmUnitTest.java new file mode 100644 index 0000000000..09a53cfa4e --- /dev/null +++ b/java-numbers-2/src/test/java/com/baeldung/lcm/EuclideanAlgorithmUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.lcm; + +import org.junit.Assert; +import org.junit.Test; + +public class EuclideanAlgorithmUnitTest { + + @Test + public void testGCD() { + Assert.assertEquals(6, EuclideanAlgorithm.gcd(12, 18)); + } + + @Test + public void testLCM() { + Assert.assertEquals(36, EuclideanAlgorithm.lcm(12, 18)); + } + + @Test + public void testLCMForArray() { + Assert.assertEquals(15, EuclideanAlgorithm.lcmForArray(new int[]{3, 5, 15})); + } + + @Test + public void testLCMByLambdaForArray() { + Assert.assertEquals(15, EuclideanAlgorithm.lcmByLambda(new int[]{3, 5, 15})); + } +} diff --git a/java-numbers-2/src/test/java/com/baeldung/lcm/PrimeFactorizationAlgorithmUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/lcm/PrimeFactorizationAlgorithmUnitTest.java new file mode 100644 index 0000000000..b33b81f85e --- /dev/null +++ b/java-numbers-2/src/test/java/com/baeldung/lcm/PrimeFactorizationAlgorithmUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.lcm; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static com.baeldung.lcm.PrimeFactorizationAlgorithm.*; + + +public class PrimeFactorizationAlgorithmUnitTest { + + @Test + public void testGetPrimeFactors() { + Map expectedPrimeFactorsMapForTwelve = new HashMap<>(); + expectedPrimeFactorsMapForTwelve.put(2, 2); + expectedPrimeFactorsMapForTwelve.put(3, 1); + Map expectedPrimeFactorsMapForEighteen = new HashMap<>(); + expectedPrimeFactorsMapForEighteen.put(2, 1); + expectedPrimeFactorsMapForEighteen.put(3, 2); + Assert.assertEquals(expectedPrimeFactorsMapForTwelve, getPrimeFactors(12)); + Assert.assertEquals(expectedPrimeFactorsMapForEighteen, getPrimeFactors(18)); + } + + @Test + public void testLCM() { + Assert.assertEquals(36, PrimeFactorizationAlgorithm.lcm(12, 18)); + } +} diff --git a/java-numbers-2/src/test/java/com/baeldung/lcm/SimpleAlgorithmUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/lcm/SimpleAlgorithmUnitTest.java new file mode 100644 index 0000000000..bc0a1690f4 --- /dev/null +++ b/java-numbers-2/src/test/java/com/baeldung/lcm/SimpleAlgorithmUnitTest.java @@ -0,0 +1,15 @@ +package com.baeldung.lcm; + +import org.junit.Assert; +import org.junit.Test; + +import static com.baeldung.lcm.SimpleAlgorithm.*; + +public class SimpleAlgorithmUnitTest { + + @Test + public void testLCM() { + Assert.assertEquals(36, lcm(12, 18)); + } + +} diff --git a/java-numbers-2/src/test/java/com/baeldung/numbersinrange/NumbersInARangeUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/numbersinrange/NumbersInARangeUnitTest.java new file mode 100644 index 0000000000..3225257166 --- /dev/null +++ b/java-numbers-2/src/test/java/com/baeldung/numbersinrange/NumbersInARangeUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.numbersinrange; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +public class NumbersInARangeUnitTest { + + @Test + public void givenTheRange1To10_andUsingForLoop_thenExpectCorrectResult() { + NumbersInARange numbersInARange = new NumbersInARange(); + List numbers = numbersInARange.getNumbersInRange(1, 10); + + assertEquals(Arrays.asList(1,2,3,4,5,6,7,8,9), numbers); + } + + @Test + public void givenTheRange1To10_andUsingIntStreamRange_thenExpectCorrectResult() { + NumbersInARange numbersInARange = new NumbersInARange(); + List numbers = numbersInARange.getNumbersUsingIntStreamRange(1, 10); + + assertEquals(Arrays.asList(1,2,3,4,5,6,7,8,9), numbers); + } + + @Test + public void givenTheRange1To10_andUsingIntStreamRangeClosed_thenExpectCorrectResult() { + NumbersInARange numbersInARange = new NumbersInARange(); + List numbers = numbersInARange.getNumbersUsingIntStreamRangeClosed(1, 10); + + assertEquals(Arrays.asList(1,2,3,4,5,6,7,8,9,10), numbers); + } + + @Test + public void givenTheRange1To10_andUsingIntStreamIterate_thenExpectCorrectResult() { + NumbersInARange numbersInARange = new NumbersInARange(); + List numbers = numbersInARange.getNumbersUsingIntStreamIterate(1, 10); + + assertEquals(Arrays.asList(1,2,3,4,5,6,7,8,9,10), numbers); + } +} diff --git a/java-numbers-2/src/test/java/com/baeldung/numbersinrange/RandomNumbersInARangeUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/numbersinrange/RandomNumbersInARangeUnitTest.java new file mode 100644 index 0000000000..77b2cbbfef --- /dev/null +++ b/java-numbers-2/src/test/java/com/baeldung/numbersinrange/RandomNumbersInARangeUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.numbersinrange; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class RandomNumbersInARangeUnitTest { + + @Test + public void givenTheRange1To10_andUsingMathRandom_thenExpectCorrectResult() { + RandomNumbersInARange randomNumbersInARange = new RandomNumbersInARange(); + int number = randomNumbersInARange.getRandomNumber(1, 10); + + assertTrue(number >= 1); + assertTrue(number < 10); + } + + @Test + public void givenTheRange1To10_andUsingRandomInts_thenExpectCorrectResult() { + RandomNumbersInARange randomNumbersInARange = new RandomNumbersInARange(); + int number = randomNumbersInARange.getRandomNumberUsingInts(1, 10); + + assertTrue(number >= 1); + assertTrue(number < 10); + } + + @Test + public void givenTheRange1To10_andUsingRandomNextInt_thenExpectCorrectResult() { + RandomNumbersInARange randomNumbersInARange = new RandomNumbersInARange(); + int number = randomNumbersInARange.getRandomNumberUsingNextInt(1, 10); + + assertTrue(number >= 1); + assertTrue(number < 10); + } +} diff --git a/java-streams-2/pom.xml b/java-streams-2/pom.xml index f7a0379ac5..4cebd44427 100644 --- a/java-streams-2/pom.xml +++ b/java-streams-2/pom.xml @@ -2,9 +2,9 @@ 4.0.0 com.baeldung.javastreams2 - javastreams2 + java-streams-2 1.0 - javastreams2 + java-streams-2 jar diff --git a/java-streams/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstUnitTest.java b/java-streams/src/test/java/com/baeldung/java8/streams/Java8FindAnyFindFirstUnitTest.java similarity index 97% rename from java-streams/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstUnitTest.java rename to java-streams/src/test/java/com/baeldung/java8/streams/Java8FindAnyFindFirstUnitTest.java index 8c2e0628fa..5f52fe375e 100644 --- a/java-streams/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstUnitTest.java +++ b/java-streams/src/test/java/com/baeldung/java8/streams/Java8FindAnyFindFirstUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java8; +package com.baeldung.java8.streams; import org.junit.Test; diff --git a/java-streams/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java b/java-streams/src/test/java/com/baeldung/java8/streams/Java8StreamApiUnitTest.java similarity index 99% rename from java-streams/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java rename to java-streams/src/test/java/com/baeldung/java8/streams/Java8StreamApiUnitTest.java index 5005cf7f47..75cfbc049f 100644 --- a/java-streams/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java +++ b/java-streams/src/test/java/com/baeldung/java8/streams/Java8StreamApiUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java8; +package com.baeldung.java8.streams; import com.baeldung.stream.Product; import org.junit.Before; diff --git a/java-strings-2/src/main/java/com/baeldung/string/streamtokenizer/StreamTokenizerDemo.java b/java-strings-2/src/main/java/com/baeldung/string/streamtokenizer/StreamTokenizerDemo.java new file mode 100644 index 0000000000..3bb0ff5b77 --- /dev/null +++ b/java-strings-2/src/main/java/com/baeldung/string/streamtokenizer/StreamTokenizerDemo.java @@ -0,0 +1,76 @@ +package com.baeldung.string.streamtokenizer; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; + +public class StreamTokenizerDemo { + + private static final String INPUT_FILE = "/stream-tokenizer-example.txt"; + private static final int QUOTE_CHARACTER = '\''; + private static final int DOUBLE_QUOTE_CHARACTER = '"'; + + public static List streamTokenizerWithDefaultConfiguration(Reader reader) throws IOException { + StreamTokenizer streamTokenizer = new StreamTokenizer(reader); + List tokens = new ArrayList<>(); + + int currentToken = streamTokenizer.nextToken(); + while (currentToken != StreamTokenizer.TT_EOF) { + + if (streamTokenizer.ttype == StreamTokenizer.TT_NUMBER) { + tokens.add(streamTokenizer.nval); + } else if (streamTokenizer.ttype == StreamTokenizer.TT_WORD + || streamTokenizer.ttype == QUOTE_CHARACTER + || streamTokenizer.ttype == DOUBLE_QUOTE_CHARACTER) { + tokens.add(streamTokenizer.sval); + } else { + tokens.add((char) currentToken); + } + + currentToken = streamTokenizer.nextToken(); + } + + return tokens; + } + + public static List streamTokenizerWithCustomConfiguration(Reader reader) throws IOException { + StreamTokenizer streamTokenizer = new StreamTokenizer(reader); + List tokens = new ArrayList<>(); + + streamTokenizer.wordChars('!', '-'); + streamTokenizer.ordinaryChar('/'); + streamTokenizer.commentChar('#'); + streamTokenizer.eolIsSignificant(true); + + int currentToken = streamTokenizer.nextToken(); + while (currentToken != StreamTokenizer.TT_EOF) { + + if (streamTokenizer.ttype == StreamTokenizer.TT_NUMBER) { + tokens.add(streamTokenizer.nval); + } else if (streamTokenizer.ttype == StreamTokenizer.TT_WORD + || streamTokenizer.ttype == QUOTE_CHARACTER + || streamTokenizer.ttype == DOUBLE_QUOTE_CHARACTER) { + tokens.add(streamTokenizer.sval); + } else { + tokens.add((char) currentToken); + } + currentToken = streamTokenizer.nextToken(); + } + + return tokens; + } + + public static Reader createReaderFromFile() throws FileNotFoundException { + String inputFile = StreamTokenizerDemo.class.getResource(INPUT_FILE).getFile(); + return new FileReader(inputFile); + } + + public static void main(String[] args) throws IOException { + List tokens1 = streamTokenizerWithDefaultConfiguration(createReaderFromFile()); + List tokens2 = streamTokenizerWithCustomConfiguration(createReaderFromFile()); + + System.out.println(tokens1); + System.out.println(tokens2); + } + +} \ No newline at end of file diff --git a/java-strings-2/src/main/resources/stream-tokenizer-example.txt b/java-strings-2/src/main/resources/stream-tokenizer-example.txt new file mode 100644 index 0000000000..6efe4fdc81 --- /dev/null +++ b/java-strings-2/src/main/resources/stream-tokenizer-example.txt @@ -0,0 +1,3 @@ +3 quick brown foxes jump over the "lazy" dog! +#test1 +//test2 \ No newline at end of file diff --git a/java-strings-2/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java b/java-strings-2/src/test/java/com/baeldung/base64encodinganddecoding/ApacheCommonsEncodeDecodeUnitTest.java similarity index 97% rename from java-strings-2/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/base64encodinganddecoding/ApacheCommonsEncodeDecodeUnitTest.java index 7889e6ad53..a0fc845d52 100644 --- a/java-strings-2/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java +++ b/java-strings-2/src/test/java/com/baeldung/base64encodinganddecoding/ApacheCommonsEncodeDecodeUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java8.base64; +package com.baeldung.base64encodinganddecoding; import org.apache.commons.codec.binary.Base64; import org.junit.Test; diff --git a/java-strings-2/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java b/java-strings-2/src/test/java/com/baeldung/base64encodinganddecoding/Java8EncodeDecodeUnitTest.java similarity index 98% rename from java-strings-2/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/base64encodinganddecoding/Java8EncodeDecodeUnitTest.java index 62cfa4c0a1..191a3628e8 100644 --- a/java-strings-2/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java +++ b/java-strings-2/src/test/java/com/baeldung/base64encodinganddecoding/Java8EncodeDecodeUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java8.base64; +package com.baeldung.base64encodinganddecoding; import org.junit.Test; diff --git a/java-strings-2/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java b/java-strings-2/src/test/java/com/baeldung/base64encodinganddecoding/StringToByteArrayUnitTest.java similarity index 97% rename from java-strings-2/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java rename to java-strings-2/src/test/java/com/baeldung/base64encodinganddecoding/StringToByteArrayUnitTest.java index c5f7051c25..e2bb7bb64d 100644 --- a/java-strings-2/src/test/java/com/baeldung/java8/base64/StringToByteArrayUnitTest.java +++ b/java-strings-2/src/test/java/com/baeldung/base64encodinganddecoding/StringToByteArrayUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.java8.base64; +package com.baeldung.base64encodinganddecoding; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/java-strings-2/src/test/java/com/baeldung/string/streamtokenizer/StreamTokenizerDemoUnitTest.java b/java-strings-2/src/test/java/com/baeldung/string/streamtokenizer/StreamTokenizerDemoUnitTest.java new file mode 100644 index 0000000000..01091ec629 --- /dev/null +++ b/java-strings-2/src/test/java/com/baeldung/string/streamtokenizer/StreamTokenizerDemoUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.string.streamtokenizer; + +import org.junit.Test; + +import java.io.IOException; +import java.io.Reader; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertArrayEquals; + +public class StreamTokenizerDemoUnitTest { + + @Test + public void whenStreamTokenizerWithDefaultConfigurationIsCalled_ThenCorrectTokensAreReturned() throws IOException { + Reader reader = StreamTokenizerDemo.createReaderFromFile(); + List expectedTokens = Arrays.asList(3.0, "quick", "brown", "foxes", "jump", "over", "the", "lazy", "dog", '!', '#', "test1"); + + List actualTokens = StreamTokenizerDemo.streamTokenizerWithDefaultConfiguration(reader); + + assertArrayEquals(expectedTokens.toArray(), actualTokens.toArray()); + } + + @Test + public void whenStreamTokenizerWithCustomConfigurationIsCalled_ThenCorrectTokensAreReturned() throws IOException { + Reader reader = StreamTokenizerDemo.createReaderFromFile(); + List expectedTokens = Arrays.asList(3.0, "quick", "brown", "foxes", "jump", "over", "the", "\"lazy\"", "dog!", '\n', '\n', '/', '/', "test2"); + + List actualTokens = StreamTokenizerDemo.streamTokenizerWithCustomConfiguration(reader); + + assertArrayEquals(expectedTokens.toArray(), actualTokens.toArray()); + } + +} diff --git a/java-strings-3/src/main/java/com/baeldung/string/README.md b/java-strings-3/src/main/java/com/baeldung/string/README.md deleted file mode 100644 index e02980e93f..0000000000 --- a/java-strings-3/src/main/java/com/baeldung/string/README.md +++ /dev/null @@ -1,3 +0,0 @@ -This file exists to ensure this empty directory is committed in Git. - -Please remove this file when this directory is populated. \ No newline at end of file diff --git a/java-strings-3/src/main/java/com/baeldung/string/wordcount/WordCounter.java b/java-strings-3/src/main/java/com/baeldung/string/wordcount/WordCounter.java new file mode 100644 index 0000000000..30275773a6 --- /dev/null +++ b/java-strings-3/src/main/java/com/baeldung/string/wordcount/WordCounter.java @@ -0,0 +1,49 @@ +package com.baeldung.string.wordcount; + +import java.util.StringTokenizer; + +public class WordCounter { + static final int WORD = 0; + static final int SEPARATOR = 1; + + public static int countWordsUsingRegex(String arg) { + if (arg == null) { + return 0; + } + final String[] words = arg.split("[\\pP\\s&&[^']]+"); + return words.length; + } + + public static int countWordsUsingTokenizer(String arg) { + if (arg == null) { + return 0; + } + final StringTokenizer stringTokenizer = new StringTokenizer(arg); + return stringTokenizer.countTokens(); + } + + public static int countWordsManually(String arg) { + if (arg == null) { + return 0; + } + int flag = SEPARATOR; + int count = 0; + int stringLength = arg.length(); + int characterCounter = 0; + + while (characterCounter < stringLength) { + if (isAllowedInWord(arg.charAt(characterCounter)) && flag == SEPARATOR) { + flag = WORD; + count++; + } else if (!isAllowedInWord(arg.charAt(characterCounter))) { + flag = SEPARATOR; + } + characterCounter++; + } + return count; + } + + private static boolean isAllowedInWord(char charAt) { + return charAt == '\'' || Character.isLetter(charAt); + } +} diff --git a/java-strings-3/src/test/java/com/baeldung/string/charArrayToString/CharArrayToStringConversionUnitTest.java b/java-strings-3/src/test/java/com/baeldung/string/charArrayToString/CharArrayToStringConversionUnitTest.java new file mode 100644 index 0000000000..1030185c3e --- /dev/null +++ b/java-strings-3/src/test/java/com/baeldung/string/charArrayToString/CharArrayToStringConversionUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.string.charArrayToString; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +import com.google.common.base.Joiner; +import org.junit.Test; + +import java.util.Arrays; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class CharArrayToStringConversionUnitTest { + + @Test + public void whenStringConstructor_thenOK() { + final char[] charArray = { 'b', 'a', 'e', 'l', 'd', 'u', 'n', 'g' }; + + String string = new String(charArray); + + assertThat(string, is("baeldung")); + } + + @Test + public void whenStringCopyValueOf_thenOK() { + final char[] charArray = { 'b', 'a', 'e', 'l', 'd', 'u', 'n', 'g' }; + + String string = String.copyValueOf(charArray); + + assertThat(string, is("baeldung")); + } + + @Test + public void whenStringValueOf_thenOK() { + final char[] charArray = { 'b', 'a', 'e', 'l', 'd', 'u', 'n', 'g' }; + + String string = String.valueOf(charArray); + + assertThat(string, is("baeldung")); + } + + @Test + public void whenStringBuilder_thenOK() { + final char[][] arrayOfCharArray = { { 'b', 'a' }, { 'e', 'l', 'd', 'u' }, { 'n', 'g' } }; + + StringBuilder sb = new StringBuilder(); + for (char[] subArray : arrayOfCharArray) { + sb.append(subArray); + } + + assertThat(sb.toString(), is("baeldung")); + } + + @Test + public void whenStreamCollectors_thenOK() { + final Character[] charArray = { 'b', 'a', 'e', 'l', 'd', 'u', 'n', 'g' }; + + Stream charStream = Arrays.stream(charArray); + String string = charStream.map(String::valueOf).collect(Collectors.joining()); + + assertThat(string, is("baeldung")); + } + + @Test + public void whenGoogleCommonBaseJoiners_thenOK() { + final Character[] charArray = { 'b', 'a', 'e', 'l', 'd', 'u', 'n', 'g' }; + + String string = Joiner.on("|").join(charArray); + + assertThat(string, is("b|a|e|l|d|u|n|g")); + } +} diff --git a/java-strings-3/src/test/java/com/baeldung/string/wordcount/WordCountUnitTest.java b/java-strings-3/src/test/java/com/baeldung/string/wordcount/WordCountUnitTest.java new file mode 100644 index 0000000000..fdd045978f --- /dev/null +++ b/java-strings-3/src/test/java/com/baeldung/string/wordcount/WordCountUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.string.wordcount; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import java.util.StringTokenizer; + +public class WordCountUnitTest { + private String string1 = "This is a test sentence with eight words"; + private String string2 = "This#is%a test sentence with eight words"; + + @Test + public void givenStringWith8Words_whenUsingRegexCount_ThenResultEqual8() { + assertEquals(8, WordCounter.countWordsUsingRegex(string2)); + assertEquals(9, WordCounter.countWordsUsingRegex("no&one#should%ever-write-like,this;but:well")); + assertEquals(7, WordCounter.countWordsUsingRegex("the farmer's wife--she was from Albuquerque")); + } + + @Test + public void givenStringWith8Words_whenUsingManualMethod_ThenWordCountEqual8() { + assertEquals(8, WordCounter.countWordsManually(string1)); + assertEquals(9, WordCounter.countWordsManually("no&one#should%ever-write-like,this but well")); + assertEquals(7, WordCounter.countWordsManually("the farmer's wife--she was from Albuquerque")); + } + + @Test + public void givenAStringWith8Words_whenUsingTokenizer_ThenWordCountEqual8() { + assertEquals(8, WordCounter.countWordsUsingTokenizer(string1)); + assertEquals(3, new StringTokenizer("three blind mice").countTokens()); + assertEquals(4, new StringTokenizer("see\thow\tthey\trun").countTokens()); + assertEquals(7, new StringTokenizer("the farmer's wife--she was from Albuquerque", " -").countTokens()); + assertEquals(10, new StringTokenizer("did,you,ever,see,such,a,sight,in,your,life", ",").countTokens()); + } +} diff --git a/java-strings/src/main/java/com/baeldung/string/AddingNewLineToString.java b/java-strings/src/main/java/com/baeldung/string/newline/AddingNewLineToString.java similarity index 98% rename from java-strings/src/main/java/com/baeldung/string/AddingNewLineToString.java rename to java-strings/src/main/java/com/baeldung/string/newline/AddingNewLineToString.java index b522f7337b..48b71eed12 100644 --- a/java-strings/src/main/java/com/baeldung/string/AddingNewLineToString.java +++ b/java-strings/src/main/java/com/baeldung/string/newline/AddingNewLineToString.java @@ -1,4 +1,4 @@ -package com.baeldung.string; +package com.baeldung.string.newline; public class AddingNewLineToString { diff --git a/javaxval/README.md b/javaxval/README.md index 3a975022ad..fadd174166 100644 --- a/javaxval/README.md +++ b/javaxval/README.md @@ -2,9 +2,6 @@ ## Java Bean Validation Examples -###The Course -The "REST With Spring" Classes: http://bit.ly/restwithspring - ### Relevant Articles: - [Java Bean Validation Basics](http://www.baeldung.com/javax-validation) - [Validating Container Elements with Bean Validation 2.0](http://www.baeldung.com/bean-validation-container-elements) diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/validationgroup/AdvanceInfo.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/validationgroup/AdvanceInfo.java new file mode 100644 index 0000000000..4d5df052c2 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/validationgroup/AdvanceInfo.java @@ -0,0 +1,5 @@ +package org.baeldung.javabeanconstraints.validationgroup; + +public interface AdvanceInfo { + +} diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/validationgroup/BasicInfo.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/validationgroup/BasicInfo.java new file mode 100644 index 0000000000..4564a7a702 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/validationgroup/BasicInfo.java @@ -0,0 +1,5 @@ +package org.baeldung.javabeanconstraints.validationgroup; + +public interface BasicInfo { + +} diff --git a/javaxval/src/main/java/org/baeldung/javabeanconstraints/validationgroup/RegistrationForm.java b/javaxval/src/main/java/org/baeldung/javabeanconstraints/validationgroup/RegistrationForm.java new file mode 100644 index 0000000000..154d9821b6 --- /dev/null +++ b/javaxval/src/main/java/org/baeldung/javabeanconstraints/validationgroup/RegistrationForm.java @@ -0,0 +1,99 @@ +package org.baeldung.javabeanconstraints.validationgroup; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; + +public class RegistrationForm { + @NotBlank(groups = BasicInfo.class) + private String firstName; + @NotBlank(groups = BasicInfo.class) + private String lastName; + @Email(groups = BasicInfo.class) + private String email; + @NotBlank(groups = BasicInfo.class) + private String phone; + + @NotBlank(groups = AdvanceInfo.class) + private String street; + @NotBlank(groups = AdvanceInfo.class) + private String houseNumber; + @NotBlank(groups = AdvanceInfo.class) + private String zipCode; + @NotBlank(groups = AdvanceInfo.class) + private String city; + @NotBlank(groups = AdvanceInfo.class) + private String contry; + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getHouseNumber() { + return houseNumber; + } + + public void setHouseNumber(String houseNumber) { + this.houseNumber = houseNumber; + } + + public String getZipCode() { + return zipCode; + } + + public void setZipCode(String zipCode) { + this.zipCode = zipCode; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getContry() { + return contry; + } + + public void setContry(String contry) { + this.contry = contry; + } + + 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 String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + +} diff --git a/javaxval/src/main/java/org/baeldung/User.java b/javaxval/src/main/java/org/baeldung/javaxval/beanvalidation/User.java similarity index 97% rename from javaxval/src/main/java/org/baeldung/User.java rename to javaxval/src/main/java/org/baeldung/javaxval/beanvalidation/User.java index e2f2732399..cf80266c9d 100644 --- a/javaxval/src/main/java/org/baeldung/User.java +++ b/javaxval/src/main/java/org/baeldung/javaxval/beanvalidation/User.java @@ -1,4 +1,4 @@ -package org.baeldung; +package org.baeldung.javaxval.beanvalidation; import java.time.LocalDate; import java.util.List; diff --git a/javaxval/src/test/java/org/baeldung/javabeanconstraints/bigdecimal/InvoiceUnitTest.java b/javaxval/src/test/java/org/baeldung/javabeanconstraints/bigdecimal/InvoiceUnitTest.java index 525dd7d1ad..860177f4c9 100644 --- a/javaxval/src/test/java/org/baeldung/javabeanconstraints/bigdecimal/InvoiceUnitTest.java +++ b/javaxval/src/test/java/org/baeldung/javabeanconstraints/bigdecimal/InvoiceUnitTest.java @@ -26,7 +26,8 @@ public class InvoiceUnitTest { Invoice invoice = new Invoice(new BigDecimal(10.21), "Book purchased"); Set> violations = validator.validate(invoice); assertThat(violations.size()).isEqualTo(1); - violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("numeric value out of bounds (<3 digits>.<2 digits> expected)")); + violations.forEach(action-> assertThat(action.getMessage()) + .isEqualTo("numeric value out of bounds (<3 digits>.<2 digits> expected)")); } @Test @@ -41,7 +42,8 @@ public class InvoiceUnitTest { Invoice invoice = new Invoice(new BigDecimal(1021.21), "Book purchased"); Set> violations = validator.validate(invoice); assertThat(violations.size()).isEqualTo(1); - violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("numeric value out of bounds (<3 digits>.<2 digits> expected)")); + violations.forEach(action-> assertThat(action.getMessage()) + .isEqualTo("numeric value out of bounds (<3 digits>.<2 digits> expected)")); } @Test @@ -49,7 +51,8 @@ public class InvoiceUnitTest { Invoice invoice = new Invoice(new BigDecimal(000.00), "Book purchased"); Set> violations = validator.validate(invoice); assertThat(violations.size()).isEqualTo(1); - violations.forEach(action-> assertThat(action.getMessage()).isEqualTo("must be greater than 0.0")); + violations.forEach(action-> assertThat(action.getMessage()) + .isEqualTo("must be greater than 0.0")); } @Test diff --git a/javaxval/src/test/java/org/baeldung/javabeanconstraints/validationgroup/RegistrationFormUnitTest.java b/javaxval/src/test/java/org/baeldung/javabeanconstraints/validationgroup/RegistrationFormUnitTest.java new file mode 100644 index 0000000000..f8944524f3 --- /dev/null +++ b/javaxval/src/test/java/org/baeldung/javabeanconstraints/validationgroup/RegistrationFormUnitTest.java @@ -0,0 +1,80 @@ +package org.baeldung.javabeanconstraints.validationgroup; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Set; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class RegistrationFormUnitTest { + private static Validator validator; + + @BeforeClass + public static void setupValidatorInstance() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @Test + public void whenBasicInfoIsNotComplete_thenShouldGiveConstraintViolationsOnlyForBasicInfo() { + RegistrationForm form = buildRegistrationFormWithBasicInfo(); + form.setFirstName(""); + Set> violations = validator.validate(form, BasicInfo.class); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action -> { + assertThat(action.getMessage()).isEqualTo("must not be blank"); + assertThat(action.getPropertyPath().toString()).isEqualTo("firstName"); + }); + } + + @Test + public void whenAdvanceInfoIsNotComplete_thenShouldGiveConstraintViolationsOnlyForAdvanceInfo() { + RegistrationForm form = buildRegistrationFormWithAdvanceInfo(); + form.setZipCode(""); + Set> violations = validator.validate(form, AdvanceInfo.class); + assertThat(violations.size()).isEqualTo(1); + violations.forEach(action -> { + assertThat(action.getMessage()).isEqualTo("must not be blank"); + assertThat(action.getPropertyPath().toString()).isEqualTo("zipCode"); + }); + } + + @Test + public void whenBasicAndAdvanceInfoIsComplete_thenShouldNotGiveConstraintViolations() { + RegistrationForm form = buildRegistrationFormWithBasicAndAdvanceInfo(); + Set> violations = validator.validate(form); + assertThat(violations.size()).isEqualTo(0); + } + + private RegistrationForm buildRegistrationFormWithBasicInfo() { + RegistrationForm form = new RegistrationForm(); + form.setFirstName("devender"); + form.setLastName("kumar"); + form.setEmail("anyemail@yopmail.com"); + form.setPhone("12345"); + return form; + } + + private RegistrationForm buildRegistrationFormWithAdvanceInfo() { + RegistrationForm form = new RegistrationForm(); + return populateAdvanceInfo(form); + } + + private RegistrationForm populateAdvanceInfo(RegistrationForm form) { + form.setCity("Berlin"); + form.setContry("DE"); + form.setStreet("alexa str."); + form.setZipCode("19923"); + form.setHouseNumber("2a"); + return form; + } + + private RegistrationForm buildRegistrationFormWithBasicAndAdvanceInfo() { + RegistrationForm form = buildRegistrationFormWithBasicInfo(); + return populateAdvanceInfo(form); + } +} diff --git a/javaxval/src/test/java/org/baeldung/ValidationIntegrationTest.java b/javaxval/src/test/java/org/baeldung/javaxval/beanvalidation/ValidationIntegrationTest.java similarity index 97% rename from javaxval/src/test/java/org/baeldung/ValidationIntegrationTest.java rename to javaxval/src/test/java/org/baeldung/javaxval/beanvalidation/ValidationIntegrationTest.java index 78745a1af2..6639d60ac6 100644 --- a/javaxval/src/test/java/org/baeldung/ValidationIntegrationTest.java +++ b/javaxval/src/test/java/org/baeldung/javaxval/beanvalidation/ValidationIntegrationTest.java @@ -1,20 +1,18 @@ -package org.baeldung; +package org.baeldung.javaxval.beanvalidation; + +import static org.junit.Assert.assertEquals; import java.time.LocalDate; import java.util.Collections; -import java.util.Iterator; import java.util.Set; -import java.util.Optional; - import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; -import static org.junit.Assert.*; -import org.junit.Test; import org.junit.Before; +import org.junit.Test; public class ValidationIntegrationTest { diff --git a/jersey/pom.xml b/jersey/pom.xml index 708b36ce41..0b4d469e3a 100644 --- a/jersey/pom.xml +++ b/jersey/pom.xml @@ -32,7 +32,7 @@ org.glassfish.jersey.containers jersey-container-grizzly2-servlet - ${jersey.version} + ${jersey.version} org.glassfish.jersey.ext @@ -44,6 +44,21 @@ jersey-bean-validation ${jersey.version} + + org.glassfish.jersey.security + oauth1-client + ${jersey.version} + + + org.glassfish.jersey.security + oauth2-client + ${jersey.version} + + + org.glassfish.jersey.media + jersey-media-sse + ${jersey.version} + org.glassfish.jersey.test-framework jersey-test-framework-core diff --git a/jersey/src/main/java/com/baeldung/jersey/client/JerseyClientHeaders.java b/jersey/src/main/java/com/baeldung/jersey/client/JerseyClientHeaders.java new file mode 100644 index 0000000000..ebcbe1d4ab --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/client/JerseyClientHeaders.java @@ -0,0 +1,189 @@ +package com.baeldung.jersey.client; + +import com.baeldung.jersey.client.filter.AddHeaderOnRequestFilter; +import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; +import org.glassfish.jersey.client.oauth1.AccessToken; +import org.glassfish.jersey.client.oauth1.ConsumerCredentials; +import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport; +import org.glassfish.jersey.client.oauth2.OAuth2ClientSupport; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Feature; +import javax.ws.rs.core.Response; +import javax.ws.rs.sse.InboundSseEvent; +import javax.ws.rs.sse.SseEventSource; + +import static org.glassfish.jersey.client.authentication.HttpAuthenticationFeature.*; + +public class JerseyClientHeaders { + + private static final String BEARER_CONSUMER_SECRET = "my-consumer-secret"; + private static final String BEARER_ACCESS_TOKEN_SECRET = "my-access-token-secret"; + private static final String TARGET = "http://localhost:9998/"; + private static final String MAIN_RESOURCE = "echo-headers"; + private static final String RESOURCE_AUTH_DIGEST = "digest"; + + private static String sseHeaderValue; + + public static Response simpleHeader(String headerKey, String headerValue) { + Client client = ClientBuilder.newClient(); + WebTarget webTarget = client.target(TARGET); + WebTarget resourceWebTarget = webTarget.path(MAIN_RESOURCE); + Invocation.Builder invocationBuilder = resourceWebTarget.request(); + invocationBuilder.header(headerKey, headerValue); + return invocationBuilder.get(); + } + + public static Response simpleHeaderFluently(String headerKey, String headerValue) { + Client client = ClientBuilder.newClient(); + return client.target(TARGET) + .path(MAIN_RESOURCE) + .request() + .header(headerKey, headerValue) + .get(); + } + + public static Response basicAuthenticationAtClientLevel(String username, String password) { + //To simplify we removed de SSL/TLS protection, but it's required to have an encryption + // when using basic authentication schema as it's send only on Base64 encoding + HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(username, password); + Client client = ClientBuilder.newBuilder().register(feature).build(); + return client.target(TARGET) + .path(MAIN_RESOURCE) + .request() + .get(); + } + + public static Response basicAuthenticationAtRequestLevel(String username, String password) { + //To simplify we removed de SSL/TLS protection, but it's required to have an encryption + // when using basic authentication schema as it's send only on Base64 encoding + HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder().build(); + Client client = ClientBuilder.newBuilder().register(feature).build(); + return client.target(TARGET) + .path(MAIN_RESOURCE) + .request() + .property(HTTP_AUTHENTICATION_BASIC_USERNAME, username) + .property(HTTP_AUTHENTICATION_BASIC_PASSWORD, password) + .get(); + } + + public static Response digestAuthenticationAtClientLevel(String username, String password) { + HttpAuthenticationFeature feature = HttpAuthenticationFeature.digest(username, password); + Client client = ClientBuilder.newBuilder().register(feature).build(); + return client.target(TARGET) + .path(MAIN_RESOURCE) + .path(RESOURCE_AUTH_DIGEST) + .request() + .get(); + } + + public static Response digestAuthenticationAtRequestLevel(String username, String password) { + HttpAuthenticationFeature feature = HttpAuthenticationFeature.digest(); + + Client client = ClientBuilder.newBuilder().register(feature).build(); + return client.target(TARGET) + .path(MAIN_RESOURCE) + .path(RESOURCE_AUTH_DIGEST) + .request() + .property(HTTP_AUTHENTICATION_DIGEST_USERNAME, username) + .property(HTTP_AUTHENTICATION_DIGEST_PASSWORD, password) + .get(); + } + + public static Response bearerAuthenticationWithOAuth1AtClientLevel(String token, String consumerKey) { + ConsumerCredentials consumerCredential = new ConsumerCredentials(consumerKey, BEARER_CONSUMER_SECRET); + AccessToken accessToken = new AccessToken(token, BEARER_ACCESS_TOKEN_SECRET); + Feature feature = OAuth1ClientSupport + .builder(consumerCredential) + .feature() + .accessToken(accessToken) + .build(); + + Client client = ClientBuilder.newBuilder().register(feature).build(); + return client.target(TARGET) + .path(MAIN_RESOURCE) + .request() + .get(); + } + + public static Response bearerAuthenticationWithOAuth1AtRequestLevel(String token, String consumerKey) { + ConsumerCredentials consumerCredential = new ConsumerCredentials(consumerKey, BEARER_CONSUMER_SECRET); + AccessToken accessToken = new AccessToken(token, BEARER_ACCESS_TOKEN_SECRET); + Feature feature = OAuth1ClientSupport + .builder(consumerCredential) + .feature() + .build(); + + Client client = ClientBuilder.newBuilder().register(feature).build(); + return client.target(TARGET) + .path(MAIN_RESOURCE) + .request() + .property(OAuth1ClientSupport.OAUTH_PROPERTY_ACCESS_TOKEN, accessToken) + .get(); + } + + public static Response bearerAuthenticationWithOAuth2AtClientLevel(String token) { + Feature feature = OAuth2ClientSupport.feature(token); + + Client client = ClientBuilder.newBuilder().register(feature).build(); + return client.target(TARGET) + .path(MAIN_RESOURCE) + .request() + .get(); + } + + public static Response bearerAuthenticationWithOAuth2AtRequestLevel(String token, String otherToken) { + Feature feature = OAuth2ClientSupport.feature(token); + + Client client = ClientBuilder.newBuilder().register(feature).build(); + return client.target(TARGET) + .path(MAIN_RESOURCE) + .request() + .property(OAuth2ClientSupport.OAUTH2_PROPERTY_ACCESS_TOKEN, otherToken) + .get(); + } + + public static Response filter() { + Client client = ClientBuilder.newBuilder().register(AddHeaderOnRequestFilter.class).build(); + return client.target(TARGET) + .path(MAIN_RESOURCE) + .request() + .get(); + } + + public static Response sendRestrictedHeaderThroughDefaultTransportConnector(String headerKey, String headerValue) { + Client client = ClientBuilder.newClient(); + System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); + + return client.target(TARGET) + .path(MAIN_RESOURCE) + .request() + .header(headerKey, headerValue) + .get(); + } + + public static String simpleSSEHeader() throws InterruptedException { + Client client = ClientBuilder.newBuilder() + .register(AddHeaderOnRequestFilter.class) + .build(); + + WebTarget webTarget = client.target(TARGET) + .path(MAIN_RESOURCE) + .path("events"); + + SseEventSource sseEventSource = SseEventSource.target(webTarget).build(); + sseEventSource.register(JerseyClientHeaders::receiveEvent); + sseEventSource.open(); + Thread.sleep(3_000); + sseEventSource.close(); + + return sseHeaderValue; + } + + private static void receiveEvent(InboundSseEvent event) { + sseHeaderValue = event.readData(); + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/client/filter/AddHeaderOnRequestFilter.java b/jersey/src/main/java/com/baeldung/jersey/client/filter/AddHeaderOnRequestFilter.java new file mode 100644 index 0000000000..a874928c16 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/client/filter/AddHeaderOnRequestFilter.java @@ -0,0 +1,16 @@ +package com.baeldung.jersey.client.filter; + +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientRequestFilter; +import java.io.IOException; + +public class AddHeaderOnRequestFilter implements ClientRequestFilter { + + public static final String FILTER_HEADER_VALUE = "filter-header-value"; + public static final String FILTER_HEADER_KEY = "x-filter-header"; + + @Override + public void filter(ClientRequestContext requestContext) throws IOException { + requestContext.getHeaders().add(FILTER_HEADER_KEY, FILTER_HEADER_VALUE); + } +} diff --git a/jersey/src/main/java/com/baeldung/jersey/server/EchoHeaders.java b/jersey/src/main/java/com/baeldung/jersey/server/EchoHeaders.java new file mode 100644 index 0000000000..a8df3c10a8 --- /dev/null +++ b/jersey/src/main/java/com/baeldung/jersey/server/EchoHeaders.java @@ -0,0 +1,72 @@ +package com.baeldung.jersey.server; + +import com.baeldung.jersey.client.filter.AddHeaderOnRequestFilter; + +import javax.annotation.security.RolesAllowed; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.*; +import javax.ws.rs.sse.OutboundSseEvent; +import javax.ws.rs.sse.Sse; +import javax.ws.rs.sse.SseEventSink; + +@Path("/echo-headers") +public class EchoHeaders { + + static final String REALM_KEY = "realm"; + static final String REALM_VALUE = "Baeldung"; + static final String QOP_KEY = "qop"; + static final String QOP_VALUE = "auth"; + static final String NONCE_KEY = "nonce"; + static final String NONCE_VALUE = "dcd98b7102dd2f0e8b11d0f600bfb0c093"; + static final String OPAQUE_KEY = "opaque"; + static final String OPAQUE_VALUE = "5ccc069c403ebaf9f0171e9517f40e41"; + static final String SSE_HEADER_KEY = "x-sse-header-key"; + + @Context + HttpHeaders headers; + + @GET + public Response getHeadersBack() { + return echoHeaders(); + } + + @RolesAllowed("ADMIN") + @GET + @Path("/digest") + public Response getHeadersBackFromDigestAuthentication() { + // As the Digest authentication require some complex steps to work we'll simulate the process + // https://en.wikipedia.org/wiki/Digest_access_authentication#Example_with_explanation + if (headers.getHeaderString("authorization") == null) { + String authenticationRequired = "Digest " + REALM_KEY + "=\"" + REALM_VALUE + "\", " + QOP_KEY + "=\"" + QOP_VALUE + "\", " + NONCE_KEY + "=\"" + NONCE_VALUE + "\", " + OPAQUE_KEY + "=\"" + OPAQUE_VALUE + "\""; + return Response.status(Response.Status.UNAUTHORIZED) + .header("WWW-Authenticate", authenticationRequired) + .build(); + } else { + return echoHeaders(); + } + } + + @GET + @Path("/events") + @Produces(MediaType.SERVER_SENT_EVENTS) + public void getServerSentEvents(@Context SseEventSink eventSink, @Context Sse sse) { + OutboundSseEvent event = sse.newEventBuilder() + .name("echo-headers") + .data(String.class, headers.getHeaderString(AddHeaderOnRequestFilter.FILTER_HEADER_KEY)) + .build(); + eventSink.send(event); + } + + private Response echoHeaders() { + Response.ResponseBuilder responseBuilder = Response.noContent(); + + headers.getRequestHeaders() + .forEach((k, v) -> { + v.forEach(value -> responseBuilder.header(k, value)); + }); + + return responseBuilder.build(); + } +} diff --git a/jersey/src/test/java/com/baeldung/jersey/server/EchoHeadersUnitTest.java b/jersey/src/test/java/com/baeldung/jersey/server/EchoHeadersUnitTest.java new file mode 100644 index 0000000000..ac2cc2c4eb --- /dev/null +++ b/jersey/src/test/java/com/baeldung/jersey/server/EchoHeadersUnitTest.java @@ -0,0 +1,197 @@ +package com.baeldung.jersey.server; + +import com.baeldung.jersey.client.JerseyClientHeaders; +import com.baeldung.jersey.client.filter.AddHeaderOnRequestFilter; +import org.glassfish.jersey.media.sse.SseFeature; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.junit.Test; + +import javax.ws.rs.core.Application; +import javax.ws.rs.core.Response; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class EchoHeadersUnitTest extends JerseyTest { + + private static final String SIMPLE_HEADER_KEY = "my-header-key"; + private static final String SIMPLE_HEADER_VALUE = "my-header-value"; + private static final String USERNAME = "baeldung"; + private static final String PASSWORD = "super-secret"; + private static final String AUTHORIZATION_HEADER_KEY = "authorization"; + private static final String BEARER_TOKEN_VALUE = "my-token"; + private static final String BEARER_CONSUMER_KEY_VALUE = "my-consumer-key"; + private static final String BEARER_REQUEST_TOKEN_VALUE = "my-request-token"; + + @Test + public void whenCallingSimpleHeader_thenHeadersReturnedBack() { + Response response = JerseyClientHeaders.simpleHeader(SIMPLE_HEADER_KEY, SIMPLE_HEADER_VALUE); + + assertEquals(response.getHeaderString(SIMPLE_HEADER_KEY), SIMPLE_HEADER_VALUE); + } + + @Test + public void whenCallingSimpleHeaderFluently_thenHeadersReturnedBack() { + Response response = JerseyClientHeaders.simpleHeaderFluently(SIMPLE_HEADER_KEY, SIMPLE_HEADER_VALUE); + + assertEquals(response.getHeaderString(SIMPLE_HEADER_KEY), SIMPLE_HEADER_VALUE); + } + + @Test + public void whenCallingBasicAuthenticationAtClientLevel_thenHeadersReturnedBack() { + Response response = JerseyClientHeaders.basicAuthenticationAtClientLevel(USERNAME, PASSWORD); + + assertBasicAuthenticationHeaders(response); + } + + @Test + public void whenCallingBasicAuthenticationAtRequestLevel_thenHeadersReturnedBack() { + Response response = JerseyClientHeaders.basicAuthenticationAtRequestLevel(USERNAME, PASSWORD); + + assertBasicAuthenticationHeaders(response); + } + + @Test + public void whenCallingDigestAuthenticationAtClientLevel_thenHeadersReturnedBack() { + Response response = JerseyClientHeaders.digestAuthenticationAtClientLevel(USERNAME, PASSWORD); + + Map subHeadersMap = parseAuthenticationSubHeader(response, 7); + + assertDigestAuthenticationHeaders(subHeadersMap); + } + + @Test + public void whenCallingDigestAuthenticationAtRequestLevel_thenHeadersReturnedBack() { + Response response = JerseyClientHeaders.digestAuthenticationAtRequestLevel(USERNAME, PASSWORD); + + Map subHeadersMap = parseAuthenticationSubHeader(response, 7); + + assertDigestAuthenticationHeaders(subHeadersMap); + } + + @Test + public void whenCallingBearerAuthenticationWithOAuth1AtClientLevel_thenHeadersReturnedBack() { + Response response = JerseyClientHeaders.bearerAuthenticationWithOAuth1AtClientLevel(BEARER_TOKEN_VALUE, BEARER_CONSUMER_KEY_VALUE); + + Map subHeadersMap = parseAuthenticationSubHeader(response, 6); + + assertBearerAuthenticationHeaders(subHeadersMap); + } + + @Test + public void whenCallingBearerAuthenticationWithOAuth1AtRequestLevel_thenHeadersReturnedBack() { + Response response = JerseyClientHeaders.bearerAuthenticationWithOAuth1AtRequestLevel(BEARER_TOKEN_VALUE, BEARER_CONSUMER_KEY_VALUE); + + Map subHeadersMap = parseAuthenticationSubHeader(response, 6); + + assertBearerAuthenticationHeaders(subHeadersMap); + } + + @Test + public void whenCallingBearerAuthenticationWithOAuth2AtClientLevel_thenHeadersReturnedBack() { + Response response = JerseyClientHeaders.bearerAuthenticationWithOAuth2AtClientLevel(BEARER_TOKEN_VALUE); + + assertEquals("Bearer " + BEARER_TOKEN_VALUE, response.getHeaderString(AUTHORIZATION_HEADER_KEY)); + } + + @Test + public void whenCallingBearerAuthenticationWithOAuth2AtRequestLevel_thenHeadersReturnedBack() { + Response response = JerseyClientHeaders.bearerAuthenticationWithOAuth2AtRequestLevel(BEARER_TOKEN_VALUE, BEARER_REQUEST_TOKEN_VALUE); + + assertEquals("Bearer " + BEARER_REQUEST_TOKEN_VALUE, response.getHeaderString(AUTHORIZATION_HEADER_KEY)); + } + + @Test + public void whenCallingFilter_thenHeadersReturnedBack() { + Response response = JerseyClientHeaders.filter(); + + assertEquals(AddHeaderOnRequestFilter.FILTER_HEADER_VALUE, response.getHeaderString(AddHeaderOnRequestFilter.FILTER_HEADER_KEY)); + } + + @Test + public void whenCallingSendRestrictedHeaderThroughDefaultTransportConnector_thenHeadersReturnedBack() { + Response response = JerseyClientHeaders.sendRestrictedHeaderThroughDefaultTransportConnector("keep-alive", "keep-alive-value"); + + assertEquals("keep-alive-value", response.getHeaderString("keep-alive")); + } + + @Test + public void whenCallingSimpleSSEHeader_thenHeadersReturnedBack() throws InterruptedException { + String sseHeaderBackValue = JerseyClientHeaders.simpleSSEHeader(); + + assertEquals(AddHeaderOnRequestFilter.FILTER_HEADER_VALUE, sseHeaderBackValue); + } + + private void assertBearerAuthenticationHeaders(Map subHeadersMap) { + + assertEquals(BEARER_TOKEN_VALUE, subHeadersMap.get("oauth_token")); + assertEquals(BEARER_CONSUMER_KEY_VALUE, subHeadersMap.get("oauth_consumer_key")); + assertNotNull(subHeadersMap.get("oauth_nonce")); + assertNotNull(subHeadersMap.get("oauth_signature")); + assertNotNull(subHeadersMap.get("oauth_callback")); + assertNotNull(subHeadersMap.get("oauth_signature_method")); + assertNotNull(subHeadersMap.get("oauth_version")); + assertNotNull(subHeadersMap.get("oauth_timestamp")); + } + + private void assertDigestAuthenticationHeaders(Map subHeadersMap) { + assertEquals(EchoHeaders.NONCE_VALUE, subHeadersMap.get(EchoHeaders.NONCE_KEY)); + assertEquals(EchoHeaders.OPAQUE_VALUE, subHeadersMap.get(EchoHeaders.OPAQUE_KEY)); + assertEquals(EchoHeaders.QOP_VALUE, subHeadersMap.get(EchoHeaders.QOP_KEY)); + assertEquals(EchoHeaders.REALM_VALUE, subHeadersMap.get(EchoHeaders.REALM_KEY)); + + assertEquals(USERNAME, subHeadersMap.get("username")); + assertEquals("/echo-headers/digest", subHeadersMap.get("uri")); + assertNotNull(subHeadersMap.get("cnonce")); + assertEquals("00000001", subHeadersMap.get("nc")); + assertNotNull(subHeadersMap.get("response")); + } + + private Map parseAuthenticationSubHeader(Response response, int startAt) { + String authorizationHeader = response.getHeaderString(AUTHORIZATION_HEADER_KEY); + // The substring(startAt) is used to cut off the authentication schema part from the value returned. + String[] subHeadersKeyValue = authorizationHeader.substring(startAt).split(","); + Map subHeadersMap = new HashMap<>(); + + for (String subHeader : subHeadersKeyValue) { + String[] keyValue = subHeader.split("="); + + if (keyValue[1].startsWith("\"")) { + keyValue[1] = keyValue[1].substring(1, keyValue[1].length() - 1); + } + + subHeadersMap.put(keyValue[0].trim(), keyValue[1].trim()); + } + return subHeadersMap; + } + + private void assertBasicAuthenticationHeaders(Response response) { + String base64Credentials = response.getHeaderString(AUTHORIZATION_HEADER_KEY); + // The substring(6) is used to cut the "Basic " part of the value returned, + // as it's used to indicates the authentication schema and does not belong to the credentials + byte[] credentials = Base64.getDecoder().decode(base64Credentials.substring(6)); + String[] credentialsParsed = new String(credentials).split(":"); + + assertEquals(credentialsParsed[0], USERNAME); + assertEquals(credentialsParsed[1], PASSWORD); + } + + @Override + protected Application configure() { + return new ResourceConfig() + .register(EchoHeaders.class); + } + + @Override + public void setUp() throws Exception { + super.setUp(); + // We need this definition here, because if you are running + // the complete suit test the sendingRestrictedHeaderThroughDefaultTransportConnector_shouldReturnThanBack + // will fail if only defined on the client method, since the JerseyTest is created once. + System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); + } +} \ No newline at end of file diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/CustomAuthenticationManager.java b/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/CustomAuthenticationManager.java new file mode 100644 index 0000000000..0a7dd66b24 --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/CustomAuthenticationManager.java @@ -0,0 +1,126 @@ +package com.baeldung.jhipster5.security; + +import com.baeldung.jhipster5.domain.User; +import com.baeldung.jhipster5.security.dto.LoginRequest; +import com.baeldung.jhipster5.security.dto.LoginResponse; +import com.baeldung.jhipster5.service.UserService; +import com.baeldung.jhipster5.service.dto.UserDTO; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.AuthenticationServiceException; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +import java.util.Collection; +import java.util.Collections; +import java.util.stream.Collectors; + +@Component +public class CustomAuthenticationManager implements AuthenticationManager { + + private final static Logger LOG = LoggerFactory.getLogger(CustomAuthenticationManager.class); + + private final String REMOTE_LOGIN_URL = "https://example.com/login"; + + private final RestTemplate restTemplate = new RestTemplate(); + + @Autowired + private UserService userService; + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException { + + LoginRequest loginRequest = new LoginRequest(); + loginRequest.setUsername(authentication.getPrincipal().toString()); + loginRequest.setPassword(authentication.getCredentials().toString()); + + try + { + ResponseEntity response = + restTemplate.postForEntity( + REMOTE_LOGIN_URL, + loginRequest, + LoginResponse.class); + + if(response.getStatusCode().is2xxSuccessful()) + { + // + // Need to create a new local user if this is the first time logging in; this + // is required so they can be issued JWTs. We can use this flow to also keep + // our local use entry up to date with data from the remote service if needed + // (for example, if the first and last name might change, this is where we would + // update the local user entry) + // + + User user = userService.getUserWithAuthoritiesByLogin(authentication.getPrincipal().toString()) + .orElseGet(() -> userService.createUser(createUserDTO(response.getBody(), authentication))); + return createAuthentication(authentication, user); + } + else + { + throw new BadCredentialsException("Invalid username or password"); + } + } + catch (Exception e) + { + LOG.warn("Failed to authenticate", e); + throw new AuthenticationServiceException("Failed to login", e); + } + } + + /** + * Creates a new authentication with basic roles + * @param auth Contains auth details that will be copied into the new one. + * @param user User object representing who is logging in + * @return Authentication + */ + private Authentication createAuthentication(Authentication auth, User user) { + + // + // Honor any roles the user already has set; default is just USER role + // but could be modified after account creation + // + + Collection authorities = user + .getAuthorities() + .stream() + .map(a -> new SimpleGrantedAuthority(a.getName())) + .collect(Collectors.toSet()); + + UsernamePasswordAuthenticationToken token + = new UsernamePasswordAuthenticationToken( + user.getId(), + auth.getCredentials().toString(), + authorities); + + return token; + } + + /** + * Creates a new UserDTO with basic info. + * @param loginResponse Response from peloton login API + * @param authentication Contains user login info (namely username and password) + * @return UserDTO + */ + private UserDTO createUserDTO(LoginResponse loginResponse, Authentication authentication) { + + UserDTO dto = new UserDTO(); + + dto.setActivated(true); + dto.setEmail(loginResponse.getEmail()); + dto.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); + dto.setFirstName(loginResponse.getFirstName()); + dto.setLastName(loginResponse.getLastName()); + + return dto; + } +} diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/dto/LoginRequest.java b/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/dto/LoginRequest.java new file mode 100644 index 0000000000..f45c23fa39 --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/dto/LoginRequest.java @@ -0,0 +1,30 @@ +package com.baeldung.jhipster5.security.dto; + +/** + * Simple DTO representing a login request to a remote service. + */ +public class LoginRequest { + + private String username; + + private String password; + + public LoginRequest() { + } + + 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/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/dto/LoginResponse.java b/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/dto/LoginResponse.java new file mode 100644 index 0000000000..ad1fe37a2f --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/security/dto/LoginResponse.java @@ -0,0 +1,50 @@ +package com.baeldung.jhipster5.security.dto; + +/** + * Simple DTO representing the response of logging in using a remote service. + */ +public class LoginResponse { + + private String username; + + private String firstName; + + private String lastName; + + private String email; + + public LoginResponse() { + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + 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 String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/account.route.ts b/jhipster-5/bookstore-monolith/src/main/webapp/app/account/account.route.ts index f849342e69..cba5d40716 100644 --- a/jhipster-5/bookstore-monolith/src/main/webapp/app/account/account.route.ts +++ b/jhipster-5/bookstore-monolith/src/main/webapp/app/account/account.route.ts @@ -1,8 +1,8 @@ import { Routes } from '@angular/router'; -import { activateRoute, passwordRoute, passwordResetFinishRoute, passwordResetInitRoute, registerRoute, settingsRoute } from './'; +import { settingsRoute } from './'; -const ACCOUNT_ROUTES = [activateRoute, passwordRoute, passwordResetFinishRoute, passwordResetInitRoute, registerRoute, settingsRoute]; +const ACCOUNT_ROUTES = [settingsRoute]; export const accountState: Routes = [ { diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.component.html b/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.component.html index e58d234c22..4fab5c76ac 100644 --- a/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.component.html +++ b/jhipster-5/bookstore-monolith/src/main/webapp/app/layouts/navbar/navbar.component.html @@ -114,12 +114,6 @@ Settings -
  • - - - Password - -
  • @@ -132,12 +126,6 @@ Sign in
  • -
  • - - - Register - -
  • diff --git a/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/login/login.component.html b/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/login/login.component.html index 60d593bd4b..7eb35364b4 100644 --- a/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/login/login.component.html +++ b/jhipster-5/bookstore-monolith/src/main/webapp/app/shared/login/login.component.html @@ -30,14 +30,6 @@ -

    - -
    - You don't have an account yet? - Register a new account -
    diff --git a/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/MockAuthenticationManager.java b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/MockAuthenticationManager.java new file mode 100644 index 0000000000..bdcdba7644 --- /dev/null +++ b/jhipster-5/bookstore-monolith/src/test/java/com/baeldung/jhipster5/security/MockAuthenticationManager.java @@ -0,0 +1,54 @@ +package com.baeldung.jhipster5.security; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Primary; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Component; + +import java.util.Collection; +import java.util.Collections; + +/** + * AuthenticationManager used solely by unit tests. + */ +@Component +@Primary +public class MockAuthenticationManager implements AuthenticationManager +{ + private final static Collection ROLES = + Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")); + + @Autowired + private UserDetailsService userDetailsService; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Override + public Authentication authenticate(Authentication authentication) throws AuthenticationException + { + + UserDetails userDetails = userDetailsService.loadUserByUsername(authentication.getName()); + + if(userDetails == null || !passwordEncoder.matches(authentication.getCredentials().toString(), userDetails.getPassword())) + { + throw new BadCredentialsException("Invalid username/password"); + } + + UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( + authentication.getPrincipal().toString(), + authentication.getCredentials().toString(), + ROLES); + + return token; + } +} diff --git a/jhipster-5/pom.xml b/jhipster-5/pom.xml index df60b01317..cebbe25d8b 100644 --- a/jhipster-5/pom.xml +++ b/jhipster-5/pom.xml @@ -5,7 +5,7 @@ com.baeldung.jhipster jhipster-5 1.0.0-SNAPSHOT - JHipster + jhipster-5 pom diff --git a/jhipster/pom.xml b/jhipster/pom.xml index c50aac0c7a..dd16205706 100644 --- a/jhipster/pom.xml +++ b/jhipster/pom.xml @@ -5,7 +5,7 @@ com.baeldung.jhipster jhipster 1.0.0-SNAPSHOT - JHipster + jhipster pom diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index 83adf1e199..708006fa15 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -3,8 +3,8 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - libraries2 - libraries2 + libraries-2 + libraries-2 com.baeldung diff --git a/libraries-primitive/pom.xml b/libraries-primitive/pom.xml index 9bb58470b2..cddb3ab1fe 100644 --- a/libraries-primitive/pom.xml +++ b/libraries-primitive/pom.xml @@ -7,10 +7,16 @@ com.baeldung libraries-primitive 1.0-SNAPSHOT + libraries-primitive + + + 1.8 + 1.8 + - - + + it.unimi.dsi fastutil 8.2.2 @@ -35,5 +41,18 @@ 1.19 test + + + org.eclipse.collections + eclipse-collections-api + 10.0.0 + + + + org.eclipse.collections + eclipse-collections + 10.0.0 + + - + \ No newline at end of file diff --git a/libraries-primitive/src/test/java/com/baeldung/PrimitiveCollectionsUnitTest.java b/libraries-primitive/src/test/java/com/baeldung/PrimitiveCollectionsUnitTest.java new file mode 100644 index 0000000000..2adecd37fc --- /dev/null +++ b/libraries-primitive/src/test/java/com/baeldung/PrimitiveCollectionsUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung; + +import org.eclipse.collections.api.list.primitive.ImmutableIntList; +import org.eclipse.collections.api.list.primitive.MutableLongList; +import org.eclipse.collections.api.map.primitive.MutableIntIntMap; +import org.eclipse.collections.api.set.primitive.MutableIntSet; +import org.eclipse.collections.impl.factory.primitive.*; +import org.eclipse.collections.impl.list.Interval; +import org.eclipse.collections.impl.list.primitive.IntInterval; +import org.eclipse.collections.impl.map.mutable.primitive.IntIntHashMap; +import org.junit.Test; + +import java.util.stream.DoubleStream; + +import static org.junit.Assert.assertEquals; + + +public class PrimitiveCollectionsUnitTest { + + @Test + public void whenListOfLongHasOneTwoThree_thenSumIsSix() { + MutableLongList longList = LongLists.mutable.of(1L, 2L, 3L); + assertEquals(6, longList.sum()); + } + + @Test + public void whenListOfIntHasOneTwoThree_thenMaxIsThree() { + ImmutableIntList intList = IntLists.immutable.of(1, 2, 3); + assertEquals(3, intList.max()); + } + + @Test + public void whenConvertFromIterableToPrimitive_thenValuesAreEquals() { + Iterable iterable = Interval.oneTo(3); + MutableIntSet intSet = IntSets.mutable.withAll(iterable); + IntInterval intInterval = IntInterval.oneTo(3); + assertEquals(intInterval.toSet(), intSet); + } + + @Test + public void testOperationsOnIntIntMap() { + MutableIntIntMap map = new IntIntHashMap(); + assertEquals(5, map.addToValue(0, 5)); + assertEquals(5, map.get(0)); + assertEquals(3, map.getIfAbsentPut(1, 3)); + } + + @Test + public void whenCreateDoubleStream_thenAverageIsThree() { + DoubleStream doubleStream = DoubleLists + .mutable.with(1.0, 2.0, 3.0, 4.0, 5.0) + .primitiveStream(); + assertEquals(3, doubleStream.average().getAsDouble(), 0.001); + } + + @Test + public void whenCreateMapFromStream_thenValuesMustMatch() { + Iterable integers = Interval.oneTo(3); + MutableIntIntMap map = + IntIntMaps.mutable.from( + integers, + key -> key, + value -> value * value); + MutableIntIntMap expected = IntIntMaps.mutable.empty() + .withKeyValue(1, 1) + .withKeyValue(2, 4) + .withKeyValue(3, 9); + assertEquals(expected, map); + } +} \ No newline at end of file diff --git a/mapstruct/src/main/java/com/baeldung/dto/CustomerDto.java b/mapstruct/src/main/java/com/baeldung/dto/CustomerDto.java new file mode 100644 index 0000000000..617f2c6e0c --- /dev/null +++ b/mapstruct/src/main/java/com/baeldung/dto/CustomerDto.java @@ -0,0 +1,25 @@ +package com.baeldung.dto; + +public class CustomerDto { + + private String forename; + private String surname; + + public String getForename() { + return forename; + } + + public CustomerDto setForename(String forename) { + this.forename = forename; + return this; + } + + public String getSurname() { + return surname; + } + + public CustomerDto setSurname(String surname) { + this.surname = surname; + return this; + } +} diff --git a/mapstruct/src/main/java/com/baeldung/entity/Address.java b/mapstruct/src/main/java/com/baeldung/entity/Address.java new file mode 100644 index 0000000000..4a6edbd75d --- /dev/null +++ b/mapstruct/src/main/java/com/baeldung/entity/Address.java @@ -0,0 +1,35 @@ +package com.baeldung.entity; + +public class Address { + + private String street; + private String postalcode; + private String county; + + public String getStreet() { + return street; + } + + public Address setStreet(String street) { + this.street = street; + return this; + } + + public String getPostalcode() { + return postalcode; + } + + public Address setPostalcode(String postalcode) { + this.postalcode = postalcode; + return this; + } + + public String getCounty() { + return county; + } + + public Address setCounty(String county) { + this.county = county; + return this; + } +} diff --git a/mapstruct/src/main/java/com/baeldung/entity/Customer.java b/mapstruct/src/main/java/com/baeldung/entity/Customer.java new file mode 100644 index 0000000000..cdde6b542a --- /dev/null +++ b/mapstruct/src/main/java/com/baeldung/entity/Customer.java @@ -0,0 +1,25 @@ +package com.baeldung.entity; + +public class Customer { + + private String firstName; + private String lastName; + + public String getFirstName() { + return firstName; + } + + public Customer setFirstName(String firstName) { + this.firstName = firstName; + return this; + } + + public String getLastName() { + return lastName; + } + + public Customer setLastName(String lastName) { + this.lastName = lastName; + return this; + } +} diff --git a/mapstruct/src/main/java/com/baeldung/entity/DeliveryAddress.java b/mapstruct/src/main/java/com/baeldung/entity/DeliveryAddress.java new file mode 100644 index 0000000000..084c5f86ef --- /dev/null +++ b/mapstruct/src/main/java/com/baeldung/entity/DeliveryAddress.java @@ -0,0 +1,55 @@ +package com.baeldung.entity; + +public class DeliveryAddress { + + private String forename; + private String surname; + private String street; + private String postalcode; + private String county; + + public String getForename() { + return forename; + } + + public DeliveryAddress setForename(String forename) { + this.forename = forename; + return this; + } + + public String getSurname() { + return surname; + } + + public DeliveryAddress setSurname(String surname) { + this.surname = surname; + return this; + } + + public String getStreet() { + return street; + } + + public DeliveryAddress setStreet(String street) { + this.street = street; + return this; + } + + public String getPostalcode() { + return postalcode; + } + + public DeliveryAddress setPostalcode(String postalcode) { + this.postalcode = postalcode; + return this; + } + + public String getCounty() { + return county; + } + + public DeliveryAddress setCounty(String county) { + this.county = county; + return this; + } +} diff --git a/mapstruct/src/main/java/com/baeldung/mapper/CustomerDtoMapper.java b/mapstruct/src/main/java/com/baeldung/mapper/CustomerDtoMapper.java new file mode 100644 index 0000000000..2c84f80167 --- /dev/null +++ b/mapstruct/src/main/java/com/baeldung/mapper/CustomerDtoMapper.java @@ -0,0 +1,15 @@ +package com.baeldung.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; + +import com.baeldung.dto.CustomerDto; +import com.baeldung.entity.Customer; + +@Mapper +public interface CustomerDtoMapper { + + @Mapping(source = "firstName", target = "forename") + @Mapping(source = "lastName", target = "surname") + CustomerDto from(Customer customer); +} diff --git a/mapstruct/src/main/java/com/baeldung/mapper/DeliveryAddressMapper.java b/mapstruct/src/main/java/com/baeldung/mapper/DeliveryAddressMapper.java new file mode 100644 index 0000000000..6a337fbb9e --- /dev/null +++ b/mapstruct/src/main/java/com/baeldung/mapper/DeliveryAddressMapper.java @@ -0,0 +1,24 @@ +package com.baeldung.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.MappingTarget; + +import com.baeldung.entity.Address; +import com.baeldung.entity.Customer; +import com.baeldung.entity.DeliveryAddress; + +@Mapper +public interface DeliveryAddressMapper { + + @Mapping(source = "customer.firstName", target = "forename") + @Mapping(source = "customer.lastName", target = "surname") + @Mapping(source = "address.street", target = "street") + @Mapping(source = "address.postalcode", target = "postalcode") + @Mapping(source = "address.county", target = "county") + DeliveryAddress from(Customer customer, Address address); + + @Mapping(source = "address.postalcode", target = "postalcode") + @Mapping(source = "address.county", target = "county") + DeliveryAddress updateAddress(@MappingTarget DeliveryAddress deliveryAddress, Address address); +} diff --git a/mapstruct/src/test/java/com/baeldung/mapper/CustomerDtoMapperUnitTest.java b/mapstruct/src/test/java/com/baeldung/mapper/CustomerDtoMapperUnitTest.java new file mode 100644 index 0000000000..cded90138b --- /dev/null +++ b/mapstruct/src/test/java/com/baeldung/mapper/CustomerDtoMapperUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.mapper; + +import static org.junit.Assert.assertEquals; + +import org.junit.jupiter.api.Test; +import org.mapstruct.factory.Mappers; + +import com.baeldung.dto.CustomerDto; +import com.baeldung.entity.Customer; + +public class CustomerDtoMapperUnitTest { + + private CustomerDtoMapper customerDtoMapper = Mappers.getMapper(CustomerDtoMapper.class); + + @Test + void testGivenCustomer_mapsToCustomerDto() { + + // given + Customer customer = new Customer().setFirstName("Max") + .setLastName("Powers"); + + // when + CustomerDto customerDto = customerDtoMapper.from(customer); + + // then + assertEquals(customerDto.getForename(), customer.getFirstName()); + assertEquals(customerDto.getSurname(), customer.getLastName()); + } +} diff --git a/mapstruct/src/test/java/com/baeldung/mapper/DeliveryAddressMapperUnitTest.java b/mapstruct/src/test/java/com/baeldung/mapper/DeliveryAddressMapperUnitTest.java new file mode 100644 index 0000000000..e2c12fcba3 --- /dev/null +++ b/mapstruct/src/test/java/com/baeldung/mapper/DeliveryAddressMapperUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.mapper; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; + +import org.junit.Test; +import org.mapstruct.factory.Mappers; + +import com.baeldung.entity.Address; +import com.baeldung.entity.Customer; +import com.baeldung.entity.DeliveryAddress; + +public class DeliveryAddressMapperUnitTest { + + private DeliveryAddressMapper deliveryAddressMapper = Mappers.getMapper(DeliveryAddressMapper.class); + + @Test + public void testGivenCustomerAndAddress_mapsToDeliveryAddress() { + + // given + Customer customer = new Customer().setFirstName("Max") + .setLastName("Powers"); + + Address homeAddress = new Address().setStreet("123 Some Street") + .setCounty("Nevada") + .setPostalcode("89123"); + + // when + DeliveryAddress deliveryAddress = deliveryAddressMapper.from(customer, homeAddress); + + // then + assertEquals(deliveryAddress.getForename(), customer.getFirstName()); + assertEquals(deliveryAddress.getSurname(), customer.getLastName()); + assertEquals(deliveryAddress.getStreet(), homeAddress.getStreet()); + assertEquals(deliveryAddress.getCounty(), homeAddress.getCounty()); + assertEquals(deliveryAddress.getPostalcode(), homeAddress.getPostalcode()); + } + + @Test + public void testGivenDeliveryAddressAndSomeOtherAddress_updatesDeliveryAddress() { + + // given + Customer customer = new Customer().setFirstName("Max") + .setLastName("Powers"); + + DeliveryAddress deliveryAddress = new DeliveryAddress().setStreet("123 Some Street") + .setCounty("Nevada") + .setPostalcode("89123"); + + Address otherAddress = new Address().setStreet("456 Some other street") + .setCounty("Arizona") + .setPostalcode("12345"); + + // when + DeliveryAddress updatedDeliveryAddress = deliveryAddressMapper.updateAddress(deliveryAddress, otherAddress); + + // then + assertSame(deliveryAddress, updatedDeliveryAddress); + + assertEquals(deliveryAddress.getStreet(), otherAddress.getStreet()); + assertEquals(deliveryAddress.getCounty(), otherAddress.getCounty()); + assertEquals(deliveryAddress.getPostalcode(), otherAddress.getPostalcode()); + } +} diff --git a/metrics/pom.xml b/metrics/pom.xml index 014931a957..4cd9f3de79 100644 --- a/metrics/pom.xml +++ b/metrics/pom.xml @@ -86,6 +86,24 @@ ${spectator-api.version}
    + + io.astefanutti.metrics.aspectj + metrics-aspectj + ${metrics-aspectj.version} + + + org.slf4j + slf4j-api + + + + + + io.astefanutti.metrics.aspectj + metrics-aspectj-deps + ${metrics-aspectj.version} + + org.assertj assertj-core @@ -104,6 +122,7 @@ 0.57.1 2.0.7.RELEASE 3.11.1 + 1.1.0 diff --git a/metrics/src/main/java/com/baeldung/metrics/aspectj/MetricsAspectJMain.java b/metrics/src/main/java/com/baeldung/metrics/aspectj/MetricsAspectJMain.java new file mode 100644 index 0000000000..5bcf196035 --- /dev/null +++ b/metrics/src/main/java/com/baeldung/metrics/aspectj/MetricsAspectJMain.java @@ -0,0 +1,34 @@ +package com.baeldung.metrics.aspectj; + +import com.codahale.metrics.ConsoleReporter; +import com.codahale.metrics.MetricRegistry; +import com.codahale.metrics.SharedMetricRegistries; +import java.io.PrintStream; +import java.util.concurrent.TimeUnit; + +public class MetricsAspectJMain { + private static final MetricRegistry REGISTRY = new MetricRegistry(); + + public static void main(String args[]) throws InterruptedException { + startReport(); + + ObjectRunner runner = new ObjectRunner(); + + for (int i = 0; i < 5; i++) { + runner.run(); + } + + Thread.sleep(3000L); + } + + private static void startReport() { + SharedMetricRegistries.add(ObjectRunner.REGISTRY_NAME, REGISTRY); + + ConsoleReporter.forRegistry(REGISTRY) + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .outputTo(new PrintStream(System.out)) + .build() + .start(3, TimeUnit.SECONDS); + } +} diff --git a/metrics/src/main/java/com/baeldung/metrics/aspectj/ObjectRunner.java b/metrics/src/main/java/com/baeldung/metrics/aspectj/ObjectRunner.java new file mode 100644 index 0000000000..ffded9bdb6 --- /dev/null +++ b/metrics/src/main/java/com/baeldung/metrics/aspectj/ObjectRunner.java @@ -0,0 +1,22 @@ +package com.baeldung.metrics.aspectj; + +import com.codahale.metrics.annotation.Timed; +import io.astefanutti.metrics.aspectj.Metrics; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Metrics( registry = ObjectRunner.REGISTRY_NAME) +public class ObjectRunner { + + private static final Logger logger = LoggerFactory.getLogger(ObjectRunner.class); + public static final String REGISTRY_NAME = "ObjectRunner"; + + @Timed(name = "timerName") + public void run() { + logger.info("run"); + try { + Thread.sleep(1000L); + } catch (InterruptedException e) { + } + } +} diff --git a/ml/README.md b/ml/README.md new file mode 100644 index 0000000000..f4712a94da --- /dev/null +++ b/ml/README.md @@ -0,0 +1,5 @@ +### Logistic Regression in Java +This is a soft introduction to ML using [deeplearning4j](https://deeplearning4j.org) library + +### Relevant Articles: +- [Logistic Regression in Java](http://www.baeldung.com/) diff --git a/ml/pom.xml b/ml/pom.xml new file mode 100644 index 0000000000..80afcc24f4 --- /dev/null +++ b/ml/pom.xml @@ -0,0 +1,52 @@ + + 4.0.0 + com.baeldung.deeplearning4j + ml + 1.0-SNAPSHOT + Machine Learning + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.nd4j + nd4j-native-platform + ${dl4j.version} + + + org.deeplearning4j + deeplearning4j-core + ${dl4j.version} + + + org.deeplearning4j + deeplearning4j-nn + ${dl4j.version} + + + + org.datavec + datavec-api + ${dl4j.version} + + + org.apache.httpcomponents + httpclient + 4.3.5 + + + + + + + 1.0.0-beta4 + + + \ No newline at end of file diff --git a/ml/src/main/java/com/baeldung/logreg/MnistClassifier.java b/ml/src/main/java/com/baeldung/logreg/MnistClassifier.java new file mode 100644 index 0000000000..1246de973f --- /dev/null +++ b/ml/src/main/java/com/baeldung/logreg/MnistClassifier.java @@ -0,0 +1,168 @@ +package com.baeldung.logreg; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +import org.datavec.api.io.labels.ParentPathLabelGenerator; +import org.datavec.api.split.FileSplit; +import org.datavec.image.loader.NativeImageLoader; +import org.datavec.image.recordreader.ImageRecordReader; +import org.deeplearning4j.datasets.datavec.RecordReaderDataSetIterator; +import org.deeplearning4j.nn.conf.MultiLayerConfiguration; +import org.deeplearning4j.nn.conf.NeuralNetConfiguration; +import org.deeplearning4j.nn.conf.inputs.InputType; +import org.deeplearning4j.nn.conf.layers.ConvolutionLayer; +import org.deeplearning4j.nn.conf.layers.DenseLayer; +import org.deeplearning4j.nn.conf.layers.OutputLayer; +import org.deeplearning4j.nn.conf.layers.SubsamplingLayer; +import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; +import org.deeplearning4j.nn.weights.WeightInit; +import org.deeplearning4j.optimize.listeners.ScoreIterationListener; +import org.deeplearning4j.util.ModelSerializer; +import org.nd4j.evaluation.classification.Evaluation; +import org.nd4j.linalg.activations.Activation; +import org.nd4j.linalg.dataset.api.iterator.DataSetIterator; +import org.nd4j.linalg.dataset.api.preprocessor.DataNormalization; +import org.nd4j.linalg.dataset.api.preprocessor.ImagePreProcessingScaler; +import org.nd4j.linalg.learning.config.Nesterovs; +import org.nd4j.linalg.lossfunctions.LossFunctions; +import org.nd4j.linalg.schedule.MapSchedule; +import org.nd4j.linalg.schedule.ScheduleType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Handwritten digit image classification based on LeNet-5 architecture by Yann LeCun. + * + * This code accompanies the article "Logistic regression in Java" and is heavily based on + * MnistClassifier. + * Some minor changes have been made in order to make article's flow smoother. + * + */ + +public class MnistClassifier { + private static final Logger logger = LoggerFactory.getLogger(MnistClassifier.class); + private static final String basePath = System.getProperty("java.io.tmpdir") + "mnist" + File.separator; + private static final File modelPath = new File(basePath + "mnist-model.zip"); + private static final String dataUrl = "http://github.com/myleott/mnist_png/raw/master/mnist_png.tar.gz"; + + public static void main(String[] args) throws Exception { + // input image sizes in pixels + int height = 28; + int width = 28; + // input image colour depth (1 for gray scale images) + int channels = 1; + // the number of output classes + int outputClasses = 10; + // number of samples that will be propagated through the network in each iteration + int batchSize = 54; + // total number of training epochs + int epochs = 1; + + // initialize a pseudorandom number generator + int seed = 1234; + Random randNumGen = new Random(seed); + + final String path = basePath + "mnist_png" + File.separator; + if (!new File(path).exists()) { + logger.info("Downloading data {}", dataUrl); + String localFilePath = basePath + "mnist_png.tar.gz"; + File file = new File(localFilePath); + if (!file.exists()) { + file.getParentFile() + .mkdirs(); + Utils.downloadAndSave(dataUrl, file); + Utils.extractTarArchive(file, basePath); + } + } else { + logger.info("Using the local data from folder {}", path); + } + + logger.info("Vectorizing the data from folder {}", path); + // vectorization of train data + File trainData = new File(path + "training"); + FileSplit trainSplit = new FileSplit(trainData, NativeImageLoader.ALLOWED_FORMATS, randNumGen); + // use parent directory name as the image label + ParentPathLabelGenerator labelMaker = new ParentPathLabelGenerator(); + ImageRecordReader trainRR = new ImageRecordReader(height, width, channels, labelMaker); + trainRR.initialize(trainSplit); + DataSetIterator train = new RecordReaderDataSetIterator(trainRR, batchSize, 1, outputClasses); + + // pixel values from 0-255 to 0-1 (min-max scaling) + DataNormalization imageScaler = new ImagePreProcessingScaler(); + imageScaler.fit(train); + train.setPreProcessor(imageScaler); + + // vectorization of test data + File testData = new File(path + "testing"); + FileSplit testSplit = new FileSplit(testData, NativeImageLoader.ALLOWED_FORMATS, randNumGen); + ImageRecordReader testRR = new ImageRecordReader(height, width, channels, labelMaker); + testRR.initialize(testSplit); + DataSetIterator test = new RecordReaderDataSetIterator(testRR, batchSize, 1, outputClasses); + // same normalization for better results + test.setPreProcessor(imageScaler); + + logger.info("Network configuration and training..."); + // reduce the learning rate as the number of training epochs increases + // iteration #, learning rate + Map learningRateSchedule = new HashMap<>(); + learningRateSchedule.put(0, 0.06); + learningRateSchedule.put(200, 0.05); + learningRateSchedule.put(600, 0.028); + learningRateSchedule.put(800, 0.0060); + learningRateSchedule.put(1000, 0.001); + + final ConvolutionLayer layer1 = new ConvolutionLayer.Builder(5, 5).nIn(channels) + .stride(1, 1) + .nOut(20) + .activation(Activation.IDENTITY) + .build(); + final SubsamplingLayer layer2 = new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX).kernelSize(2, 2) + .stride(2, 2) + .build(); + // nIn need not specified in later layers + final ConvolutionLayer layer3 = new ConvolutionLayer.Builder(5, 5).stride(1, 1) + .nOut(50) + .activation(Activation.IDENTITY) + .build(); + final DenseLayer layer4 = new DenseLayer.Builder().activation(Activation.RELU) + .nOut(500) + .build(); + final OutputLayer layer5 = new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD).nOut(outputClasses) + .activation(Activation.SOFTMAX) + .build(); + final MultiLayerConfiguration config = new NeuralNetConfiguration.Builder().seed(seed) + .l2(0.0005) // ridge regression value + .updater(new Nesterovs(new MapSchedule(ScheduleType.ITERATION, learningRateSchedule))) + .weightInit(WeightInit.XAVIER) + .list() + .layer(layer1) + .layer(layer2) + .layer(layer3) + .layer(layer2) + .layer(layer4) + .layer(layer5) + .setInputType(InputType.convolutionalFlat(height, width, channels)) + .build(); + + final MultiLayerNetwork model = new MultiLayerNetwork(config); + model.init(); + model.setListeners(new ScoreIterationListener(100)); + logger.info("Total num of params: {}", model.numParams()); + + // evaluation while training (the score should go down) + for (int i = 0; i < epochs; i++) { + model.fit(train); + logger.info("Completed epoch {}", i); + train.reset(); + test.reset(); + } + Evaluation eval = model.evaluate(test); + logger.info(eval.stats()); + + ModelSerializer.writeModel(model, modelPath, true); + logger.info("The MINIST model has been saved in {}", modelPath.getPath()); + } +} \ No newline at end of file diff --git a/ml/src/main/java/com/baeldung/logreg/MnistPrediction.java b/ml/src/main/java/com/baeldung/logreg/MnistPrediction.java new file mode 100644 index 0000000000..56097d9a45 --- /dev/null +++ b/ml/src/main/java/com/baeldung/logreg/MnistPrediction.java @@ -0,0 +1,57 @@ +package com.baeldung.logreg; + +import java.io.File; +import java.io.IOException; + +import javax.swing.JFileChooser; + +import org.datavec.image.loader.NativeImageLoader; +import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; +import org.deeplearning4j.util.ModelSerializer; +import org.nd4j.linalg.api.ndarray.INDArray; +import org.nd4j.linalg.dataset.api.preprocessor.ImagePreProcessingScaler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MnistPrediction { + private static final Logger logger = LoggerFactory.getLogger(MnistPrediction.class); + private static final File modelPath = new File(System.getProperty("java.io.tmpdir") + "mnist" + File.separator + "mnist-model.zip"); + private static final int height = 28; + private static final int width = 28; + private static final int channels = 1; + + /** + * Opens a popup that allows to select a file from the filesystem. + * @return + */ + public static String fileChose() { + JFileChooser fc = new JFileChooser(); + int ret = fc.showOpenDialog(null); + if (ret == JFileChooser.APPROVE_OPTION) { + File file = fc.getSelectedFile(); + return file.getAbsolutePath(); + } else { + return null; + } + } + + public static void main(String[] args) throws IOException { + if (!modelPath.exists()) { + logger.info("The model not found. Have you trained it?"); + return; + } + MultiLayerNetwork model = ModelSerializer.restoreMultiLayerNetwork(modelPath); + String path = fileChose(); + File file = new File(path); + + INDArray image = new NativeImageLoader(height, width, channels).asMatrix(file); + new ImagePreProcessingScaler(0, 1).transform(image); + + // Pass through to neural Net + INDArray output = model.output(image); + + logger.info("File: {}", path); + logger.info("Probabilities: {}", output); + } + +} diff --git a/ml/src/main/java/com/baeldung/logreg/Utils.java b/ml/src/main/java/com/baeldung/logreg/Utils.java new file mode 100644 index 0000000000..fa4be127cd --- /dev/null +++ b/ml/src/main/java/com/baeldung/logreg/Utils.java @@ -0,0 +1,103 @@ +package com.baeldung.logreg; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import org.apache.commons.compress.archivers.ArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Utility class for digit classifier. + * + */ +public class Utils { + + private static final Logger logger = LoggerFactory.getLogger(Utils.class); + + private Utils() { + } + + /** + * Download the content of the given url and save it into a file. + * @param url + * @param file + */ + public static void downloadAndSave(String url, File file) throws IOException { + CloseableHttpClient client = HttpClientBuilder.create() + .build(); + logger.info("Connecting to {}", url); + try (CloseableHttpResponse response = client.execute(new HttpGet(url))) { + HttpEntity entity = response.getEntity(); + if (entity != null) { + logger.info("Downloaded {} bytes", entity.getContentLength()); + try (FileOutputStream outstream = new FileOutputStream(file)) { + logger.info("Saving to the local file"); + entity.writeTo(outstream); + outstream.flush(); + logger.info("Local file saved"); + } + } + } + } + + /** + * Extract a "tar.gz" file into a given folder. + * @param file + * @param folder + */ + public static void extractTarArchive(File file, String folder) throws IOException { + logger.info("Extracting archive {} into folder {}", file.getName(), folder); + // @formatter:off + try (FileInputStream fis = new FileInputStream(file); + BufferedInputStream bis = new BufferedInputStream(fis); + GzipCompressorInputStream gzip = new GzipCompressorInputStream(bis); + TarArchiveInputStream tar = new TarArchiveInputStream(gzip)) { + // @formatter:on + TarArchiveEntry entry; + while ((entry = (TarArchiveEntry) tar.getNextEntry()) != null) { + extractEntry(entry, tar, folder); + } + } + logger.info("Archive extracted"); + } + + /** + * Extract an entry of the input stream into a given folder + * @param entry + * @param tar + * @param folder + * @throws IOException + */ + public static void extractEntry(ArchiveEntry entry, InputStream tar, String folder) throws IOException { + final int bufferSize = 4096; + final String path = folder + entry.getName(); + if (entry.isDirectory()) { + new File(path).mkdirs(); + } else { + int count; + byte[] data = new byte[bufferSize]; + // @formatter:off + try (FileOutputStream os = new FileOutputStream(path); + BufferedOutputStream dest = new BufferedOutputStream(os, bufferSize)) { + // @formatter:off + while ((count = tar.read(data, 0, bufferSize)) != -1) { + dest.write(data, 0, count); + } + } + } + } +} diff --git a/testing-modules/mocks/mock-comparisons/src/main/resources/logback.xml b/ml/src/main/resources/logback.xml similarity index 100% rename from testing-modules/mocks/mock-comparisons/src/main/resources/logback.xml rename to ml/src/main/resources/logback.xml diff --git a/oauth2-framework-impl/README.md b/oauth2-framework-impl/README.md new file mode 100644 index 0000000000..60fefe3415 --- /dev/null +++ b/oauth2-framework-impl/README.md @@ -0,0 +1,3 @@ +### Relevant Articles + +- [Implementing The OAuth 2.0 Authorization Framework Using Java EE](https://www.baeldung.com/java-ee-oauth2-implementation) diff --git a/oauth2-framework-impl/oauth2-authorization-server/pom.xml b/oauth2-framework-impl/oauth2-authorization-server/pom.xml index 8db2150558..6ab7a60f72 100644 --- a/oauth2-framework-impl/oauth2-authorization-server/pom.xml +++ b/oauth2-framework-impl/oauth2-authorization-server/pom.xml @@ -6,6 +6,7 @@ oauth2-authorization-server war + oauth2-authorization-server com.baeldung.oauth2 diff --git a/oauth2-framework-impl/oauth2-client/pom.xml b/oauth2-framework-impl/oauth2-client/pom.xml index e46a44268e..9b2f05c483 100644 --- a/oauth2-framework-impl/oauth2-client/pom.xml +++ b/oauth2-framework-impl/oauth2-client/pom.xml @@ -5,6 +5,7 @@ 4.0.0 oauth2-client war + oauth2-client com.baeldung.oauth2 diff --git a/oauth2-framework-impl/oauth2-resource-server/pom.xml b/oauth2-framework-impl/oauth2-resource-server/pom.xml index 9b58c33472..e6bc860c67 100644 --- a/oauth2-framework-impl/oauth2-resource-server/pom.xml +++ b/oauth2-framework-impl/oauth2-resource-server/pom.xml @@ -5,6 +5,7 @@ 4.0.0 oauth2-resource-server war + oauth2-resource-server com.baeldung.oauth2 diff --git a/oauth2-framework-impl/pom.xml b/oauth2-framework-impl/pom.xml index 281103660b..47d42eaaea 100644 --- a/oauth2-framework-impl/pom.xml +++ b/oauth2-framework-impl/pom.xml @@ -7,6 +7,7 @@ oauth2-framework-impl 1.0-SNAPSHOT pom + oauth2-framework-impl 1.8 diff --git a/patterns/backoff-jitter/pom.xml b/patterns/backoff-jitter/pom.xml index 6b0d016609..739aa87873 100644 --- a/patterns/backoff-jitter/pom.xml +++ b/patterns/backoff-jitter/pom.xml @@ -7,6 +7,7 @@ backoff-jitter 1.0.0-SNAPSHOT pom + backoff-jitter diff --git a/performance-tests/README.md b/performance-tests/README.md index 5af735b708..0064157966 100644 --- a/performance-tests/README.md +++ b/performance-tests/README.md @@ -1,3 +1,10 @@ ### Relevant Articles: - [Performance of Java Mapping Frameworks](http://www.baeldung.com/java-performance-mapping-frameworks) + +### Running + + To run the performance benchmarks: + +1: `mvn clean install` +2: `java -jar target/benchmarks.jar` \ No newline at end of file diff --git a/performance-tests/pom.xml b/performance-tests/pom.xml index d7738780bf..956c0ccfa8 100644 --- a/performance-tests/pom.xml +++ b/performance-tests/pom.xml @@ -1,17 +1,20 @@ - - 4.0.0 + + com.baeldung performance-tests - performance-tests - + 1.0 + jar + parent-modules com.baeldung 1.0.0-SNAPSHOT + performance-tests + ma.glasnost.orika @@ -32,7 +35,16 @@ org.mapstruct mapstruct-jdk8 ${mapstruct-jdk8.version} + true + + + org.mapstruct + mapstruct-processor + 1.2.0.Final + provided + + org.modelmapper modelmapper @@ -46,46 +58,141 @@ org.openjdk.jmh jmh-core - ${jmh-core.version} + ${jmh.version} org.openjdk.jmh jmh-generator-annprocess - ${jmh-generator.version} + ${jmh.version} + provided - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${java.version} - ${java.version} - - - org.mapstruct - mapstruct-processor - ${mapstruct-processor.version} - - - - - - - - + + UTF-8 + + + 1.21 1.5.2 5.5.1 1.0.2 1.2.0.Final 1.1.0 1.6.0.1 + 1.8 1.2.0.Final + 1.21 + 1.21 + 3.7.0 + + + 1.8 + + + benchmarks - \ No newline at end of file + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${javac.target} + ${javac.target} + ${javac.target} + + + org.mapstruct + mapstruct-processor + ${mapstruct-processor.version} + + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.2 + + + package + + shade + + + ${uberjar.name} + + + org.openjdk.jmh.Main + + + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + + + + + + maven-clean-plugin + 2.5 + + + maven-deploy-plugin + 2.8.1 + + + maven-install-plugin + 2.5.1 + + + maven-jar-plugin + 2.4 + + + maven-javadoc-plugin + 2.9.1 + + + maven-resources-plugin + 2.6 + + + maven-site-plugin + 3.3 + + + maven-source-plugin + 2.2.1 + + + maven-surefire-plugin + 2.17 + + + + + + diff --git a/performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java b/performance-tests/src/main/java/com/baeldung/performancetests/MappingFrameworksPerformance.java similarity index 100% rename from performance-tests/src/test/java/com/baeldung/performancetests/benchmark/MappingFrameworksPerformance.java rename to performance-tests/src/main/java/com/baeldung/performancetests/MappingFrameworksPerformance.java diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml index e90d7463bd..98c946a6e9 100644 --- a/persistence-modules/hibernate-mapping/pom.xml +++ b/persistence-modules/hibernate-mapping/pom.xml @@ -5,6 +5,7 @@ hibernate-mapping 1.0.0-SNAPSHOT 4.0.0 + hibernate-mapping com.baeldung diff --git a/persistence-modules/java-cassandra/pom.xml b/persistence-modules/java-cassandra/pom.xml index e7c93bc4e5..3f8367d130 100644 --- a/persistence-modules/java-cassandra/pom.xml +++ b/persistence-modules/java-cassandra/pom.xml @@ -35,6 +35,11 @@ java-driver-core ${datastax-cassandra.version} + + com.datastax.oss + java-driver-query-builder + ${datastax-cassandra.version} + io.netty diff --git a/persistence-modules/java-cassandra/src/main/java/com/baeldung/datastax/cassandra/Application.java b/persistence-modules/java-cassandra/src/main/java/com/baeldung/datastax/cassandra/Application.java index 23140e0455..f067ee8b73 100644 --- a/persistence-modules/java-cassandra/src/main/java/com/baeldung/datastax/cassandra/Application.java +++ b/persistence-modules/java-cassandra/src/main/java/com/baeldung/datastax/cassandra/Application.java @@ -26,7 +26,7 @@ public class Application { KeyspaceRepository keyspaceRepository = new KeyspaceRepository(session); - keyspaceRepository.createKeyspace("testKeyspace", "SimpleStrategy", 1); + keyspaceRepository.createKeyspace("testKeyspace", 1); keyspaceRepository.useKeyspace("testKeyspace"); VideoRepository videoRepository = new VideoRepository(session); diff --git a/persistence-modules/java-cassandra/src/main/java/com/baeldung/datastax/cassandra/repository/KeyspaceRepository.java b/persistence-modules/java-cassandra/src/main/java/com/baeldung/datastax/cassandra/repository/KeyspaceRepository.java index fd4581d055..899481738a 100644 --- a/persistence-modules/java-cassandra/src/main/java/com/baeldung/datastax/cassandra/repository/KeyspaceRepository.java +++ b/persistence-modules/java-cassandra/src/main/java/com/baeldung/datastax/cassandra/repository/KeyspaceRepository.java @@ -1,7 +1,11 @@ package com.baeldung.datastax.cassandra.repository; +import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.core.CqlSession; +import com.datastax.oss.driver.api.querybuilder.SchemaBuilder; +import com.datastax.oss.driver.api.querybuilder.schema.CreateKeyspace; + public class KeyspaceRepository { private final CqlSession session; @@ -9,19 +13,15 @@ public class KeyspaceRepository { this.session = session; } - public void createKeyspace(String keyspaceName, String replicationStrategy, int numberOfReplicas) { - StringBuilder sb = new StringBuilder("CREATE KEYSPACE IF NOT EXISTS ").append(keyspaceName) - .append(" WITH replication = {") - .append("'class':'").append(replicationStrategy) - .append("','replication_factor':").append(numberOfReplicas) - .append("};"); + public void createKeyspace(String keyspaceName, int numberOfReplicas) { + CreateKeyspace createKeyspace = SchemaBuilder.createKeyspace(keyspaceName) + .ifNotExists() + .withSimpleStrategy(numberOfReplicas); - final String query = sb.toString(); - - session.execute(query); + session.execute(createKeyspace.build()); } public void useKeyspace(String keyspace) { - session.execute("USE " + keyspace); + session.execute("USE " + CqlIdentifier.fromCql(keyspace)); } } diff --git a/persistence-modules/java-cassandra/src/main/java/com/baeldung/datastax/cassandra/repository/VideoRepository.java b/persistence-modules/java-cassandra/src/main/java/com/baeldung/datastax/cassandra/repository/VideoRepository.java index 9a09d77072..48eb000eba 100644 --- a/persistence-modules/java-cassandra/src/main/java/com/baeldung/datastax/cassandra/repository/VideoRepository.java +++ b/persistence-modules/java-cassandra/src/main/java/com/baeldung/datastax/cassandra/repository/VideoRepository.java @@ -7,6 +7,12 @@ import com.datastax.oss.driver.api.core.cql.BoundStatement; import com.datastax.oss.driver.api.core.cql.PreparedStatement; import com.datastax.oss.driver.api.core.cql.ResultSet; import com.datastax.oss.driver.api.core.cql.SimpleStatement; +import com.datastax.oss.driver.api.core.type.DataTypes; +import com.datastax.oss.driver.api.querybuilder.QueryBuilder; +import com.datastax.oss.driver.api.querybuilder.SchemaBuilder; +import com.datastax.oss.driver.api.querybuilder.insert.RegularInsert; +import com.datastax.oss.driver.api.querybuilder.schema.CreateTable; +import com.datastax.oss.driver.api.querybuilder.select.Select; import java.util.ArrayList; import java.util.List; @@ -27,15 +33,12 @@ public class VideoRepository { } public void createTable(String keyspace) { - StringBuilder sb = new StringBuilder("CREATE TABLE IF NOT EXISTS ").append(TABLE_NAME).append(" (") - .append("video_id UUID,") - .append("title TEXT,") - .append("creation_date TIMESTAMP,") - .append("PRIMARY KEY(video_id));"); + CreateTable createTable = SchemaBuilder.createTable(TABLE_NAME).ifNotExists() + .withPartitionKey("video_id", DataTypes.UUID) + .withColumn("title", DataTypes.TEXT) + .withColumn("creation_date", DataTypes.TIMESTAMP); - String query = sb.toString(); - - executeStatement(SimpleStatement.newInstance(query), keyspace); + executeStatement(createTable.build(), keyspace); } public UUID insertVideo(Video video) { @@ -47,17 +50,23 @@ public class VideoRepository { video.setId(videoId); - String absoluteTableName = keyspace != null ? keyspace + "." + TABLE_NAME: TABLE_NAME; + RegularInsert insertInto = QueryBuilder.insertInto(TABLE_NAME) + .value("video_id", QueryBuilder.bindMarker()) + .value("title", QueryBuilder.bindMarker()) + .value("creation_date", QueryBuilder.bindMarker()); - StringBuilder sb = new StringBuilder("INSERT INTO ").append(absoluteTableName) - .append("(video_id, title, creation_date) values (:video_id, :title, :creation_date)"); + SimpleStatement insertStatement = insertInto.build(); - PreparedStatement preparedStatement = session.prepare(sb.toString()); + if (keyspace != null) { + insertStatement = insertStatement.setKeyspace(keyspace); + } + + PreparedStatement preparedStatement = session.prepare(insertStatement); BoundStatement statement = preparedStatement.bind() - .setUuid("video_id", video.getId()) - .setString("title", video.getTitle()) - .setInstant("creation_date", video.getCreationDate()); + .setUuid(0, video.getId()) + .setString(1, video.getTitle()) + .setInstant(2, video.getCreationDate()); session.execute(statement); @@ -69,11 +78,9 @@ public class VideoRepository { } public List + + org.xerial + sqlite-jdbc + + + org.apache.derby + derby + ${derby.version} + + + org.hsqldb + hsqldb + ${hsqldb.version} + @@ -83,6 +97,8 @@ 9.0.10 2.23.0 2.0.1.Final + 10.13.1.1 + 2.3.4 diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java index c5c77be56f..6325d2cd2e 100644 --- a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java +++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/boot/config/H2JpaConfig.java @@ -20,6 +20,9 @@ import java.util.Properties; @Configuration @EnableJpaRepositories(basePackages = { "com.baeldung.boot.repository", "com.baeldung.repository" }) @PropertySource("classpath:persistence-generic-entity.properties") +//@PropertySource("classpath:persistence-derby.properties") +//@PropertySource("classpath:persistence-hsqldb.properties") +//@PropertySource("classpath:persistence-sqlite.properties") @EnableTransactionManagement @Profile("default") //only required to allow H2JpaConfig and H2TestProfileJPAConfig to coexist in same project //this demo project is showcasing several ways to achieve the same end, and class-level diff --git a/persistence-modules/spring-boot-persistence/src/main/resources/persistence-derby.properties b/persistence-modules/spring-boot-persistence/src/main/resources/persistence-derby.properties new file mode 100644 index 0000000000..5b5ff05236 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/resources/persistence-derby.properties @@ -0,0 +1,8 @@ +jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver +jdbc.url=jdbc:derby:memory:myD;create=true +jdbc.user=sa +jdbc.pass= + +hibernate.dialect=org.hibernate.dialect.DerbyDialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence/src/main/resources/persistence-hsqldb.properties b/persistence-modules/spring-boot-persistence/src/main/resources/persistence-hsqldb.properties new file mode 100644 index 0000000000..d045a8b7e5 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/resources/persistence-hsqldb.properties @@ -0,0 +1,8 @@ +jdbc.driverClassName=org.hsqldb.jdbc.JDBCDriver +jdbc.url=jdbc:hsqldb:mem:myDb +jdbc.user=sa +jdbc.pass= + +hibernate.dialect=org.hibernate.dialect.HSQLDialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence/src/main/resources/persistence-sqlite.properties b/persistence-modules/spring-boot-persistence/src/main/resources/persistence-sqlite.properties new file mode 100644 index 0000000000..ee16081603 --- /dev/null +++ b/persistence-modules/spring-boot-persistence/src/main/resources/persistence-sqlite.properties @@ -0,0 +1,7 @@ +jdbc.driverClassName=org.sqlite.JDBC +jdbc.url=jdbc:sqlite:memory:myDb?cache=shared +jdbc.user=sa +jdbc.pass=sa +hibernate.dialect=com.baeldung.dialect.SQLiteDialect +hibernate.hbm2ddl.auto=create-drop +hibernate.show_sql=true diff --git a/persistence-modules/spring-data-couchbase-2/pom.xml b/persistence-modules/spring-data-couchbase-2/pom.xml index a857ee538f..f57d9aaa62 100644 --- a/persistence-modules/spring-data-couchbase-2/pom.xml +++ b/persistence-modules/spring-data-couchbase-2/pom.xml @@ -1,4 +1,5 @@ - 4.0.0 org.baeldung @@ -59,13 +60,24 @@ ${spring-framework.version} test + + javax.el + javax.el-api + ${javax.el.version} + + + org.glassfish + javax.el + ${javax.el.version} + - 4.3.4.RELEASE + 4.3.4.RELEASE 2.1.5.RELEASE 5.3.3.Final 2.9.6 + 3.0.0 diff --git a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/SpringContextLiveTest.java b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/SpringContextLiveTest.java index af228735b8..5e20a98a1d 100644 --- a/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/SpringContextLiveTest.java +++ b/persistence-modules/spring-data-couchbase-2/src/test/java/org/baeldung/SpringContextLiveTest.java @@ -9,6 +9,45 @@ import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; +/** + * This LiveTest requires: + * + * 1- Couchbase instance running (e.g. with `docker run -d --name db -p 8091-8096:8091-8096 -p 11210-11211:11210-11211 couchbase`) + * + * + * 2- Couchbase configured with (we can use the console in localhost:8091): + * + * 2.1- Buckets: named 'baeldung' and 'baeldung2' + * + * 2.2- Security: users 'baeldung' and 'baeldung2'. Note: in newer versions an empty password is not allowed, then we have to change the passwords in the project) + * + * 2.3- Spacial View: Add new spacial view (in Index tab) in document 'campus_spatial', view 'byLocation' with the following function: + * {@code + * function (doc) { + * if (doc.location && + * doc._class == "org.baeldung.spring.data.couchbase.model.Campus") { + * emit([doc.location.x, doc.location.y], null); + * } + * }} + * + * 2.4- MapReduce Views: Add new views in document 'campus': + * 2.4.1- view 'all' with function: + * {@code + * function (doc, meta) { + * if(doc._class == "org.baeldung.spring.data.couchbase.model.Campus") { + * emit(meta.id, null); + * } + * }} + * + * 2.4.2- view 'byName' with function: + * {@code + * function (doc, meta) { + * if(doc._class == "org.baeldung.spring.data.couchbase.model.Campus" && + * doc.name) { + * emit(doc.name, null); + * } + * }} + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { MultiBucketCouchbaseConfig.class, MultiBucketIntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) diff --git a/persistence-modules/spring-data-jpa-2/pom.xml b/persistence-modules/spring-data-jpa-2/pom.xml index 08be64670b..3616b5ce18 100644 --- a/persistence-modules/spring-data-jpa-2/pom.xml +++ b/persistence-modules/spring-data-jpa-2/pom.xml @@ -6,7 +6,7 @@ com.baeldung spring-data-jpa-2 - spring-data-jpa + spring-data-jpa-2 parent-boot-2 diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/contexttests/mongoconfig/SpringContextLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/contexttests/mongoconfig/SpringContextLiveTest.java new file mode 100644 index 0000000000..a2a3d1761f --- /dev/null +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/contexttests/mongoconfig/SpringContextLiveTest.java @@ -0,0 +1,26 @@ +package com.baeldung.contexttests.mongoconfig; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.config.MongoConfig; + +/** + * This Live test requires: + * * mongodb instance running on the environment + * + * (e.g. `docker run -d -p 27017:27017 --name bael-mongo mongo`) + * + * + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MongoConfig.class) +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/contexttests/mongoreactiveconfig/SpringContextLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/contexttests/mongoreactiveconfig/SpringContextLiveTest.java new file mode 100644 index 0000000000..d2a946fb90 --- /dev/null +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/contexttests/mongoreactiveconfig/SpringContextLiveTest.java @@ -0,0 +1,26 @@ +package com.baeldung.contexttests.mongoreactiveconfig; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.config.MongoReactiveConfig; + +/** + * This Live test requires: + * * mongodb instance running on the environment + * + * (e.g. `docker run -d -p 27017:27017 --name bael-mongo mongo`) + * + * + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = MongoReactiveConfig.class) +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/contexttests/simplemongoconfig/SpringContextLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/contexttests/simplemongoconfig/SpringContextLiveTest.java new file mode 100644 index 0000000000..6e8905c139 --- /dev/null +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/contexttests/simplemongoconfig/SpringContextLiveTest.java @@ -0,0 +1,26 @@ +package com.baeldung.contexttests.simplemongoconfig; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.baeldung.config.SimpleMongoConfig; + +/** + * This Live test requires: + * * mongodb instance running on the environment + * + * (e.g. `docker run -d -p 27017:27017 --name bael-mongo mongo`) + * + * + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = SimpleMongoConfig.class) +public class SpringContextLiveTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } + +} diff --git a/persistence-modules/spring-hibernate-5/README.md b/persistence-modules/spring-hibernate-5/README.md index adfb152afd..7a18761a7b 100644 --- a/persistence-modules/spring-hibernate-5/README.md +++ b/persistence-modules/spring-hibernate-5/README.md @@ -5,3 +5,6 @@ - [JPA Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries) - [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search) - [@DynamicUpdate with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-dynamicupdate) +- [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache) +- [Deleting Objects with Hibernate](http://www.baeldung.com/delete-with-hibernate) +- [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource) \ No newline at end of file diff --git a/persistence-modules/spring-hibernate-5/pom.xml b/persistence-modules/spring-hibernate-5/pom.xml index e27775c76f..694ab570a5 100644 --- a/persistence-modules/spring-hibernate-5/pom.xml +++ b/persistence-modules/spring-hibernate-5/pom.xml @@ -51,6 +51,11 @@ hibernate-core ${hibernate.version} + + org.hibernate + hibernate-ehcache + ${hibernate.version} + javax.transaction jta diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/cache/dao/AbstractJpaDAO.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/cache/dao/AbstractJpaDAO.java new file mode 100644 index 0000000000..0d002b8fbb --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/cache/dao/AbstractJpaDAO.java @@ -0,0 +1,46 @@ +package com.baeldung.hibernate.cache.dao; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +public abstract class AbstractJpaDAO { + + private Class clazz; + + @PersistenceContext + private EntityManager entityManager; + + public final void setClazz(final Class clazzToSet) { + this.clazz = clazzToSet; + } + + public T findOne(final long id) { + return entityManager.find(clazz, id); + } + + @SuppressWarnings("unchecked") + public List findAll() { + return entityManager.createQuery("from " + clazz.getName()).getResultList(); + } + + public void create(final T entity) { + entityManager.persist(entity); + } + + public T update(final T entity) { + return entityManager.merge(entity); + } + + public void delete(final T entity) { + entityManager.remove(entity); + } + + public void deleteById(final long entityId) { + final T entity = findOne(entityId); + delete(entity); + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/cache/dao/FooDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/cache/dao/FooDao.java new file mode 100644 index 0000000000..68c94fc0e3 --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/cache/dao/FooDao.java @@ -0,0 +1,17 @@ +package com.baeldung.hibernate.cache.dao; + +import com.baeldung.hibernate.cache.model.Foo; +import org.springframework.stereotype.Repository; + +@Repository +public class FooDao extends AbstractJpaDAO implements IFooDao { + + public FooDao() { + super(); + + setClazz(Foo.class); + } + + // API + +} diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/cache/dao/IFooDao.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/cache/dao/IFooDao.java new file mode 100644 index 0000000000..0a6d4bdbd6 --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/cache/dao/IFooDao.java @@ -0,0 +1,21 @@ +package com.baeldung.hibernate.cache.dao; + +import java.util.List; + +import com.baeldung.hibernate.cache.model.Foo; + +public interface IFooDao { + + Foo findOne(long id); + + List findAll(); + + void create(Foo entity); + + Foo update(Foo entity); + + void delete(Foo entity); + + void deleteById(long entityId); + +} diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/cache/model/Bar.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/cache/model/Bar.java new file mode 100644 index 0000000000..cd8f3a57cc --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/cache/model/Bar.java @@ -0,0 +1,102 @@ +package com.baeldung.hibernate.cache.model; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.OrderBy; + +@Entity +public class Bar implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + @Column(nullable = false) + private String name; + + @OneToMany(mappedBy = "bar", fetch = FetchType.EAGER, cascade = CascadeType.ALL) + @OrderBy("name ASC") + List fooList; + + public Bar() { + super(); + } + + public Bar(final String name) { + super(); + + this.name = name; + } + + // API + + public long getId() { + return id; + } + + public void setId(final long id) { + + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public List getFooList() { + return fooList; + } + + public void setFooList(final List fooList) { + this.fooList = fooList; + } + + // + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Bar other = (Bar) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Bar [name=").append(name).append("]"); + return builder.toString(); + } + +} diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/cache/model/Foo.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/cache/model/Foo.java new file mode 100644 index 0000000000..902d76e2cc --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/cache/model/Foo.java @@ -0,0 +1,92 @@ +package com.baeldung.hibernate.cache.model; + +import org.hibernate.annotations.CacheConcurrencyStrategy; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +@Cacheable +@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) +public class Foo implements Serializable { + + private static final long serialVersionUID = 1L; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + this.name = name; + } + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "ID") + private Long id; + @Column(name = "NAME") + private String name; + + @ManyToOne(targetEntity = Bar.class, fetch = FetchType.EAGER) + @JoinColumn(name = "BAR_ID") + private Bar bar; + + public Bar getBar() { + return bar; + } + + public void setBar(final Bar bar) { + this.bar = bar; + } + + public Long getId() { + return id; + } + + public void setId(final Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Foo other = (Foo) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Foo [name=").append(name).append("]"); + return builder.toString(); + } + +} diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/cache/service/FooService.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/cache/service/FooService.java new file mode 100644 index 0000000000..222968f98f --- /dev/null +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/cache/service/FooService.java @@ -0,0 +1,37 @@ +package com.baeldung.hibernate.cache.service; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.hibernate.cache.dao.IFooDao; +import com.baeldung.hibernate.cache.model.Foo; + +@Service +@Transactional +public class FooService { + + @Autowired + private IFooDao dao; + + public FooService() { + super(); + } + + // API + + public void create(final Foo entity) { + dao.create(entity); + } + + public Foo findOne(final long id) { + return dao.findOne(id); + } + + public List findAll() { + return dao.findAll(); + } + +} diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceJNDIConfig.java similarity index 92% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceJNDIConfig.java index 56ba68dcbb..5f12dc4f5e 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJNDIConfig.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceJNDIConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.spring; import java.util.Properties; @@ -24,8 +24,8 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement @PropertySource("classpath:persistence-jndi.properties") -@ComponentScan("org.baeldung.persistence") -@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao") +@ComponentScan("com.baeldung.hibernate.cache") +@EnableJpaRepositories(basePackages = "com.baeldung.hibernate.cache.dao") public class PersistenceJNDIConfig { @Autowired @@ -35,7 +35,7 @@ public class PersistenceJNDIConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan("org.baeldung.persistence.model"); + em.setPackagesToScan("com.baeldung.hibernate.cache.model"); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigL2Cache.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceJPAConfigL2Cache.java similarity index 93% rename from persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigL2Cache.java rename to persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceJPAConfigL2Cache.java index a236cf2331..93bcb30c5f 100644 --- a/persistence-modules/spring-jpa/src/main/java/org/baeldung/config/PersistenceJPAConfigL2Cache.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/spring/PersistenceJPAConfigL2Cache.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.spring; import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; @@ -23,8 +23,8 @@ import java.util.Properties; @Configuration @EnableTransactionManagement @PropertySource({ "classpath:persistence-h2.properties" }) -@ComponentScan({ "org.baeldung.persistence" }) -@EnableJpaRepositories(basePackages = { "org.baeldung.persistence.dao", "org.baeldung.persistence.repository" }) +@ComponentScan({ "com.baeldung.hibernate.cache" }) +@EnableJpaRepositories(basePackages = { "com.baeldung.hibernate.cache.dao"}) public class PersistenceJPAConfigL2Cache { @Autowired @@ -50,7 +50,7 @@ public class PersistenceJPAConfigL2Cache { } protected String[] getPackagesToScan() { - return new String[] { "org.baeldung.persistence.model" }; + return new String[] { "com.baeldung.hibernate.cache.model" }; } @Bean diff --git a/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties b/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties index 5a137e2310..e3544d354a 100644 --- a/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties +++ b/persistence-modules/spring-hibernate-5/src/main/resources/persistence-h2.properties @@ -9,6 +9,9 @@ jdbc.pass= hibernate.dialect=org.hibernate.dialect.H2Dialect hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop +hibernate.cache.use_second_level_cache=true +hibernate.cache.use_query_cache=true +hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory # hibernate.search.X hibernate.search.default.directory_provider = filesystem diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence-jndi.properties b/persistence-modules/spring-hibernate-5/src/main/resources/persistence-jndi.properties similarity index 100% rename from persistence-modules/spring-jpa/src/main/resources/persistence-jndi.properties rename to persistence-modules/spring-hibernate-5/src/main/resources/persistence-jndi.properties diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java similarity index 50% rename from persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java index e5fb728a0a..3a2f227793 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/deletion/config/PersistenceJPAConfigDeletion.java @@ -1,6 +1,6 @@ -package org.baeldung.persistence.deletion.config; +package com.baeldung.persistence.deletion.config; -import org.baeldung.config.PersistenceJPAConfigL2Cache; +import com.baeldung.spring.PersistenceJPAConfigL2Cache; public class PersistenceJPAConfigDeletion extends PersistenceJPAConfigL2Cache { @@ -10,6 +10,6 @@ public class PersistenceJPAConfigDeletion extends PersistenceJPAConfigL2Cache { @Override protected String[] getPackagesToScan() { - return new String[] { "org.baeldung.persistence.deletion.model", "org.baeldung.persistence.model" }; + return new String[] { "com.baeldung.persistence.deletion.model", "com.baeldung.persistence.model" }; } } \ No newline at end of file diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Bar.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/deletion/model/Bar.java similarity index 95% rename from persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Bar.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/deletion/model/Bar.java index 26c4846fd2..85efd573ca 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Bar.java +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/deletion/model/Bar.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.deletion.model; +package com.baeldung.persistence.deletion.model; import javax.persistence.*; import java.util.ArrayList; diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Baz.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/deletion/model/Baz.java similarity index 94% rename from persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Baz.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/deletion/model/Baz.java index 4fb3f8965e..bea97154d4 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Baz.java +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/deletion/model/Baz.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.deletion.model; +package com.baeldung.persistence.deletion.model; import javax.persistence.*; diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Foo.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/deletion/model/Foo.java similarity index 95% rename from persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Foo.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/deletion/model/Foo.java index 00fc34c166..f0d57c5b6e 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/deletion/model/Foo.java +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/deletion/model/Foo.java @@ -1,4 +1,4 @@ -package org.baeldung.persistence.deletion.model; +package com.baeldung.persistence.deletion.model; import org.hibernate.annotations.Where; diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/service/DeletionIntegrationTest.java similarity index 94% rename from persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/service/DeletionIntegrationTest.java index 0dbb7dbfe8..dfc944f649 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/DeletionIntegrationTest.java +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/service/DeletionIntegrationTest.java @@ -1,9 +1,5 @@ -package org.baeldung.persistence.service; +package com.baeldung.persistence.service; -import org.baeldung.persistence.deletion.config.PersistenceJPAConfigDeletion; -import org.baeldung.persistence.deletion.model.Bar; -import org.baeldung.persistence.deletion.model.Baz; -import org.baeldung.persistence.deletion.model.Foo; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -15,6 +11,11 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; +import com.baeldung.persistence.deletion.config.PersistenceJPAConfigDeletion; +import com.baeldung.persistence.deletion.model.Bar; +import com.baeldung.persistence.deletion.model.Baz; +import com.baeldung.persistence.deletion.model.Foo; + import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java similarity index 89% rename from persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java rename to persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java index 4de8d321d5..e3436d762e 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/persistence/service/SecondLevelCacheIntegrationTest.java @@ -1,9 +1,13 @@ -package org.baeldung.persistence.service; +package com.baeldung.persistence.service; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.hamcrest.Matchers.greaterThan; +import static org.junit.Assert.assertThat; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; -import net.sf.ehcache.CacheManager; -import org.baeldung.config.PersistenceJPAConfigL2Cache; -import org.baeldung.persistence.model.Bar; -import org.baeldung.persistence.model.Foo; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -15,13 +19,12 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionTemplate; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; +import com.baeldung.hibernate.cache.model.Bar; +import com.baeldung.hibernate.cache.model.Foo; +import com.baeldung.hibernate.cache.service.FooService; +import com.baeldung.spring.PersistenceJPAConfigL2Cache; -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertThat; +import net.sf.ehcache.CacheManager; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class) @@ -45,7 +48,7 @@ public class SecondLevelCacheIntegrationTest { final Foo foo = new Foo(randomAlphabetic(6)); fooService.create(foo); fooService.findOne(foo.getId()); - final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.baeldung.persistence.model.Foo").getSize(); + final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("com.baeldung.hibernate.cache.model.Foo").getSize(); assertThat(size, greaterThan(0)); } @@ -65,7 +68,7 @@ public class SecondLevelCacheIntegrationTest { return nativeQuery.executeUpdate(); }); - final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("org.baeldung.persistence.model.Foo").getSize(); + final int size = CacheManager.ALL_CACHE_MANAGERS.get(0).getCache("com.baeldung.hibernate.cache.model.Foo").getSize(); assertThat(size, greaterThan(0)); } diff --git a/persistence-modules/spring-jpa/README.md b/persistence-modules/spring-jpa/README.md index e856e4808e..d04e9f6f41 100644 --- a/persistence-modules/spring-jpa/README.md +++ b/persistence-modules/spring-jpa/README.md @@ -7,12 +7,8 @@ - [The DAO with JPA and Spring](http://www.baeldung.com/spring-dao-jpa) - [JPA Pagination](http://www.baeldung.com/jpa-pagination) - [Sorting with JPA](http://www.baeldung.com/jpa-sort) -- [Hibernate Second-Level Cache](http://www.baeldung.com/hibernate-second-level-cache) -- [Spring, Hibernate and a JNDI Datasource](http://www.baeldung.com/spring-persistence-jpa-jndi-datasource) -- [Deleting Objects with Hibernate](http://www.baeldung.com/delete-with-hibernate) - [Self-Contained Testing Using an In-Memory Database](http://www.baeldung.com/spring-jpa-test-in-memory-database) - [A Guide to Spring AbstractRoutingDatasource](http://www.baeldung.com/spring-abstract-routing-data-source) -- [A Guide to Hibernate with Spring 4](http://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) - [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) - [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries) diff --git a/persistence-modules/spring-jpa/pom.xml b/persistence-modules/spring-jpa/pom.xml index 0961cabaff..792f3918b6 100644 --- a/persistence-modules/spring-jpa/pom.xml +++ b/persistence-modules/spring-jpa/pom.xml @@ -44,11 +44,6 @@ hibernate-entitymanager ${hibernate.version} - - org.hibernate - hibernate-ehcache - ${hibernate.version} - xml-apis xml-apis diff --git a/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties b/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties index 716a96fde3..a3060cc796 100644 --- a/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties +++ b/persistence-modules/spring-jpa/src/main/resources/persistence-h2.properties @@ -7,7 +7,4 @@ jdbc.pass= # hibernate.X hibernate.dialect=org.hibernate.dialect.H2Dialect hibernate.show_sql=true -hibernate.hbm2ddl.auto=create-drop -hibernate.cache.use_second_level_cache=true -hibernate.cache.use_query_cache=true -hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory \ No newline at end of file +hibernate.hbm2ddl.auto=create-drop \ No newline at end of file diff --git a/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextIntegrationTest.java index 822cbb8ed5..9b0cdf180f 100644 --- a/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -1,6 +1,6 @@ package com.baeldung; -import org.baeldung.config.PersistenceJPAConfigL2Cache; +import org.baeldung.config.PersistenceJPAConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.annotation.DirtiesContext; @@ -10,7 +10,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) @WebAppConfiguration @DirtiesContext public class SpringContextIntegrationTest { diff --git a/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextTest.java index 291e49d0c4..de333eef91 100644 --- a/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextTest.java +++ b/persistence-modules/spring-jpa/src/test/java/com/baeldung/SpringContextTest.java @@ -1,6 +1,6 @@ package com.baeldung; -import org.baeldung.config.PersistenceJPAConfigL2Cache; +import org.baeldung.config.PersistenceJPAConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.annotation.DirtiesContext; @@ -10,7 +10,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) @WebAppConfiguration @DirtiesContext public class SpringContextTest { diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java index bf49a431e1..76c34affb9 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java @@ -16,7 +16,6 @@ import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.baeldung.config.PersistenceJPAConfig; -import org.baeldung.config.PersistenceJPAConfigL2Cache; import org.baeldung.persistence.model.Foo; import org.junit.Before; import org.junit.Test; @@ -28,7 +27,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) @DirtiesContext public class FooPaginationPersistenceIntegrationTest { diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java index 45316cf06c..e1b53c8ded 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java @@ -3,7 +3,6 @@ package org.baeldung.persistence.service; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import org.baeldung.config.PersistenceJPAConfig; -import org.baeldung.config.PersistenceJPAConfigL2Cache; import org.baeldung.persistence.model.Foo; import org.junit.Assert; import org.junit.Test; @@ -18,7 +17,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) @DirtiesContext public class FooServicePersistenceIntegrationTest { diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java index 61a3bfd565..40249b4b30 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java @@ -10,7 +10,7 @@ import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; -import org.baeldung.config.PersistenceJPAConfigL2Cache; +import org.baeldung.config.PersistenceJPAConfig; import org.baeldung.persistence.model.Bar; import org.baeldung.persistence.model.Foo; import org.junit.Test; @@ -21,7 +21,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) @DirtiesContext @SuppressWarnings("unchecked") public class FooServiceSortingIntegrationTest { diff --git a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java index 50fdf5f0f3..c530003ac1 100644 --- a/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java +++ b/persistence-modules/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java @@ -10,7 +10,6 @@ import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.baeldung.config.PersistenceJPAConfig; -import org.baeldung.config.PersistenceJPAConfigL2Cache; import org.baeldung.persistence.model.Foo; import org.junit.Test; import org.junit.runner.RunWith; @@ -21,7 +20,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) @DirtiesContext public class FooServiceSortingWitNullsManualIntegrationTest { diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/config/PersistenceConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/config/PersistenceConfig.java index 717b9c3aa0..66b540a692 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/config/PersistenceConfig.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/config/PersistenceConfig.java @@ -26,7 +26,7 @@ import com.google.common.base.Preconditions; @PropertySource({ "classpath:persistence-${envTarget:h2}.properties" }) @ComponentScan({ "com.baeldung.spring.data.persistence" }) // @ImportResource("classpath*:springDataPersistenceConfig.xml") -@EnableJpaRepositories(basePackages = "com.baeldung.spring.data.persistence.dao") +@EnableJpaRepositories(basePackages = { "com.baeldung.spring.data.persistence.dao", "com.baeldung.spring.data.persistence.jpaquery" }) public class PersistenceConfig { @Autowired diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/dao/user/UserRepository.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/jpaquery/UserRepository.java similarity index 98% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/dao/user/UserRepository.java rename to persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/jpaquery/UserRepository.java index e8f95302ef..f22970c401 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/dao/user/UserRepository.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/jpaquery/UserRepository.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.data.persistence.dao.user; +package com.baeldung.spring.data.persistence.jpaquery; import java.time.LocalDate; import java.util.Collection; diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/dao/user/UserRepositoryCustom.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCustom.java similarity index 86% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/dao/user/UserRepositoryCustom.java rename to persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCustom.java index ff92159077..8bfcb93158 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/dao/user/UserRepositoryCustom.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCustom.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.data.persistence.dao.user; +package com.baeldung.spring.data.persistence.jpaquery; import java.util.Collection; import java.util.List; diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/dao/user/UserRepositoryCustomImpl.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCustomImpl.java similarity index 97% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/dao/user/UserRepositoryCustomImpl.java rename to persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCustomImpl.java index 8bd8217e83..f264ca0b44 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/dao/user/UserRepositoryCustomImpl.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCustomImpl.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.data.persistence.dao.user; +package com.baeldung.spring.data.persistence.jpaquery; import java.util.ArrayList; import java.util.Collection; diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/dao/user/UserRepositoryCommon.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCommon.java similarity index 99% rename from persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/dao/user/UserRepositoryCommon.java rename to persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCommon.java index d002ff7575..69ddbb9b9f 100644 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/dao/user/UserRepositoryCommon.java +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryCommon.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.data.persistence.dao.user; +package com.baeldung.spring.data.persistence.jpaquery; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; @@ -19,6 +19,7 @@ import javax.persistence.EntityManager; import javax.persistence.Query; import com.baeldung.spring.data.persistence.config.PersistenceConfig; +import com.baeldung.spring.data.persistence.jpaquery.UserRepository; import com.baeldung.spring.data.persistence.model.User; import org.junit.After; import org.junit.Test; diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/dao/user/UserRepositoryIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryIntegrationTest.java similarity index 96% rename from persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/dao/user/UserRepositoryIntegrationTest.java rename to persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryIntegrationTest.java index 2a9bffaeae..3bffb51917 100644 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/dao/user/UserRepositoryIntegrationTest.java +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/jpaquery/UserRepositoryIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.data.persistence.dao.user; +package com.baeldung.spring.data.persistence.jpaquery; import static org.assertj.core.api.Assertions.assertThat; diff --git a/play-framework/introduction/.gitignore b/play-framework/introduction/.gitignore index eb372fc719..e497f3fc67 100644 --- a/play-framework/introduction/.gitignore +++ b/play-framework/introduction/.gitignore @@ -1,6 +1,7 @@ logs target /.idea +/.g8 /.idea_modules /.classpath /.project diff --git a/play-framework/introduction/LICENSE b/play-framework/introduction/LICENSE deleted file mode 100644 index 4baedcb95f..0000000000 --- a/play-framework/introduction/LICENSE +++ /dev/null @@ -1,8 +0,0 @@ -This software is licensed under the Apache 2 license, quoted below. - -Licensed under the Apache License, Version 2.0 (the "License"); you may not use this project except in compliance with -the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. - -Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific -language governing permissions and limitations under the License. \ No newline at end of file diff --git a/play-framework/introduction/README b/play-framework/introduction/README deleted file mode 100644 index f21d092edf..0000000000 --- a/play-framework/introduction/README +++ /dev/null @@ -1,49 +0,0 @@ -This is your new Play application -================================= - -This file will be packaged with your application when using `activator dist`. - -There are several demonstration files available in this template. - -Controllers -=========== - -- HomeController.java: - - Shows how to handle simple HTTP requests. - -- AsyncController.java: - - Shows how to do asynchronous programming when handling a request. - -- CountController.java: - - Shows how to inject a component into a controller and use the component when - handling requests. - -Components -========== - -- Module.java: - - Shows how to use Guice to bind all the components needed by your application. - -- Counter.java: - - An example of a component that contains state, in this case a simple counter. - -- ApplicationTimer.java: - - An example of a component that starts when the application starts and stops - when the application stops. - -Filters -======= - -- Filters.java: - - Creates the list of HTTP filters used by your application. - -- ExampleFilter.java - - A simple filter that adds a header to every response. \ No newline at end of file diff --git a/play-framework/introduction/app/Filters.java b/play-framework/introduction/app/Filters.java deleted file mode 100644 index 255de8ca93..0000000000 --- a/play-framework/introduction/app/Filters.java +++ /dev/null @@ -1,46 +0,0 @@ -import javax.inject.*; -import play.*; -import play.mvc.EssentialFilter; -import play.http.HttpFilters; -import play.mvc.*; - -import filters.ExampleFilter; - -/** - * This class configures filters that run on every request. This - * class is queried by Play to get a list of filters. - * - * Play will automatically use filters from any class called - * Filters that is placed the root package. You can load filters - * from a different class by adding a `play.http.filters` setting to - * the application.conf configuration file. - */ -@Singleton -public class Filters implements HttpFilters { - - private final Environment env; - private final EssentialFilter exampleFilter; - - /** - * @param env Basic environment settings for the current application. - * @param exampleFilter A demonstration filter that adds a header to - */ - @Inject - public Filters(Environment env, ExampleFilter exampleFilter) { - this.env = env; - this.exampleFilter = exampleFilter; - } - - @Override - public EssentialFilter[] filters() { - // Use the example filter if we're running development mode. If - // we're running in production or test mode then don't use any - // filters at all. - if (env.mode().equals(Mode.DEV)) { - return new EssentialFilter[] { exampleFilter }; - } else { - return new EssentialFilter[] {}; - } - } - -} diff --git a/play-framework/introduction/app/Module.java b/play-framework/introduction/app/Module.java deleted file mode 100644 index 6e7d1766ef..0000000000 --- a/play-framework/introduction/app/Module.java +++ /dev/null @@ -1,31 +0,0 @@ -import com.google.inject.AbstractModule; -import java.time.Clock; - -import services.ApplicationTimer; -import services.AtomicCounter; -import services.Counter; - -/** - * This class is a Guice module that tells Guice how to bind several - * different types. This Guice module is created when the Play - * application starts. - * - * Play will automatically use any class called `Module` that is in - * the root package. You can create modules in other locations by - * adding `play.modules.enabled` settings to the `application.conf` - * configuration file. - */ -public class Module extends AbstractModule { - - @Override - public void configure() { - // Use the system clock as the default implementation of Clock - bind(Clock.class).toInstance(Clock.systemDefaultZone()); - // Ask Guice to create an instance of ApplicationTimer when the - // application starts. - bind(ApplicationTimer.class).asEagerSingleton(); - // Set AtomicCounter as the implementation for Counter. - bind(Counter.class).to(AtomicCounter.class); - } - -} diff --git a/play-framework/introduction/app/controllers/AsyncController.java b/play-framework/introduction/app/controllers/AsyncController.java deleted file mode 100644 index 92c84bb755..0000000000 --- a/play-framework/introduction/app/controllers/AsyncController.java +++ /dev/null @@ -1,64 +0,0 @@ -package controllers; - -import akka.actor.ActorSystem; - -import javax.inject.*; - -import play.*; -import play.mvc.*; - -import java.util.concurrent.Executor; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.TimeUnit; - -import scala.concurrent.duration.Duration; -import scala.concurrent.ExecutionContextExecutor; - -/** - * This controller contains an action that demonstrates how to write - * simple asynchronous code in a controller. It uses a timer to - * asynchronously delay sending a response for 1 second. - * - * @param actorSystem We need the {@link ActorSystem}'s - * {@link Scheduler} to run code after a delay. - * @param exec We need a Java {@link Executor} to apply the result - * of the {@link CompletableFuture} and a Scala - * {@link ExecutionContext} so we can use the Akka {@link Scheduler}. - * An {@link ExecutionContextExecutor} implements both interfaces. - */ -@Singleton -public class AsyncController extends Controller { - - private final ActorSystem actorSystem; - private final ExecutionContextExecutor exec; - - @Inject - public AsyncController(ActorSystem actorSystem, ExecutionContextExecutor exec) { - this.actorSystem = actorSystem; - this.exec = exec; - } - - /** - * An action that returns a plain text message after a delay - * of 1 second. - *

    - * The configuration in the routes file means that this method - * will be called when the application receives a GET request with - * a path of /message. - */ - public CompletionStage message() { - return getFutureMessage(1, TimeUnit.SECONDS).thenApplyAsync(Results::ok, exec); - } - - private CompletionStage getFutureMessage(long time, TimeUnit timeUnit) { - CompletableFuture future = new CompletableFuture<>(); - actorSystem.scheduler().scheduleOnce( - Duration.create(time, timeUnit), - () -> future.complete("Hi!"), - exec - ); - return future; - } - -} diff --git a/play-framework/introduction/app/controllers/CountController.java b/play-framework/introduction/app/controllers/CountController.java deleted file mode 100644 index 02fcb15f8e..0000000000 --- a/play-framework/introduction/app/controllers/CountController.java +++ /dev/null @@ -1,35 +0,0 @@ -package controllers; - -import javax.inject.*; -import play.*; -import play.mvc.*; - -import services.Counter; - -/** - * This controller demonstrates how to use dependency injection to - * bind a component into a controller class. The class contains an - * action that shows an incrementing count to users. The {@link Counter} - * object is injected by the Guice dependency injection system. - */ -@Singleton -public class CountController extends Controller { - - private final Counter counter; - - @Inject - public CountController(Counter counter) { - this.counter = counter; - } - - /** - * An action that responds with the {@link Counter}'s current - * count. The result is plain text. This action is mapped to - * GET requests with a path of /count - * requests by an entry in the routes config file. - */ - public Result count() { - return ok(Integer.toString(counter.nextCount())); - } - -} diff --git a/play-framework/introduction/app/controllers/HomeController.java b/play-framework/introduction/app/controllers/HomeController.java index 6a79856eb4..9b1146886e 100644 --- a/play-framework/introduction/app/controllers/HomeController.java +++ b/play-framework/introduction/app/controllers/HomeController.java @@ -1,14 +1,25 @@ package controllers; +import play.libs.concurrent.HttpExecutionContext; import play.mvc.*; +import play.twirl.api.Html; -import views.html.*; +import javax.inject.Inject; +import java.util.concurrent.CompletionStage; + +import static java.util.concurrent.CompletableFuture.supplyAsync; /** * This controller contains an action to handle HTTP requests * to the application's home page. */ public class HomeController extends Controller { + private HttpExecutionContext ec; + + @Inject + public HomeController(HttpExecutionContext ec) { + this.ec = ec; + } /** * An action that renders an HTML page with a welcome message. @@ -17,7 +28,41 @@ public class HomeController extends Controller { * GET request with a path of /. */ public Result index() { - return ok(index.render("Your new application is ready.")); + return ok(views.html.index.render()); } + public Result applyHtml() { + return ok(Html.apply("

    This text will appear as a heading 1

    ")); + } + + public Result badRequestPage() { + return badRequest("Your request data has issues."); + } + + public Result notFoundPage() { + return notFound("Could not find the page you requested."); + } + + public Result customContentType() { + return ok("This is some text content").as("text/html"); + } + + public CompletionStage asyncOperation() { + return supplyAsync(() -> { + return longRunningTask(); + }, ec.current()) + .thenApplyAsync(s -> { + return ok("Got result -> " + s); + }, ec.current()); + } + + private String longRunningTask() { + return "Long running task has completed"; + } + + public Result setHeaders() { + return ok("This is some text content") + .as("text/html") + .withHeader("Header-Key", "Some value"); + } } diff --git a/play-framework/introduction/app/controllers/StudentController.java b/play-framework/introduction/app/controllers/StudentController.java deleted file mode 100644 index 8b759b9598..0000000000 --- a/play-framework/introduction/app/controllers/StudentController.java +++ /dev/null @@ -1,63 +0,0 @@ -package controllers; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import models.Student; -import models.StudentStore; -import play.libs.Json; -import play.mvc.Controller; -import play.mvc.Result; -import util.Util; - -import java.util.Set; - -public class StudentController extends Controller { - public Result create() { - JsonNode json = request().body().asJson(); - if (json == null) { - return badRequest(Util.createResponse("Expecting Json data", false)); - } - Student student = StudentStore.getInstance().addStudent(Json.fromJson(json, Student.class)); - JsonNode jsonObject = Json.toJson(student); - return created(Util.createResponse(jsonObject, true)); - } - - public Result update() { - JsonNode json = request().body().asJson(); - if (json == null) { - return badRequest(Util.createResponse("Expecting Json data", false)); - } - Student student = StudentStore.getInstance().updateStudent(Json.fromJson(json, Student.class)); - if (student == null) { - return notFound(Util.createResponse("Student not found", false)); - } - - JsonNode jsonObject = Json.toJson(student); - return ok(Util.createResponse(jsonObject, true)); - } - - public Result retrieve(int id) { - if (StudentStore.getInstance().getStudent(id) == null) { - return notFound(Util.createResponse("Student with id:" + id + " not found", false)); - } - JsonNode jsonObjects = Json.toJson(StudentStore.getInstance().getStudent(id)); - return ok(Util.createResponse(jsonObjects, true)); - } - - public Result listStudents() { - Set result = StudentStore.getInstance().getAllStudents(); - ObjectMapper mapper = new ObjectMapper(); - - JsonNode jsonData = mapper.convertValue(result, JsonNode.class); - return ok(Util.createResponse(jsonData, true)); - - } - - public Result delete(int id) { - if (!StudentStore.getInstance().deleteStudent(id)) { - return notFound(Util.createResponse("Student with id:" + id + " not found", false)); - } - return ok(Util.createResponse("Student with id:" + id + " deleted", true)); - } - -} diff --git a/play-framework/introduction/app/filters/ExampleFilter.java b/play-framework/introduction/app/filters/ExampleFilter.java deleted file mode 100644 index 67a6a36cc3..0000000000 --- a/play-framework/introduction/app/filters/ExampleFilter.java +++ /dev/null @@ -1,45 +0,0 @@ -package filters; - -import akka.stream.Materializer; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.Executor; -import java.util.function.Function; -import javax.inject.*; -import play.mvc.*; -import play.mvc.Http.RequestHeader; - - -/** - * This is a simple filter that adds a header to all requests. It's - * added to the application's list of filters by the - * {@link Filters} class. - */ -@Singleton -public class ExampleFilter extends Filter { - - private final Executor exec; - - /** - * @param mat This object is needed to handle streaming of requests - * and responses. - * @param exec This class is needed to execute code asynchronously. - * It is used below by the thenAsyncApply method. - */ - @Inject - public ExampleFilter(Materializer mat, Executor exec) { - super(mat); - this.exec = exec; - } - - @Override - public CompletionStage apply( - Function> next, - RequestHeader requestHeader) { - - return next.apply(requestHeader).thenApplyAsync( - result -> result.withHeader("X-ExampleFilter", "foo"), - exec - ); - } - -} diff --git a/play-framework/introduction/app/models/StudentStore.java b/play-framework/introduction/app/models/StudentStore.java deleted file mode 100644 index add6a5dbd6..0000000000 --- a/play-framework/introduction/app/models/StudentStore.java +++ /dev/null @@ -1,46 +0,0 @@ -package models; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -public class StudentStore { - private static StudentStore instance; - private Map students = new HashMap<>(); - - public static StudentStore getInstance() { - if (instance == null) { - instance = new StudentStore(); - } - return instance; - } - - public Student addStudent(Student student) { - int id = students.size(); - student.setId(id); - students.put(id, student); - return student; - } - - public Student getStudent(int id) { - return students.get(id); - } - - public Set getAllStudents() { - return new HashSet<>(students.values()); - } - - public Student updateStudent(Student student) { - int id = student.getId(); - if (students.containsKey(id)) { - students.put(id, student); - return student; - } - return null; - } - - public boolean deleteStudent(int id) { - return students.remove(id) != null; - } -} \ No newline at end of file diff --git a/play-framework/introduction/app/services/ApplicationTimer.java b/play-framework/introduction/app/services/ApplicationTimer.java deleted file mode 100644 index a951562b1d..0000000000 --- a/play-framework/introduction/app/services/ApplicationTimer.java +++ /dev/null @@ -1,50 +0,0 @@ -package services; - -import java.time.Clock; -import java.time.Instant; -import java.util.concurrent.CompletableFuture; -import javax.inject.*; -import play.Logger; -import play.inject.ApplicationLifecycle; - -/** - * This class demonstrates how to run code when the - * application starts and stops. It starts a timer when the - * application starts. When the application stops it prints out how - * long the application was running for. - * - * This class is registered for Guice dependency injection in the - * {@link Module} class. We want the class to start when the application - * starts, so it is registered as an "eager singleton". See the code - * in the {@link Module} class to see how this happens. - * - * This class needs to run code when the server stops. It uses the - * application's {@link ApplicationLifecycle} to register a stop hook. - */ -@Singleton -public class ApplicationTimer { - - private final Clock clock; - private final ApplicationLifecycle appLifecycle; - private final Instant start; - - @Inject - public ApplicationTimer(Clock clock, ApplicationLifecycle appLifecycle) { - this.clock = clock; - this.appLifecycle = appLifecycle; - // This code is called when the application starts. - start = clock.instant(); - Logger.info("ApplicationTimer demo: Starting application at " + start); - - // When the application starts, register a stop hook with the - // ApplicationLifecycle object. The code inside the stop hook will - // be run when the application stops. - appLifecycle.addStopHook(() -> { - Instant stop = clock.instant(); - Long runningTime = stop.getEpochSecond() - start.getEpochSecond(); - Logger.info("ApplicationTimer demo: Stopping application at " + clock.instant() + " after " + runningTime + "s."); - return CompletableFuture.completedFuture(null); - }); - } - -} diff --git a/play-framework/introduction/app/services/AtomicCounter.java b/play-framework/introduction/app/services/AtomicCounter.java deleted file mode 100644 index 41f741cbf7..0000000000 --- a/play-framework/introduction/app/services/AtomicCounter.java +++ /dev/null @@ -1,26 +0,0 @@ -package services; - -import java.util.concurrent.atomic.AtomicInteger; -import javax.inject.*; - -/** - * This class is a concrete implementation of the {@link Counter} trait. - * It is configured for Guice dependency injection in the {@link Module} - * class. - * - * This class has a {@link Singleton} annotation because we need to make - * sure we only use one counter per application. Without this - * annotation we would get a new instance every time a {@link Counter} is - * injected. - */ -@Singleton -public class AtomicCounter implements Counter { - - private final AtomicInteger atomicCounter = new AtomicInteger(); - - @Override - public int nextCount() { - return atomicCounter.getAndIncrement(); - } - -} diff --git a/play-framework/introduction/app/services/Counter.java b/play-framework/introduction/app/services/Counter.java deleted file mode 100644 index dadad8b09d..0000000000 --- a/play-framework/introduction/app/services/Counter.java +++ /dev/null @@ -1,13 +0,0 @@ -package services; - -/** - * This interface demonstrates how to create a component that is injected - * into a controller. The interface represents a counter that returns a - * incremented number each time it is called. - * - * The {@link Modules} class binds this interface to the - * {@link AtomicCounter} implementation. - */ -public interface Counter { - int nextCount(); -} diff --git a/play-framework/introduction/app/views/index.scala.html b/play-framework/introduction/app/views/index.scala.html index 4539f5a10b..68d37fb1d4 100644 --- a/play-framework/introduction/app/views/index.scala.html +++ b/play-framework/introduction/app/views/index.scala.html @@ -1,20 +1,5 @@ -@* - * This template takes a single argument, a String containing a - * message to display. - *@ -@(message: String) +@() -@* - * Call the `main` template with two arguments. The first - * argument is a `String` with the title of the page, the second - * argument is an `Html` object containing the body of the page. - *@ @main("Welcome to Play") { - - @* - * Get an `Html` object by calling the built-in Play welcome - * template and passing a `String` message. - *@ - @play20.welcome(message, style = "Java") - +

    Welcome to Play!

    } diff --git a/play-framework/introduction/app/views/main.scala.html b/play-framework/introduction/app/views/main.scala.html index 9414f4be6e..c5f755f236 100644 --- a/play-framework/introduction/app/views/main.scala.html +++ b/play-framework/introduction/app/views/main.scala.html @@ -13,11 +13,12 @@ @title - @* And here's where we render the `Html` object containing * the page content. *@ @content + + diff --git a/play-framework/introduction/bin/activator b/play-framework/introduction/bin/activator deleted file mode 100644 index a8b11d482f..0000000000 --- a/play-framework/introduction/bin/activator +++ /dev/null @@ -1,397 +0,0 @@ -#!/usr/bin/env bash - -### ------------------------------- ### -### Helper methods for BASH scripts ### -### ------------------------------- ### - -realpath () { -( - TARGET_FILE="$1" - FIX_CYGPATH="$2" - - cd "$(dirname "$TARGET_FILE")" - TARGET_FILE=$(basename "$TARGET_FILE") - - COUNT=0 - while [ -L "$TARGET_FILE" -a $COUNT -lt 100 ] - do - TARGET_FILE=$(readlink "$TARGET_FILE") - cd "$(dirname "$TARGET_FILE")" - TARGET_FILE=$(basename "$TARGET_FILE") - COUNT=$(($COUNT + 1)) - done - - # make sure we grab the actual windows path, instead of cygwin's path. - if [[ "x$FIX_CYGPATH" != "x" ]]; then - echo "$(cygwinpath "$(pwd -P)/$TARGET_FILE")" - else - echo "$(pwd -P)/$TARGET_FILE" - fi -) -} - - -# Uses uname to detect if we're in the odd cygwin environment. -is_cygwin() { - local os=$(uname -s) - case "$os" in - CYGWIN*) return 0 ;; - *) return 1 ;; - esac -} - -# TODO - Use nicer bash-isms here. -CYGWIN_FLAG=$(if is_cygwin; then echo true; else echo false; fi) - - -# This can fix cygwin style /cygdrive paths so we get the -# windows style paths. -cygwinpath() { - local file="$1" - if [[ "$CYGWIN_FLAG" == "true" ]]; then - echo $(cygpath -w $file) - else - echo $file - fi -} - -# Make something URI friendly -make_url() { - url="$1" - local nospaces=${url// /%20} - if is_cygwin; then - echo "/${nospaces//\\//}" - else - echo "$nospaces" - fi -} - -declare -a residual_args -declare -a java_args -declare -a scalac_args -declare -a sbt_commands -declare java_cmd=java -declare java_version -declare -r real_script_path="$(realpath "$0")" -declare -r sbt_home="$(realpath "$(dirname "$(dirname "$real_script_path")")")" -declare -r sbt_bin_dir="$(dirname "$real_script_path")" -declare -r app_version="1.3.10" - -declare -r script_name=activator -declare -r java_opts=( "${ACTIVATOR_OPTS[@]}" "${SBT_OPTS[@]}" "${JAVA_OPTS[@]}" "${java_opts[@]}" ) -userhome="$HOME" -if is_cygwin; then - # cygwin sets home to something f-d up, set to real windows homedir - userhome="$USERPROFILE" -fi -declare -r activator_user_home_dir="${userhome}/.activator" -declare -r java_opts_config_home="${activator_user_home_dir}/activatorconfig.txt" -declare -r java_opts_config_version="${activator_user_home_dir}/${app_version}/activatorconfig.txt" - -echoerr () { - echo 1>&2 "$@" -} -vlog () { - [[ $verbose || $debug ]] && echoerr "$@" -} -dlog () { - [[ $debug ]] && echoerr "$@" -} - -jar_file () { - echo "$(cygwinpath "${sbt_home}/libexec/activator-launch-${app_version}.jar")" -} - -acquire_sbt_jar () { - sbt_jar="$(jar_file)" - - if [[ ! -f "$sbt_jar" ]]; then - echoerr "Could not find launcher jar: $sbt_jar" - exit 2 - fi -} - -execRunner () { - # print the arguments one to a line, quoting any containing spaces - [[ $verbose || $debug ]] && echo "# Executing command line:" && { - for arg; do - if printf "%s\n" "$arg" | grep -q ' '; then - printf "\"%s\"\n" "$arg" - else - printf "%s\n" "$arg" - fi - done - echo "" - } - - # THis used to be exec, but we loose the ability to re-hook stty then - # for cygwin... Maybe we should flag the feature here... - "$@" -} - -addJava () { - dlog "[addJava] arg = '$1'" - java_args=( "${java_args[@]}" "$1" ) -} -addSbt () { - dlog "[addSbt] arg = '$1'" - sbt_commands=( "${sbt_commands[@]}" "$1" ) -} -addResidual () { - dlog "[residual] arg = '$1'" - residual_args=( "${residual_args[@]}" "$1" ) -} -addDebugger () { - addJava "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=$1" -} - -get_mem_opts () { - # if we detect any of these settings in ${JAVA_OPTS} we need to NOT output our settings. - # The reason is the Xms/Xmx, if they don't line up, cause errors. - if [[ "${JAVA_OPTS}" == *-Xmx* ]] || [[ "${JAVA_OPTS}" == *-Xms* ]] || [[ "${JAVA_OPTS}" == *-XX:MaxPermSize* ]] || [[ "${JAVA_OPTS}" == *-XX:MaxMetaspaceSize* ]] || [[ "${JAVA_OPTS}" == *-XX:ReservedCodeCacheSize* ]]; then - echo "" - else - # a ham-fisted attempt to move some memory settings in concert - # so they need not be messed around with individually. - local mem=${1:-1024} - local codecache=$(( $mem / 8 )) - (( $codecache > 128 )) || codecache=128 - (( $codecache < 512 )) || codecache=512 - local class_metadata_size=$(( $codecache * 2 )) - local class_metadata_opt=$([[ "$java_version" < "1.8" ]] && echo "MaxPermSize" || echo "MaxMetaspaceSize") - - echo "-Xms${mem}m -Xmx${mem}m -XX:ReservedCodeCacheSize=${codecache}m -XX:${class_metadata_opt}=${class_metadata_size}m" - fi -} - -require_arg () { - local type="$1" - local opt="$2" - local arg="$3" - if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then - echo "$opt requires <$type> argument" - exit 1 - fi -} - -is_function_defined() { - declare -f "$1" > /dev/null -} - -# If we're *not* running in a terminal, and we don't have any arguments, then we need to add the 'ui' parameter -detect_terminal_for_ui() { - [[ ! -t 0 ]] && [[ "${#residual_args}" == "0" ]] && { - addResidual "ui" - } - # SPECIAL TEST FOR MAC - [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]] && [[ "${#residual_args}" == "0" ]] && { - echo "Detected MAC OSX launched script...." - echo "Swapping to UI" - addResidual "ui" - } -} - -process_args () { - while [[ $# -gt 0 ]]; do - case "$1" in - -h|-help) usage; exit 1 ;; - -v|-verbose) verbose=1 && shift ;; - -d|-debug) debug=1 && shift ;; - - -ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;; - -mem) require_arg integer "$1" "$2" && sbt_mem="$2" && shift 2 ;; - -jvm-debug) require_arg port "$1" "$2" && addDebugger $2 && shift 2 ;; - -batch) exec &1 | awk -F '"' '/version/ {print $2}') - vlog "[process_args] java_version = '$java_version'" -} - -# Detect that we have java installed. -checkJava() { - local required_version="$1" - # Now check to see if it's a good enough version - if [[ "$java_version" == "" ]]; then - echo - echo No java installations was detected. - echo Please go to http://www.java.com/getjava/ and download - echo - exit 1 - elif [[ ! "$java_version" > "$required_version" ]]; then - echo - echo The java installation you have is not up to date - echo $script_name requires at least version $required_version+, you have - echo version $java_version - echo - echo Please go to http://www.java.com/getjava/ and download - echo a valid Java Runtime and install before running $script_name. - echo - exit 1 - fi -} - - -run() { - # no jar? download it. - [[ -f "$sbt_jar" ]] || acquire_sbt_jar "$sbt_version" || { - # still no jar? uh-oh. - echo "Download failed. Obtain the sbt-launch.jar manually and place it at $sbt_jar" - exit 1 - } - - # process the combined args, then reset "$@" to the residuals - process_args "$@" - detect_terminal_for_ui - set -- "${residual_args[@]}" - argumentCount=$# - - # TODO - java check should be configurable... - checkJava "1.6" - - #If we're in cygwin, we should use the windows config, and terminal hacks - if [[ "$CYGWIN_FLAG" == "true" ]]; then - stty -icanon min 1 -echo > /dev/null 2>&1 - addJava "-Djline.terminal=jline.UnixTerminal" - addJava "-Dsbt.cygwin=true" - fi - - # run sbt - execRunner "$java_cmd" \ - "-Dactivator.home=$(make_url "$sbt_home")" \ - ${SBT_OPTS:-$default_sbt_opts} \ - $(get_mem_opts $sbt_mem) \ - ${JAVA_OPTS} \ - ${java_args[@]} \ - -jar "$sbt_jar" \ - "${sbt_commands[@]}" \ - "${residual_args[@]}" - - exit_code=$? - - # Clean up the terminal from cygwin hacks. - if [[ "$CYGWIN_FLAG" == "true" ]]; then - stty icanon echo > /dev/null 2>&1 - fi - exit $exit_code -} - - -declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy" -declare -r sbt_opts_file=".sbtopts" -declare -r etc_sbt_opts_file="${sbt_home}/conf/sbtopts" -declare -r win_sbt_opts_file="${sbt_home}/conf/sbtconfig.txt" - -usage() { - cat < path to global settings/plugins directory (default: ~/.sbt) - -sbt-boot path to shared boot directory (default: ~/.sbt/boot in 0.11 series) - -ivy path to local Ivy repository (default: ~/.ivy2) - -mem set memory options (default: $sbt_mem, which is $(get_mem_opts $sbt_mem)) - -no-share use all local caches; no sharing - -no-global uses global caches, but does not use global ~/.sbt directory. - -jvm-debug Turn on JVM debugging, open at the given port. - -batch Disable interactive mode - - # sbt version (default: from project/build.properties if present, else latest release) - -sbt-version use the specified version of sbt - -sbt-jar use the specified jar as the sbt launcher - -sbt-rc use an RC version of sbt - -sbt-snapshot use a snapshot version of sbt - - # java version (default: java from PATH, currently $(java -version 2>&1 | grep version)) - -java-home alternate JAVA_HOME - - # jvm options and output control - JAVA_OPTS environment variable, if unset uses "$java_opts" - SBT_OPTS environment variable, if unset uses "$default_sbt_opts" - ACTIVATOR_OPTS Environment variable, if unset uses "" - .sbtopts if this file exists in the current directory, it is - prepended to the runner args - /etc/sbt/sbtopts if this file exists, it is prepended to the runner args - -Dkey=val pass -Dkey=val directly to the java runtime - -J-X pass option -X directly to the java runtime - (-J is stripped) - -S-X add -X to sbt's scalacOptions (-S is stripped) - -In the case of duplicated or conflicting options, the order above -shows precedence: JAVA_OPTS lowest, command line options highest. -EOM -} - - - -process_my_args () { - while [[ $# -gt 0 ]]; do - case "$1" in - -no-colors) addJava "-Dsbt.log.noformat=true" && shift ;; - -no-share) addJava "$noshare_opts" && shift ;; - -no-global) addJava "-Dsbt.global.base=$(pwd)/project/.sbtboot" && shift ;; - -sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;; - -sbt-dir) require_arg path "$1" "$2" && addJava "-Dsbt.global.base=$2" && shift 2 ;; - -debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;; - -batch) exec ^&1') do ( - if %%~j==java set JAVAINSTALLED=1 - if %%~j==openjdk set JAVAINSTALLED=1 -) - -rem Detect the same thing about javac -if "%_JAVACCMD%"=="" ( - if not "%JAVA_HOME%"=="" ( - if exist "%JAVA_HOME%\bin\javac.exe" set "_JAVACCMD=%JAVA_HOME%\bin\javac.exe" - ) -) -if "%_JAVACCMD%"=="" set _JAVACCMD=javac -for /F %%j in ('"%_JAVACCMD%" -version 2^>^&1') do ( - if %%~j==javac set JAVACINSTALLED=1 -) - -rem BAT has no logical or, so we do it OLD SCHOOL! Oppan Redmond Style -set JAVAOK=true -if not defined JAVAINSTALLED set JAVAOK=false -if not defined JAVACINSTALLED set JAVAOK=false - -if "%JAVAOK%"=="false" ( - echo. - echo A Java JDK is not installed or can't be found. - if not "%JAVA_HOME%"=="" ( - echo JAVA_HOME = "%JAVA_HOME%" - ) - echo. - echo Please go to - echo http://www.oracle.com/technetwork/java/javase/downloads/index.html - echo and download a valid Java JDK and install before running Activator. - echo. - echo If you think this message is in error, please check - echo your environment variables to see if "java.exe" and "javac.exe" are - echo available via JAVA_HOME or PATH. - echo. - if defined DOUBLECLICKED pause - exit /B 1 -) - -rem Check what Java version is being used to determine what memory options to use -for /f "tokens=3" %%g in ('java -version 2^>^&1 ^| findstr /i "version"') do ( - set JAVA_VERSION=%%g -) - -rem Strips away the " characters -set JAVA_VERSION=%JAVA_VERSION:"=% - -rem TODO Check if there are existing mem settings in JAVA_OPTS/CFG_OPTS and use those instead of the below -for /f "delims=. tokens=1-3" %%v in ("%JAVA_VERSION%") do ( - set MAJOR=%%v - set MINOR=%%w - set BUILD=%%x - - set META_SIZE=-XX:MetaspaceSize=64M -XX:MaxMetaspaceSize=256M - if "!MINOR!" LSS "8" ( - set META_SIZE=-XX:PermSize=64M -XX:MaxPermSize=256M - ) - - set MEM_OPTS=!META_SIZE! - ) - -rem We use the value of the JAVA_OPTS environment variable if defined, rather than the config. -set _JAVA_OPTS=%JAVA_OPTS% -if "%_JAVA_OPTS%"=="" set _JAVA_OPTS=%CFG_OPTS% - -set DEBUG_OPTS= - -rem Loop through the arguments, building remaining args in args variable -set args= -:argsloop -if not "%~1"=="" ( - rem Checks if the argument contains "-D" and if true, adds argument 1 with 2 and puts an equal sign between them. - rem This is done since batch considers "=" to be a delimiter so we need to circumvent this behavior with a small hack. - set arg1=%~1 - if "!arg1:~0,2!"=="-D" ( - set "args=%args% "%~1"="%~2"" - shift - shift - goto argsloop - ) - - if "%~1"=="-jvm-debug" ( - if not "%~2"=="" ( - rem This piece of magic somehow checks that an argument is a number - for /F "delims=0123456789" %%i in ("%~2") do ( - set var="%%i" - ) - if defined var ( - rem Not a number, assume no argument given and default to 9999 - set JPDA_PORT=9999 - ) else ( - rem Port was given, shift arguments - set JPDA_PORT=%~2 - shift - ) - ) else ( - set JPDA_PORT=9999 - ) - shift - - set DEBUG_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=!JPDA_PORT! - goto argsloop - ) - rem else - set "args=%args% "%~1"" - shift - goto argsloop -) - -:run - -if "!args!"=="" ( - if defined DOUBLECLICKED ( - set CMDS="ui" - ) else set CMDS=!args! -) else set CMDS=!args! - -rem We add a / in front, so we get file:///C: instead of file://C: -rem Java considers the later a UNC path. -rem We also attempt a solid effort at making it URI friendly. -rem We don't even bother with UNC paths. -set JAVA_FRIENDLY_HOME_1=/!ACTIVATOR_HOME:\=/! -set JAVA_FRIENDLY_HOME=/!JAVA_FRIENDLY_HOME_1: =%%20! - -rem Checks if the command contains spaces to know if it should be wrapped in quotes or not -set NON_SPACED_CMD=%_JAVACMD: =% -if "%_JAVACMD%"=="%NON_SPACED_CMD%" %_JAVACMD% %DEBUG_OPTS% %MEM_OPTS% %ACTIVATOR_OPTS% %SBT_OPTS% %_JAVA_OPTS% "-Dactivator.home=%JAVA_FRIENDLY_HOME%" -jar "%ACTIVATOR_HOME%\libexec\%ACTIVATOR_LAUNCH_JAR%" %CMDS% -if NOT "%_JAVACMD%"=="%NON_SPACED_CMD%" "%_JAVACMD%" %DEBUG_OPTS% %MEM_OPTS% %ACTIVATOR_OPTS% %SBT_OPTS% %_JAVA_OPTS% "-Dactivator.home=%JAVA_FRIENDLY_HOME%" -jar "%ACTIVATOR_HOME%\libexec\%ACTIVATOR_LAUNCH_JAR%" %CMDS% - -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end - -@endlocal - -exit /B %ERROR_CODE% diff --git a/play-framework/introduction/build.sbt b/play-framework/introduction/build.sbt index 0f5ea736f6..5b05db6719 100644 --- a/play-framework/introduction/build.sbt +++ b/play-framework/introduction/build.sbt @@ -1,13 +1,10 @@ -name := """student-api""" +name := """introduction""" +organization := "com.baeldung" version := "1.0-SNAPSHOT" lazy val root = (project in file(".")).enablePlugins(PlayJava) -scalaVersion := "2.11.7" +scalaVersion := "2.13.0" -libraryDependencies ++= Seq( - javaJdbc, - cache, - javaWs -) +libraryDependencies += guice diff --git a/play-framework/introduction/conf/application.conf b/play-framework/introduction/conf/application.conf index 489d3f9b3e..85c184dcb1 100644 --- a/play-framework/introduction/conf/application.conf +++ b/play-framework/introduction/conf/application.conf @@ -1,353 +1,2 @@ # This is the main configuration file for the application. # https://www.playframework.com/documentation/latest/ConfigFile -# ~~~~~ -# Play uses HOCON as its configuration file format. HOCON has a number -# of advantages over other config formats, but there are two things that -# can be used when modifying settings. -# -# You can include other configuration files in this main application.conf file: -#include "extra-config.conf" -# -# You can declare variables and substitute for them: -#mykey = ${some.value} -# -# And if an environment variable exists when there is no other subsitution, then -# HOCON will fall back to substituting environment variable: -#mykey = ${JAVA_HOME} - -## Akka -# https://www.playframework.com/documentation/latest/ScalaAkka#Configuration -# https://www.playframework.com/documentation/latest/JavaAkka#Configuration -# ~~~~~ -# Play uses Akka internally and exposes Akka Streams and actors in Websockets and -# other streaming HTTP responses. -akka { - # "akka.log-config-on-start" is extraordinarly useful because it log the complete - # configuration at INFO level, including defaults and overrides, so it s worth - # putting at the very top. - # - # Put the following in your conf/logback.xml file: - # - # - # - # And then uncomment this line to debug the configuration. - # - #log-config-on-start = true -} - -## Secret key -# http://www.playframework.com/documentation/latest/ApplicationSecret -# ~~~~~ -# The secret key is used to sign Play's session cookie. -# This must be changed for production, but we don't recommend you change it in this file. -play.crypto.secret = "changeme" - -## Modules -# https://www.playframework.com/documentation/latest/Modules -# ~~~~~ -# Control which modules are loaded when Play starts. Note that modules are -# the replacement for "GlobalSettings", which are deprecated in 2.5.x. -# Please see https://www.playframework.com/documentation/latest/GlobalSettings -# for more information. -# -# You can also extend Play functionality by using one of the publically available -# Play modules: https://playframework.com/documentation/latest/ModuleDirectory -play.modules { - # By default, Play will load any class called Module that is defined - # in the root package (the "app" directory), or you can define them - # explicitly below. - # If there are any built-in modules that you want to disable, you can list them here. - #enabled += my.application.Module - - # If there are any built-in modules that you want to disable, you can list them here. - #disabled += "" -} - -## IDE -# https://www.playframework.com/documentation/latest/IDE -# ~~~~~ -# Depending on your IDE, you can add a hyperlink for errors that will jump you -# directly to the code location in the IDE in dev mode. The following line makes -# use of the IntelliJ IDEA REST interface: -#play.editor="http://localhost:63342/api/file/?file=%s&line=%s" - -## Internationalisation -# https://www.playframework.com/documentation/latest/JavaI18N -# https://www.playframework.com/documentation/latest/ScalaI18N -# ~~~~~ -# Play comes with its own i18n settings, which allow the user's preferred language -# to map through to internal messages, or allow the language to be stored in a cookie. -play.i18n { - # The application languages - langs = [ "en" ] - - # Whether the language cookie should be secure or not - #langCookieSecure = true - - # Whether the HTTP only attribute of the cookie should be set to true - #langCookieHttpOnly = true -} - -## Play HTTP settings -# ~~~~~ -play.http { - ## Router - # https://www.playframework.com/documentation/latest/JavaRouting - # https://www.playframework.com/documentation/latest/ScalaRouting - # ~~~~~ - # Define the Router object to use for this application. - # This router will be looked up first when the application is starting up, - # so make sure this is the entry point. - # Furthermore, it's assumed your route file is named properly. - # So for an application router like `my.application.Router`, - # you may need to define a router file `conf/my.application.routes`. - # Default to Routes in the root package (aka "apps" folder) (and conf/routes) - #router = my.application.Router - - ## Action Creator - # https://www.playframework.com/documentation/latest/JavaActionCreator - # ~~~~~ - #actionCreator = null - - ## ErrorHandler - # https://www.playframework.com/documentation/latest/JavaRouting - # https://www.playframework.com/documentation/latest/ScalaRouting - # ~~~~~ - # If null, will attempt to load a class called ErrorHandler in the root package, - #errorHandler = null - - ## Filters - # https://www.playframework.com/documentation/latest/ScalaHttpFilters - # https://www.playframework.com/documentation/latest/JavaHttpFilters - # ~~~~~ - # Filters run code on every request. They can be used to perform - # common logic for all your actions, e.g. adding common headers. - # Defaults to "Filters" in the root package (aka "apps" folder) - # Alternatively you can explicitly register a class here. - #filters = my.application.Filters - - ## Session & Flash - # https://www.playframework.com/documentation/latest/JavaSessionFlash - # https://www.playframework.com/documentation/latest/ScalaSessionFlash - # ~~~~~ - session { - # Sets the cookie to be sent only over HTTPS. - #secure = true - - # Sets the cookie to be accessed only by the server. - #httpOnly = true - - # Sets the max-age field of the cookie to 5 minutes. - # NOTE: this only sets when the browser will discard the cookie. Play will consider any - # cookie value with a valid signature to be a valid session forever. To implement a server side session timeout, - # you need to put a timestamp in the session and check it at regular intervals to possibly expire it. - #maxAge = 300 - - # Sets the domain on the session cookie. - #domain = "example.com" - } - - flash { - # Sets the cookie to be sent only over HTTPS. - #secure = true - - # Sets the cookie to be accessed only by the server. - #httpOnly = true - } -} - -## Netty Provider -# https://www.playframework.com/documentation/latest/SettingsNetty -# ~~~~~ -play.server.netty { - # Whether the Netty wire should be logged - #log.wire = true - - # If you run Play on Linux, you can use Netty's native socket transport - # for higher performance with less garbage. - #transport = "native" -} - -## WS (HTTP Client) -# https://www.playframework.com/documentation/latest/ScalaWS#Configuring-WS -# ~~~~~ -# The HTTP client primarily used for REST APIs. The default client can be -# configured directly, but you can also create different client instances -# with customized settings. You must enable this by adding to build.sbt: -# -# libraryDependencies += ws // or javaWs if using java -# -play.ws { - # Sets HTTP requests not to follow 302 requests - #followRedirects = false - - # Sets the maximum number of open HTTP connections for the client. - #ahc.maxConnectionsTotal = 50 - - ## WS SSL - # https://www.playframework.com/documentation/latest/WsSSL - # ~~~~~ - ssl { - # Configuring HTTPS with Play WS does not require programming. You can - # set up both trustManager and keyManager for mutual authentication, and - # turn on JSSE debugging in development with a reload. - #debug.handshake = true - #trustManager = { - # stores = [ - # { type = "JKS", path = "exampletrust.jks" } - # ] - #} - } -} - -## Cache -# https://www.playframework.com/documentation/latest/JavaCache -# https://www.playframework.com/documentation/latest/ScalaCache -# ~~~~~ -# Play comes with an integrated cache API that can reduce the operational -# overhead of repeated requests. You must enable this by adding to build.sbt: -# -# libraryDependencies += cache -# -play.cache { - # If you want to bind several caches, you can bind the individually - #bindCaches = ["db-cache", "user-cache", "session-cache"] -} - -## Filters -# https://www.playframework.com/documentation/latest/Filters -# ~~~~~ -# There are a number of built-in filters that can be enabled and configured -# to give Play greater security. You must enable this by adding to build.sbt: -# -# libraryDependencies += filters -# -play.filters { - ## CORS filter configuration - # https://www.playframework.com/documentation/latest/CorsFilter - # ~~~~~ - # CORS is a protocol that allows web applications to make requests from the browser - # across different domains. - # NOTE: You MUST apply the CORS configuration before the CSRF filter, as CSRF has - # dependencies on CORS settings. - cors { - # Filter paths by a whitelist of path prefixes - #pathPrefixes = ["/some/path", ...] - - # The allowed origins. If null, all origins are allowed. - #allowedOrigins = ["http://www.example.com"] - - # The allowed HTTP methods. If null, all methods are allowed - #allowedHttpMethods = ["GET", "POST"] - } - - ## CSRF Filter - # https://www.playframework.com/documentation/latest/ScalaCsrf#Applying-a-global-CSRF-filter - # https://www.playframework.com/documentation/latest/JavaCsrf#Applying-a-global-CSRF-filter - # ~~~~~ - # Play supports multiple methods for verifying that a request is not a CSRF request. - # The primary mechanism is a CSRF token. This token gets placed either in the query string - # or body of every form submitted, and also gets placed in the users session. - # Play then verifies that both tokens are present and match. - csrf { - # Sets the cookie to be sent only over HTTPS - #cookie.secure = true - - # Defaults to CSRFErrorHandler in the root package. - #errorHandler = MyCSRFErrorHandler - } - - ## Security headers filter configuration - # https://www.playframework.com/documentation/latest/SecurityHeaders - # ~~~~~ - # Defines security headers that prevent XSS attacks. - # If enabled, then all options are set to the below configuration by default: - headers { - # The X-Frame-Options header. If null, the header is not set. - #frameOptions = "DENY" - - # The X-XSS-Protection header. If null, the header is not set. - #xssProtection = "1; mode=block" - - # The X-Content-Type-Options header. If null, the header is not set. - #contentTypeOptions = "nosniff" - - # The X-Permitted-Cross-Domain-Policies header. If null, the header is not set. - #permittedCrossDomainPolicies = "master-only" - - # The Content-Security-Policy header. If null, the header is not set. - #contentSecurityPolicy = "default-src 'self'" - } - - ## Allowed hosts filter configuration - # https://www.playframework.com/documentation/latest/AllowedHostsFilter - # ~~~~~ - # Play provides a filter that lets you configure which hosts can access your application. - # This is useful to prevent cache poisoning attacks. - hosts { - # Allow requests to example.com, its subdomains, and localhost:9000. - #allowed = [".example.com", "localhost:9000"] - } -} - -## Evolutions -# https://www.playframework.com/documentation/latest/Evolutions -# ~~~~~ -# Evolutions allows database scripts to be automatically run on startup in dev mode -# for database migrations. You must enable this by adding to build.sbt: -# -# libraryDependencies += evolutions -# -play.evolutions { - # You can disable evolutions for a specific datasource if necessary - #db.default.enabled = false -} - -## Database Connection Pool -# https://www.playframework.com/documentation/latest/SettingsJDBC -# ~~~~~ -# Play doesn't require a JDBC database to run, but you can easily enable one. -# -# libraryDependencies += jdbc -# -play.db { - # The combination of these two settings results in "db.default" as the - # default JDBC pool: - #config = "db" - #default = "default" - - # Play uses HikariCP as the default connection pool. You can override - # settings by changing the prototype: - prototype { - # Sets a fixed JDBC connection pool size of 50 - #hikaricp.minimumIdle = 50 - #hikaricp.maximumPoolSize = 50 - } -} - -## JDBC Datasource -# https://www.playframework.com/documentation/latest/JavaDatabase -# https://www.playframework.com/documentation/latest/ScalaDatabase -# ~~~~~ -# Once JDBC datasource is set up, you can work with several different -# database options: -# -# Slick (Scala preferred option): https://www.playframework.com/documentation/latest/PlaySlick -# JPA (Java preferred option): https://playframework.com/documentation/latest/JavaJPA -# EBean: https://playframework.com/documentation/latest/JavaEbean -# Anorm: https://www.playframework.com/documentation/latest/ScalaAnorm -# -db { - # You can declare as many datasources as you want. - # By convention, the default datasource is named `default` - - # https://www.playframework.com/documentation/latest/Developing-with-the-H2-Database - #default.driver = org.h2.Driver - #default.url = "jdbc:h2:mem:play" - #default.username = sa - #default.password = "" - - # You can turn on SQL logging for any datasource - # https://www.playframework.com/documentation/latest/Highlights25#Logging-SQL-statements - #default.logSql=true -} diff --git a/play-framework/introduction/conf/logback.xml b/play-framework/introduction/conf/logback.xml index 86ec12c0af..e8c982543f 100644 --- a/play-framework/introduction/conf/logback.xml +++ b/play-framework/introduction/conf/logback.xml @@ -27,12 +27,6 @@ - - - - - - diff --git a/play-framework/introduction/conf/routes b/play-framework/introduction/conf/routes index ab55792683..e26dc10383 100644 --- a/play-framework/introduction/conf/routes +++ b/play-framework/introduction/conf/routes @@ -2,11 +2,14 @@ # This file defines all application routes (Higher priority routes first) # ~~~~ -GET / controllers.StudentController.listStudents() -POST /:id controllers.StudentController.retrieve(id:Int) -POST / controllers.StudentController.create() -PUT / controllers.StudentController.update() -DELETE /:id controllers.StudentController.delete(id:Int) +# An example controller showing a sample home page +GET / controllers.HomeController.index +GET /baeldung/html controllers.HomeController.applyHtml +GET /baeldung/bad-req controllers.HomeController.badRequestPage +GET /baeldung/not-found controllers.HomeController.notFoundPage +GET /baeldung/custom-content-type controllers.HomeController.customContentType +GET /baeldung/async controllers.HomeController.asyncOperation +GET /baeldung/headers controllers.HomeController.setHeaders # Map static resources from the /public folder to the /assets URL path -GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset) +GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset) diff --git a/play-framework/introduction/libexec/activator-launch-1.3.10.jar b/play-framework/introduction/libexec/activator-launch-1.3.10.jar deleted file mode 100644 index 69050e7dec..0000000000 Binary files a/play-framework/introduction/libexec/activator-launch-1.3.10.jar and /dev/null differ diff --git a/play-framework/introduction/project/build.properties b/play-framework/introduction/project/build.properties index 6d9fa6badb..c0bab04941 100644 --- a/play-framework/introduction/project/build.properties +++ b/play-framework/introduction/project/build.properties @@ -1,4 +1 @@ -#Activator-generated Properties -#Wed Sep 07 12:29:40 EAT 2016 -template.uuid=c373963b-f5ad-433b-8e74-178e7ae25b1c -sbt.version=0.13.11 +sbt.version=1.2.8 diff --git a/play-framework/introduction/project/plugins.sbt b/play-framework/introduction/project/plugins.sbt index 51c5b2a35a..1c8c62a0d5 100644 --- a/play-framework/introduction/project/plugins.sbt +++ b/play-framework/introduction/project/plugins.sbt @@ -1,21 +1,7 @@ // The Play plugin -addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.6") +addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.7.3") -// Web plugins -addSbtPlugin("com.typesafe.sbt" % "sbt-coffeescript" % "1.0.0") -addSbtPlugin("com.typesafe.sbt" % "sbt-less" % "1.1.0") -addSbtPlugin("com.typesafe.sbt" % "sbt-jshint" % "1.0.3") -addSbtPlugin("com.typesafe.sbt" % "sbt-rjs" % "1.0.7") -addSbtPlugin("com.typesafe.sbt" % "sbt-digest" % "1.1.0") -addSbtPlugin("com.typesafe.sbt" % "sbt-mocha" % "1.1.0") -addSbtPlugin("org.irundaia.sbt" % "sbt-sassify" % "1.4.2") - -// Play enhancer - this automatically generates getters/setters for public fields -// and rewrites accessors of these fields to use the getters/setters. Remove this -// plugin if you prefer not to have this feature, or disable on a per project -// basis using disablePlugins(PlayEnhancer) in your build.sbt -addSbtPlugin("com.typesafe.sbt" % "sbt-play-enhancer" % "1.1.0") - -// Play Ebean support, to enable, uncomment this line, and enable in your build.sbt using -// enablePlugins(PlayEbean). -// addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "1.0.0") +// Defines scaffolding (found under .g8 folder) +// http://www.foundweekends.org/giter8/scaffolding.html +// sbt "g8Scaffold form" +addSbtPlugin("org.foundweekends.giter8" % "sbt-giter8-scaffold" % "0.11.0") diff --git a/play-framework/introduction/public/javascripts/hello.js b/play-framework/introduction/public/javascripts/hello.js deleted file mode 100644 index 02ee13c7ca..0000000000 --- a/play-framework/introduction/public/javascripts/hello.js +++ /dev/null @@ -1,3 +0,0 @@ -if (window.console) { - console.log("Welcome to your Play application's JavaScript!"); -} diff --git a/play-framework/introduction/public/javascripts/main.js b/play-framework/introduction/public/javascripts/main.js new file mode 100644 index 0000000000..e69de29bb2 diff --git a/play-framework/introduction/test/ApplicationLiveTest.java b/play-framework/introduction/test/ApplicationLiveTest.java deleted file mode 100644 index beeef1a602..0000000000 --- a/play-framework/introduction/test/ApplicationLiveTest.java +++ /dev/null @@ -1,172 +0,0 @@ - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Arrays; - -import org.json.JSONArray; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import model.Student; -import play.test.*; -import static play.test.Helpers.*; - -public class ApplicationLiveTest{ - private static final String BASE_URL = "http://localhost:9000"; - - @Test -public void testInServer() throws Exception { - TestServer server = testServer(3333); - running(server, () -> { - try { - WSClient ws = play.libs.ws.WS.newClient(3333); - CompletionStage completionStage = ws.url("/").get(); - WSResponse response = completionStage.toCompletableFuture().get(); - ws.close(); - assertEquals(OK, response.getStatus()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - }); -} - @Test - public void whenCreatesRecord_thenCorrect() { - Student student = new Student("jody", "west", 50); - JSONObject obj = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))); - assertTrue(obj.getBoolean("isSuccessfull")); - JSONObject body = obj.getJSONObject("body"); - assertEquals(student.getAge(), body.getInt("age")); - assertEquals(student.getFirstName(), body.getString("firstName")); - assertEquals(student.getLastName(), body.getString("lastName")); - } - - @Test - public void whenDeletesCreatedRecord_thenCorrect() { - Student student = new Student("Usain", "Bolt", 25); - JSONObject ob1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body"); - int id = ob1.getInt("id"); - JSONObject obj1 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject())); - assertTrue(obj1.getBoolean("isSuccessfull")); - makeRequest(BASE_URL + "/" + id, "DELETE", null); - JSONObject obj2 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject())); - assertFalse(obj2.getBoolean("isSuccessfull")); - } - - @Test - public void whenUpdatesCreatedRecord_thenCorrect() { - Student student = new Student("john", "doe", 50); - JSONObject body1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body"); - assertEquals(student.getAge(), body1.getInt("age")); - int newAge = 60; - body1.put("age", newAge); - JSONObject body2 = new JSONObject(makeRequest(BASE_URL, "PUT", body1)).getJSONObject("body"); - assertFalse(student.getAge() == body2.getInt("age")); - assertTrue(newAge == body2.getInt("age")); - } - - @Test - public void whenGetsAllRecords_thenCorrect() { - Student student1 = new Student("jane", "daisy", 50); - Student student2 = new Student("john", "daniel", 60); - Student student3 = new Student("don", "mason", 55); - Student student4 = new Student("scarlet", "ohara", 90); - - makeRequest(BASE_URL, "POST", new JSONObject(student1)); - makeRequest(BASE_URL, "POST", new JSONObject(student2)); - makeRequest(BASE_URL, "POST", new JSONObject(student3)); - makeRequest(BASE_URL, "POST", new JSONObject(student4)); - - JSONObject objects = new JSONObject(makeRequest(BASE_URL, "GET", null)); - assertTrue(objects.getBoolean("isSuccessfull")); - JSONArray array = objects.getJSONArray("body"); - assertTrue(array.length() >= 4); - } - - public static String makeRequest(String myUrl, String httpMethod, JSONObject parameters) { - - URL url = null; - try { - url = new URL(myUrl); - } catch (MalformedURLException e) { - e.printStackTrace(); - } - HttpURLConnection conn = null; - try { - - conn = (HttpURLConnection) url.openConnection(); - } catch (IOException e) { - e.printStackTrace(); - } - conn.setDoInput(true); - - conn.setReadTimeout(10000); - - conn.setRequestProperty("Content-Type", "application/json"); - DataOutputStream dos = null; - int respCode = 0; - String inputString = null; - try { - conn.setRequestMethod(httpMethod); - - if (Arrays.asList("POST", "PUT").contains(httpMethod)) { - String params = parameters.toString(); - - conn.setDoOutput(true); - - dos = new DataOutputStream(conn.getOutputStream()); - dos.writeBytes(params); - dos.flush(); - dos.close(); - } - respCode = conn.getResponseCode(); - if (respCode != 200 && respCode != 201) { - String error = inputStreamToString(conn.getErrorStream()); - return error; - } - inputString = inputStreamToString(conn.getInputStream()); - - } catch (IOException e) { - - e.printStackTrace(); - } - return inputString; - } - - public static String inputStreamToString(InputStream is) { - BufferedReader br = null; - StringBuilder sb = new StringBuilder(); - - String line; - try { - - br = new BufferedReader(new InputStreamReader(is)); - while ((line = br.readLine()) != null) { - sb.append(line); - } - - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - return sb.toString(); - - } -} diff --git a/play-framework/introduction/test/controllers/HomeControllerUnitTest.java b/play-framework/introduction/test/controllers/HomeControllerUnitTest.java new file mode 100644 index 0000000000..42a2e871f0 --- /dev/null +++ b/play-framework/introduction/test/controllers/HomeControllerUnitTest.java @@ -0,0 +1,97 @@ +package controllers; + +import org.junit.Test; +import play.Application; +import play.inject.guice.GuiceApplicationBuilder; +import play.mvc.Http; +import play.mvc.Result; +import play.test.WithApplication; + +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static play.mvc.Http.Status.*; +import static play.test.Helpers.GET; +import static play.test.Helpers.route; + +public class HomeControllerUnitTest extends WithApplication { + + @Override + protected Application provideApplication() { + return new GuiceApplicationBuilder().build(); + } + + @Test + public void givenRequest_whenRootPath_ThenStatusOkay() { + Http.RequestBuilder request = new Http.RequestBuilder() + .method(GET) + .uri("/"); + + Result result = route(app, request); + assertEquals(OK, result.status()); + } + + @Test + public void givenRequest_whenHtmlPath_ThenStatusOkay() { + Http.RequestBuilder request = new Http.RequestBuilder() + .method(GET) + .uri("/baeldung/html"); + + Result result = route(app, request); + assertEquals(OK, result.status()); + } + + @Test + public void givenRequest_whenBadRequest_ThenStatusBadRequest() { + Http.RequestBuilder request = new Http.RequestBuilder() + .method(GET) + .uri("/baeldung/bad-req"); + + Result result = route(app, request); + assertEquals(BAD_REQUEST, result.status()); + } + + @Test + public void givenRequest_whenNotFound_ThenStatusNotFound() { + Http.RequestBuilder request = new Http.RequestBuilder() + .method(GET) + .uri("/baeldung/not-found"); + + Result result = route(app, request); + assertEquals(NOT_FOUND, result.status()); + } + + @Test + public void givenRequest_whenCustomContentTypePath_ThenContextTypeTextHtml() { + Http.RequestBuilder request = new Http.RequestBuilder() + .method(GET) + .uri("/baeldung/custom-content-type"); + + Result result = route(app, request); + assertTrue(result.contentType().isPresent()); + assertEquals("text/html", result.contentType().get()); + } + + @Test + public void givenRequest_whenAsyncPath_ThenStatusOkay() { + Http.RequestBuilder request = new Http.RequestBuilder() + .method(GET) + .uri("/baeldung/async"); + + Result result = route(app, request); + assertEquals(OK, result.status()); + } + + @Test + public void givenRequest_whenHeadersPath_ThenCustomHeaderFieldSet() { + Http.RequestBuilder request = new Http.RequestBuilder() + .method(GET) + .uri("/baeldung/headers"); + + Result result = route(app, request); + final Optional headerOptional = result.header("Header-Key"); + assertTrue(headerOptional.isPresent()); + assertEquals("Some value", headerOptional.get()); + } +} diff --git a/play-framework/routing-in-play/LICENSE b/play-framework/routing-in-play/LICENSE deleted file mode 100644 index 4baedcb95f..0000000000 --- a/play-framework/routing-in-play/LICENSE +++ /dev/null @@ -1,8 +0,0 @@ -This software is licensed under the Apache 2 license, quoted below. - -Licensed under the Apache License, Version 2.0 (the "License"); you may not use this project except in compliance with -the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. - -Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an -"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific -language governing permissions and limitations under the License. \ No newline at end of file diff --git a/play-framework/routing-in-play/README b/play-framework/routing-in-play/README deleted file mode 100644 index f21d092edf..0000000000 --- a/play-framework/routing-in-play/README +++ /dev/null @@ -1,49 +0,0 @@ -This is your new Play application -================================= - -This file will be packaged with your application when using `activator dist`. - -There are several demonstration files available in this template. - -Controllers -=========== - -- HomeController.java: - - Shows how to handle simple HTTP requests. - -- AsyncController.java: - - Shows how to do asynchronous programming when handling a request. - -- CountController.java: - - Shows how to inject a component into a controller and use the component when - handling requests. - -Components -========== - -- Module.java: - - Shows how to use Guice to bind all the components needed by your application. - -- Counter.java: - - An example of a component that contains state, in this case a simple counter. - -- ApplicationTimer.java: - - An example of a component that starts when the application starts and stops - when the application stops. - -Filters -======= - -- Filters.java: - - Creates the list of HTTP filters used by your application. - -- ExampleFilter.java - - A simple filter that adds a header to every response. \ No newline at end of file diff --git a/play-framework/routing-in-play/app/Filters.java b/play-framework/routing-in-play/app/Filters.java deleted file mode 100644 index 255de8ca93..0000000000 --- a/play-framework/routing-in-play/app/Filters.java +++ /dev/null @@ -1,46 +0,0 @@ -import javax.inject.*; -import play.*; -import play.mvc.EssentialFilter; -import play.http.HttpFilters; -import play.mvc.*; - -import filters.ExampleFilter; - -/** - * This class configures filters that run on every request. This - * class is queried by Play to get a list of filters. - * - * Play will automatically use filters from any class called - * Filters that is placed the root package. You can load filters - * from a different class by adding a `play.http.filters` setting to - * the application.conf configuration file. - */ -@Singleton -public class Filters implements HttpFilters { - - private final Environment env; - private final EssentialFilter exampleFilter; - - /** - * @param env Basic environment settings for the current application. - * @param exampleFilter A demonstration filter that adds a header to - */ - @Inject - public Filters(Environment env, ExampleFilter exampleFilter) { - this.env = env; - this.exampleFilter = exampleFilter; - } - - @Override - public EssentialFilter[] filters() { - // Use the example filter if we're running development mode. If - // we're running in production or test mode then don't use any - // filters at all. - if (env.mode().equals(Mode.DEV)) { - return new EssentialFilter[] { exampleFilter }; - } else { - return new EssentialFilter[] {}; - } - } - -} diff --git a/play-framework/routing-in-play/app/Module.java b/play-framework/routing-in-play/app/Module.java deleted file mode 100644 index 6e7d1766ef..0000000000 --- a/play-framework/routing-in-play/app/Module.java +++ /dev/null @@ -1,31 +0,0 @@ -import com.google.inject.AbstractModule; -import java.time.Clock; - -import services.ApplicationTimer; -import services.AtomicCounter; -import services.Counter; - -/** - * This class is a Guice module that tells Guice how to bind several - * different types. This Guice module is created when the Play - * application starts. - * - * Play will automatically use any class called `Module` that is in - * the root package. You can create modules in other locations by - * adding `play.modules.enabled` settings to the `application.conf` - * configuration file. - */ -public class Module extends AbstractModule { - - @Override - public void configure() { - // Use the system clock as the default implementation of Clock - bind(Clock.class).toInstance(Clock.systemDefaultZone()); - // Ask Guice to create an instance of ApplicationTimer when the - // application starts. - bind(ApplicationTimer.class).asEagerSingleton(); - // Set AtomicCounter as the implementation for Counter. - bind(Counter.class).to(AtomicCounter.class); - } - -} diff --git a/play-framework/routing-in-play/app/controllers/HomeController.java b/play-framework/routing-in-play/app/controllers/HomeController.java index 6e340d594f..c7f6daa898 100644 --- a/play-framework/routing-in-play/app/controllers/HomeController.java +++ b/play-framework/routing-in-play/app/controllers/HomeController.java @@ -1,8 +1,13 @@ package controllers; +import play.libs.concurrent.HttpExecutionContext; import play.mvc.*; +import play.twirl.api.Html; -import views.html.*; +import javax.inject.Inject; +import java.util.concurrent.CompletionStage; + +import static java.util.concurrent.CompletableFuture.supplyAsync; /** * This controller contains an action to handle HTTP requests @@ -16,18 +21,33 @@ public class HomeController extends Controller { * this method will be called when the application receives a * GET request with a path of /. */ - public Result index(String author,int id) { - return ok("Routing in Play by:"+author+" ID:"+id); - } - public Result greet(String name,int age) { - return ok("Hello "+name+", you are "+age+" years old"); - } - public Result introduceMe(String data) { - String[] clientData=data.split(","); - return ok("Your name is "+clientData[0]+", you are "+clientData[1]+" years old"); - } - public Result squareMe(Long num) { - return ok(num+" Squared is "+(num*num)); + public Result index() { + return ok(views.html.index.render()); } + public Result writer(String author) { + return ok("Routing in Play by " + author); + } + + public Result viewUser(String userId) { + final String response = String.format("Got user id {} in request.", userId); + return ok(response); + } + + public Result greet(String name, int age) { + return ok("Hello " + name + ", you are " + age + " years old"); + } + + public Result squareMe(Long num) { + return ok(num + " Squared is " + (num * num)); + } + + public Result writer(String author, int id) { + return ok("Routing in Play by: " + author + " ID: " + id); + } + + public Result introduceMe(String data) { + String[] clientData = data.split(","); + return ok("Your name is " + clientData[0] + ", you are " + clientData[1] + " years old"); + } } diff --git a/play-framework/routing-in-play/app/filters/ExampleFilter.java b/play-framework/routing-in-play/app/filters/ExampleFilter.java deleted file mode 100644 index 67a6a36cc3..0000000000 --- a/play-framework/routing-in-play/app/filters/ExampleFilter.java +++ /dev/null @@ -1,45 +0,0 @@ -package filters; - -import akka.stream.Materializer; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.Executor; -import java.util.function.Function; -import javax.inject.*; -import play.mvc.*; -import play.mvc.Http.RequestHeader; - - -/** - * This is a simple filter that adds a header to all requests. It's - * added to the application's list of filters by the - * {@link Filters} class. - */ -@Singleton -public class ExampleFilter extends Filter { - - private final Executor exec; - - /** - * @param mat This object is needed to handle streaming of requests - * and responses. - * @param exec This class is needed to execute code asynchronously. - * It is used below by the thenAsyncApply method. - */ - @Inject - public ExampleFilter(Materializer mat, Executor exec) { - super(mat); - this.exec = exec; - } - - @Override - public CompletionStage apply( - Function> next, - RequestHeader requestHeader) { - - return next.apply(requestHeader).thenApplyAsync( - result -> result.withHeader("X-ExampleFilter", "foo"), - exec - ); - } - -} diff --git a/play-framework/routing-in-play/app/services/ApplicationTimer.java b/play-framework/routing-in-play/app/services/ApplicationTimer.java deleted file mode 100644 index a951562b1d..0000000000 --- a/play-framework/routing-in-play/app/services/ApplicationTimer.java +++ /dev/null @@ -1,50 +0,0 @@ -package services; - -import java.time.Clock; -import java.time.Instant; -import java.util.concurrent.CompletableFuture; -import javax.inject.*; -import play.Logger; -import play.inject.ApplicationLifecycle; - -/** - * This class demonstrates how to run code when the - * application starts and stops. It starts a timer when the - * application starts. When the application stops it prints out how - * long the application was running for. - * - * This class is registered for Guice dependency injection in the - * {@link Module} class. We want the class to start when the application - * starts, so it is registered as an "eager singleton". See the code - * in the {@link Module} class to see how this happens. - * - * This class needs to run code when the server stops. It uses the - * application's {@link ApplicationLifecycle} to register a stop hook. - */ -@Singleton -public class ApplicationTimer { - - private final Clock clock; - private final ApplicationLifecycle appLifecycle; - private final Instant start; - - @Inject - public ApplicationTimer(Clock clock, ApplicationLifecycle appLifecycle) { - this.clock = clock; - this.appLifecycle = appLifecycle; - // This code is called when the application starts. - start = clock.instant(); - Logger.info("ApplicationTimer demo: Starting application at " + start); - - // When the application starts, register a stop hook with the - // ApplicationLifecycle object. The code inside the stop hook will - // be run when the application stops. - appLifecycle.addStopHook(() -> { - Instant stop = clock.instant(); - Long runningTime = stop.getEpochSecond() - start.getEpochSecond(); - Logger.info("ApplicationTimer demo: Stopping application at " + clock.instant() + " after " + runningTime + "s."); - return CompletableFuture.completedFuture(null); - }); - } - -} diff --git a/play-framework/routing-in-play/app/services/AtomicCounter.java b/play-framework/routing-in-play/app/services/AtomicCounter.java deleted file mode 100644 index 41f741cbf7..0000000000 --- a/play-framework/routing-in-play/app/services/AtomicCounter.java +++ /dev/null @@ -1,26 +0,0 @@ -package services; - -import java.util.concurrent.atomic.AtomicInteger; -import javax.inject.*; - -/** - * This class is a concrete implementation of the {@link Counter} trait. - * It is configured for Guice dependency injection in the {@link Module} - * class. - * - * This class has a {@link Singleton} annotation because we need to make - * sure we only use one counter per application. Without this - * annotation we would get a new instance every time a {@link Counter} is - * injected. - */ -@Singleton -public class AtomicCounter implements Counter { - - private final AtomicInteger atomicCounter = new AtomicInteger(); - - @Override - public int nextCount() { - return atomicCounter.getAndIncrement(); - } - -} diff --git a/play-framework/routing-in-play/app/services/Counter.java b/play-framework/routing-in-play/app/services/Counter.java deleted file mode 100644 index dadad8b09d..0000000000 --- a/play-framework/routing-in-play/app/services/Counter.java +++ /dev/null @@ -1,13 +0,0 @@ -package services; - -/** - * This interface demonstrates how to create a component that is injected - * into a controller. The interface represents a counter that returns a - * incremented number each time it is called. - * - * The {@link Modules} class binds this interface to the - * {@link AtomicCounter} implementation. - */ -public interface Counter { - int nextCount(); -} diff --git a/play-framework/routing-in-play/app/views/index.scala.html b/play-framework/routing-in-play/app/views/index.scala.html index 4539f5a10b..68d37fb1d4 100644 --- a/play-framework/routing-in-play/app/views/index.scala.html +++ b/play-framework/routing-in-play/app/views/index.scala.html @@ -1,20 +1,5 @@ -@* - * This template takes a single argument, a String containing a - * message to display. - *@ -@(message: String) +@() -@* - * Call the `main` template with two arguments. The first - * argument is a `String` with the title of the page, the second - * argument is an `Html` object containing the body of the page. - *@ @main("Welcome to Play") { - - @* - * Get an `Html` object by calling the built-in Play welcome - * template and passing a `String` message. - *@ - @play20.welcome(message, style = "Java") - +

    Welcome to Play!

    } diff --git a/play-framework/routing-in-play/app/views/main.scala.html b/play-framework/routing-in-play/app/views/main.scala.html index 9414f4be6e..c5f755f236 100644 --- a/play-framework/routing-in-play/app/views/main.scala.html +++ b/play-framework/routing-in-play/app/views/main.scala.html @@ -13,11 +13,12 @@ @title - @* And here's where we render the `Html` object containing * the page content. *@ @content + + diff --git a/play-framework/routing-in-play/bin/activator b/play-framework/routing-in-play/bin/activator deleted file mode 100644 index a8b11d482f..0000000000 --- a/play-framework/routing-in-play/bin/activator +++ /dev/null @@ -1,397 +0,0 @@ -#!/usr/bin/env bash - -### ------------------------------- ### -### Helper methods for BASH scripts ### -### ------------------------------- ### - -realpath () { -( - TARGET_FILE="$1" - FIX_CYGPATH="$2" - - cd "$(dirname "$TARGET_FILE")" - TARGET_FILE=$(basename "$TARGET_FILE") - - COUNT=0 - while [ -L "$TARGET_FILE" -a $COUNT -lt 100 ] - do - TARGET_FILE=$(readlink "$TARGET_FILE") - cd "$(dirname "$TARGET_FILE")" - TARGET_FILE=$(basename "$TARGET_FILE") - COUNT=$(($COUNT + 1)) - done - - # make sure we grab the actual windows path, instead of cygwin's path. - if [[ "x$FIX_CYGPATH" != "x" ]]; then - echo "$(cygwinpath "$(pwd -P)/$TARGET_FILE")" - else - echo "$(pwd -P)/$TARGET_FILE" - fi -) -} - - -# Uses uname to detect if we're in the odd cygwin environment. -is_cygwin() { - local os=$(uname -s) - case "$os" in - CYGWIN*) return 0 ;; - *) return 1 ;; - esac -} - -# TODO - Use nicer bash-isms here. -CYGWIN_FLAG=$(if is_cygwin; then echo true; else echo false; fi) - - -# This can fix cygwin style /cygdrive paths so we get the -# windows style paths. -cygwinpath() { - local file="$1" - if [[ "$CYGWIN_FLAG" == "true" ]]; then - echo $(cygpath -w $file) - else - echo $file - fi -} - -# Make something URI friendly -make_url() { - url="$1" - local nospaces=${url// /%20} - if is_cygwin; then - echo "/${nospaces//\\//}" - else - echo "$nospaces" - fi -} - -declare -a residual_args -declare -a java_args -declare -a scalac_args -declare -a sbt_commands -declare java_cmd=java -declare java_version -declare -r real_script_path="$(realpath "$0")" -declare -r sbt_home="$(realpath "$(dirname "$(dirname "$real_script_path")")")" -declare -r sbt_bin_dir="$(dirname "$real_script_path")" -declare -r app_version="1.3.10" - -declare -r script_name=activator -declare -r java_opts=( "${ACTIVATOR_OPTS[@]}" "${SBT_OPTS[@]}" "${JAVA_OPTS[@]}" "${java_opts[@]}" ) -userhome="$HOME" -if is_cygwin; then - # cygwin sets home to something f-d up, set to real windows homedir - userhome="$USERPROFILE" -fi -declare -r activator_user_home_dir="${userhome}/.activator" -declare -r java_opts_config_home="${activator_user_home_dir}/activatorconfig.txt" -declare -r java_opts_config_version="${activator_user_home_dir}/${app_version}/activatorconfig.txt" - -echoerr () { - echo 1>&2 "$@" -} -vlog () { - [[ $verbose || $debug ]] && echoerr "$@" -} -dlog () { - [[ $debug ]] && echoerr "$@" -} - -jar_file () { - echo "$(cygwinpath "${sbt_home}/libexec/activator-launch-${app_version}.jar")" -} - -acquire_sbt_jar () { - sbt_jar="$(jar_file)" - - if [[ ! -f "$sbt_jar" ]]; then - echoerr "Could not find launcher jar: $sbt_jar" - exit 2 - fi -} - -execRunner () { - # print the arguments one to a line, quoting any containing spaces - [[ $verbose || $debug ]] && echo "# Executing command line:" && { - for arg; do - if printf "%s\n" "$arg" | grep -q ' '; then - printf "\"%s\"\n" "$arg" - else - printf "%s\n" "$arg" - fi - done - echo "" - } - - # THis used to be exec, but we loose the ability to re-hook stty then - # for cygwin... Maybe we should flag the feature here... - "$@" -} - -addJava () { - dlog "[addJava] arg = '$1'" - java_args=( "${java_args[@]}" "$1" ) -} -addSbt () { - dlog "[addSbt] arg = '$1'" - sbt_commands=( "${sbt_commands[@]}" "$1" ) -} -addResidual () { - dlog "[residual] arg = '$1'" - residual_args=( "${residual_args[@]}" "$1" ) -} -addDebugger () { - addJava "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=$1" -} - -get_mem_opts () { - # if we detect any of these settings in ${JAVA_OPTS} we need to NOT output our settings. - # The reason is the Xms/Xmx, if they don't line up, cause errors. - if [[ "${JAVA_OPTS}" == *-Xmx* ]] || [[ "${JAVA_OPTS}" == *-Xms* ]] || [[ "${JAVA_OPTS}" == *-XX:MaxPermSize* ]] || [[ "${JAVA_OPTS}" == *-XX:MaxMetaspaceSize* ]] || [[ "${JAVA_OPTS}" == *-XX:ReservedCodeCacheSize* ]]; then - echo "" - else - # a ham-fisted attempt to move some memory settings in concert - # so they need not be messed around with individually. - local mem=${1:-1024} - local codecache=$(( $mem / 8 )) - (( $codecache > 128 )) || codecache=128 - (( $codecache < 512 )) || codecache=512 - local class_metadata_size=$(( $codecache * 2 )) - local class_metadata_opt=$([[ "$java_version" < "1.8" ]] && echo "MaxPermSize" || echo "MaxMetaspaceSize") - - echo "-Xms${mem}m -Xmx${mem}m -XX:ReservedCodeCacheSize=${codecache}m -XX:${class_metadata_opt}=${class_metadata_size}m" - fi -} - -require_arg () { - local type="$1" - local opt="$2" - local arg="$3" - if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then - echo "$opt requires <$type> argument" - exit 1 - fi -} - -is_function_defined() { - declare -f "$1" > /dev/null -} - -# If we're *not* running in a terminal, and we don't have any arguments, then we need to add the 'ui' parameter -detect_terminal_for_ui() { - [[ ! -t 0 ]] && [[ "${#residual_args}" == "0" ]] && { - addResidual "ui" - } - # SPECIAL TEST FOR MAC - [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]] && [[ "${#residual_args}" == "0" ]] && { - echo "Detected MAC OSX launched script...." - echo "Swapping to UI" - addResidual "ui" - } -} - -process_args () { - while [[ $# -gt 0 ]]; do - case "$1" in - -h|-help) usage; exit 1 ;; - -v|-verbose) verbose=1 && shift ;; - -d|-debug) debug=1 && shift ;; - - -ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;; - -mem) require_arg integer "$1" "$2" && sbt_mem="$2" && shift 2 ;; - -jvm-debug) require_arg port "$1" "$2" && addDebugger $2 && shift 2 ;; - -batch) exec &1 | awk -F '"' '/version/ {print $2}') - vlog "[process_args] java_version = '$java_version'" -} - -# Detect that we have java installed. -checkJava() { - local required_version="$1" - # Now check to see if it's a good enough version - if [[ "$java_version" == "" ]]; then - echo - echo No java installations was detected. - echo Please go to http://www.java.com/getjava/ and download - echo - exit 1 - elif [[ ! "$java_version" > "$required_version" ]]; then - echo - echo The java installation you have is not up to date - echo $script_name requires at least version $required_version+, you have - echo version $java_version - echo - echo Please go to http://www.java.com/getjava/ and download - echo a valid Java Runtime and install before running $script_name. - echo - exit 1 - fi -} - - -run() { - # no jar? download it. - [[ -f "$sbt_jar" ]] || acquire_sbt_jar "$sbt_version" || { - # still no jar? uh-oh. - echo "Download failed. Obtain the sbt-launch.jar manually and place it at $sbt_jar" - exit 1 - } - - # process the combined args, then reset "$@" to the residuals - process_args "$@" - detect_terminal_for_ui - set -- "${residual_args[@]}" - argumentCount=$# - - # TODO - java check should be configurable... - checkJava "1.6" - - #If we're in cygwin, we should use the windows config, and terminal hacks - if [[ "$CYGWIN_FLAG" == "true" ]]; then - stty -icanon min 1 -echo > /dev/null 2>&1 - addJava "-Djline.terminal=jline.UnixTerminal" - addJava "-Dsbt.cygwin=true" - fi - - # run sbt - execRunner "$java_cmd" \ - "-Dactivator.home=$(make_url "$sbt_home")" \ - ${SBT_OPTS:-$default_sbt_opts} \ - $(get_mem_opts $sbt_mem) \ - ${JAVA_OPTS} \ - ${java_args[@]} \ - -jar "$sbt_jar" \ - "${sbt_commands[@]}" \ - "${residual_args[@]}" - - exit_code=$? - - # Clean up the terminal from cygwin hacks. - if [[ "$CYGWIN_FLAG" == "true" ]]; then - stty icanon echo > /dev/null 2>&1 - fi - exit $exit_code -} - - -declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy" -declare -r sbt_opts_file=".sbtopts" -declare -r etc_sbt_opts_file="${sbt_home}/conf/sbtopts" -declare -r win_sbt_opts_file="${sbt_home}/conf/sbtconfig.txt" - -usage() { - cat < path to global settings/plugins directory (default: ~/.sbt) - -sbt-boot path to shared boot directory (default: ~/.sbt/boot in 0.11 series) - -ivy path to local Ivy repository (default: ~/.ivy2) - -mem set memory options (default: $sbt_mem, which is $(get_mem_opts $sbt_mem)) - -no-share use all local caches; no sharing - -no-global uses global caches, but does not use global ~/.sbt directory. - -jvm-debug Turn on JVM debugging, open at the given port. - -batch Disable interactive mode - - # sbt version (default: from project/build.properties if present, else latest release) - -sbt-version use the specified version of sbt - -sbt-jar use the specified jar as the sbt launcher - -sbt-rc use an RC version of sbt - -sbt-snapshot use a snapshot version of sbt - - # java version (default: java from PATH, currently $(java -version 2>&1 | grep version)) - -java-home alternate JAVA_HOME - - # jvm options and output control - JAVA_OPTS environment variable, if unset uses "$java_opts" - SBT_OPTS environment variable, if unset uses "$default_sbt_opts" - ACTIVATOR_OPTS Environment variable, if unset uses "" - .sbtopts if this file exists in the current directory, it is - prepended to the runner args - /etc/sbt/sbtopts if this file exists, it is prepended to the runner args - -Dkey=val pass -Dkey=val directly to the java runtime - -J-X pass option -X directly to the java runtime - (-J is stripped) - -S-X add -X to sbt's scalacOptions (-S is stripped) - -In the case of duplicated or conflicting options, the order above -shows precedence: JAVA_OPTS lowest, command line options highest. -EOM -} - - - -process_my_args () { - while [[ $# -gt 0 ]]; do - case "$1" in - -no-colors) addJava "-Dsbt.log.noformat=true" && shift ;; - -no-share) addJava "$noshare_opts" && shift ;; - -no-global) addJava "-Dsbt.global.base=$(pwd)/project/.sbtboot" && shift ;; - -sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;; - -sbt-dir) require_arg path "$1" "$2" && addJava "-Dsbt.global.base=$2" && shift 2 ;; - -debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;; - -batch) exec ^&1') do ( - if %%~j==java set JAVAINSTALLED=1 - if %%~j==openjdk set JAVAINSTALLED=1 -) - -rem Detect the same thing about javac -if "%_JAVACCMD%"=="" ( - if not "%JAVA_HOME%"=="" ( - if exist "%JAVA_HOME%\bin\javac.exe" set "_JAVACCMD=%JAVA_HOME%\bin\javac.exe" - ) -) -if "%_JAVACCMD%"=="" set _JAVACCMD=javac -for /F %%j in ('"%_JAVACCMD%" -version 2^>^&1') do ( - if %%~j==javac set JAVACINSTALLED=1 -) - -rem BAT has no logical or, so we do it OLD SCHOOL! Oppan Redmond Style -set JAVAOK=true -if not defined JAVAINSTALLED set JAVAOK=false -if not defined JAVACINSTALLED set JAVAOK=false - -if "%JAVAOK%"=="false" ( - echo. - echo A Java JDK is not installed or can't be found. - if not "%JAVA_HOME%"=="" ( - echo JAVA_HOME = "%JAVA_HOME%" - ) - echo. - echo Please go to - echo http://www.oracle.com/technetwork/java/javase/downloads/index.html - echo and download a valid Java JDK and install before running Activator. - echo. - echo If you think this message is in error, please check - echo your environment variables to see if "java.exe" and "javac.exe" are - echo available via JAVA_HOME or PATH. - echo. - if defined DOUBLECLICKED pause - exit /B 1 -) - -rem Check what Java version is being used to determine what memory options to use -for /f "tokens=3" %%g in ('java -version 2^>^&1 ^| findstr /i "version"') do ( - set JAVA_VERSION=%%g -) - -rem Strips away the " characters -set JAVA_VERSION=%JAVA_VERSION:"=% - -rem TODO Check if there are existing mem settings in JAVA_OPTS/CFG_OPTS and use those instead of the below -for /f "delims=. tokens=1-3" %%v in ("%JAVA_VERSION%") do ( - set MAJOR=%%v - set MINOR=%%w - set BUILD=%%x - - set META_SIZE=-XX:MetaspaceSize=64M -XX:MaxMetaspaceSize=256M - if "!MINOR!" LSS "8" ( - set META_SIZE=-XX:PermSize=64M -XX:MaxPermSize=256M - ) - - set MEM_OPTS=!META_SIZE! - ) - -rem We use the value of the JAVA_OPTS environment variable if defined, rather than the config. -set _JAVA_OPTS=%JAVA_OPTS% -if "%_JAVA_OPTS%"=="" set _JAVA_OPTS=%CFG_OPTS% - -set DEBUG_OPTS= - -rem Loop through the arguments, building remaining args in args variable -set args= -:argsloop -if not "%~1"=="" ( - rem Checks if the argument contains "-D" and if true, adds argument 1 with 2 and puts an equal sign between them. - rem This is done since batch considers "=" to be a delimiter so we need to circumvent this behavior with a small hack. - set arg1=%~1 - if "!arg1:~0,2!"=="-D" ( - set "args=%args% "%~1"="%~2"" - shift - shift - goto argsloop - ) - - if "%~1"=="-jvm-debug" ( - if not "%~2"=="" ( - rem This piece of magic somehow checks that an argument is a number - for /F "delims=0123456789" %%i in ("%~2") do ( - set var="%%i" - ) - if defined var ( - rem Not a number, assume no argument given and default to 9999 - set JPDA_PORT=9999 - ) else ( - rem Port was given, shift arguments - set JPDA_PORT=%~2 - shift - ) - ) else ( - set JPDA_PORT=9999 - ) - shift - - set DEBUG_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=!JPDA_PORT! - goto argsloop - ) - rem else - set "args=%args% "%~1"" - shift - goto argsloop -) - -:run - -if "!args!"=="" ( - if defined DOUBLECLICKED ( - set CMDS="ui" - ) else set CMDS=!args! -) else set CMDS=!args! - -rem We add a / in front, so we get file:///C: instead of file://C: -rem Java considers the later a UNC path. -rem We also attempt a solid effort at making it URI friendly. -rem We don't even bother with UNC paths. -set JAVA_FRIENDLY_HOME_1=/!ACTIVATOR_HOME:\=/! -set JAVA_FRIENDLY_HOME=/!JAVA_FRIENDLY_HOME_1: =%%20! - -rem Checks if the command contains spaces to know if it should be wrapped in quotes or not -set NON_SPACED_CMD=%_JAVACMD: =% -if "%_JAVACMD%"=="%NON_SPACED_CMD%" %_JAVACMD% %DEBUG_OPTS% %MEM_OPTS% %ACTIVATOR_OPTS% %SBT_OPTS% %_JAVA_OPTS% "-Dactivator.home=%JAVA_FRIENDLY_HOME%" -jar "%ACTIVATOR_HOME%\libexec\%ACTIVATOR_LAUNCH_JAR%" %CMDS% -if NOT "%_JAVACMD%"=="%NON_SPACED_CMD%" "%_JAVACMD%" %DEBUG_OPTS% %MEM_OPTS% %ACTIVATOR_OPTS% %SBT_OPTS% %_JAVA_OPTS% "-Dactivator.home=%JAVA_FRIENDLY_HOME%" -jar "%ACTIVATOR_HOME%\libexec\%ACTIVATOR_LAUNCH_JAR%" %CMDS% - -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end - -@endlocal - -exit /B %ERROR_CODE% diff --git a/play-framework/routing-in-play/build.sbt b/play-framework/routing-in-play/build.sbt index 083d071676..4fb0126eaa 100644 --- a/play-framework/routing-in-play/build.sbt +++ b/play-framework/routing-in-play/build.sbt @@ -1,13 +1,10 @@ -name := """webapp""" +name := """play-routing""" +organization := "com.baeldung" version := "1.0-SNAPSHOT" lazy val root = (project in file(".")).enablePlugins(PlayJava) -scalaVersion := "2.11.7" +scalaVersion := "2.13.0" -libraryDependencies ++= Seq( - javaJdbc, - cache, - javaWs -) +libraryDependencies += guice diff --git a/play-framework/routing-in-play/conf/application.conf b/play-framework/routing-in-play/conf/application.conf index 489d3f9b3e..85c184dcb1 100644 --- a/play-framework/routing-in-play/conf/application.conf +++ b/play-framework/routing-in-play/conf/application.conf @@ -1,353 +1,2 @@ # This is the main configuration file for the application. # https://www.playframework.com/documentation/latest/ConfigFile -# ~~~~~ -# Play uses HOCON as its configuration file format. HOCON has a number -# of advantages over other config formats, but there are two things that -# can be used when modifying settings. -# -# You can include other configuration files in this main application.conf file: -#include "extra-config.conf" -# -# You can declare variables and substitute for them: -#mykey = ${some.value} -# -# And if an environment variable exists when there is no other subsitution, then -# HOCON will fall back to substituting environment variable: -#mykey = ${JAVA_HOME} - -## Akka -# https://www.playframework.com/documentation/latest/ScalaAkka#Configuration -# https://www.playframework.com/documentation/latest/JavaAkka#Configuration -# ~~~~~ -# Play uses Akka internally and exposes Akka Streams and actors in Websockets and -# other streaming HTTP responses. -akka { - # "akka.log-config-on-start" is extraordinarly useful because it log the complete - # configuration at INFO level, including defaults and overrides, so it s worth - # putting at the very top. - # - # Put the following in your conf/logback.xml file: - # - # - # - # And then uncomment this line to debug the configuration. - # - #log-config-on-start = true -} - -## Secret key -# http://www.playframework.com/documentation/latest/ApplicationSecret -# ~~~~~ -# The secret key is used to sign Play's session cookie. -# This must be changed for production, but we don't recommend you change it in this file. -play.crypto.secret = "changeme" - -## Modules -# https://www.playframework.com/documentation/latest/Modules -# ~~~~~ -# Control which modules are loaded when Play starts. Note that modules are -# the replacement for "GlobalSettings", which are deprecated in 2.5.x. -# Please see https://www.playframework.com/documentation/latest/GlobalSettings -# for more information. -# -# You can also extend Play functionality by using one of the publically available -# Play modules: https://playframework.com/documentation/latest/ModuleDirectory -play.modules { - # By default, Play will load any class called Module that is defined - # in the root package (the "app" directory), or you can define them - # explicitly below. - # If there are any built-in modules that you want to disable, you can list them here. - #enabled += my.application.Module - - # If there are any built-in modules that you want to disable, you can list them here. - #disabled += "" -} - -## IDE -# https://www.playframework.com/documentation/latest/IDE -# ~~~~~ -# Depending on your IDE, you can add a hyperlink for errors that will jump you -# directly to the code location in the IDE in dev mode. The following line makes -# use of the IntelliJ IDEA REST interface: -#play.editor="http://localhost:63342/api/file/?file=%s&line=%s" - -## Internationalisation -# https://www.playframework.com/documentation/latest/JavaI18N -# https://www.playframework.com/documentation/latest/ScalaI18N -# ~~~~~ -# Play comes with its own i18n settings, which allow the user's preferred language -# to map through to internal messages, or allow the language to be stored in a cookie. -play.i18n { - # The application languages - langs = [ "en" ] - - # Whether the language cookie should be secure or not - #langCookieSecure = true - - # Whether the HTTP only attribute of the cookie should be set to true - #langCookieHttpOnly = true -} - -## Play HTTP settings -# ~~~~~ -play.http { - ## Router - # https://www.playframework.com/documentation/latest/JavaRouting - # https://www.playframework.com/documentation/latest/ScalaRouting - # ~~~~~ - # Define the Router object to use for this application. - # This router will be looked up first when the application is starting up, - # so make sure this is the entry point. - # Furthermore, it's assumed your route file is named properly. - # So for an application router like `my.application.Router`, - # you may need to define a router file `conf/my.application.routes`. - # Default to Routes in the root package (aka "apps" folder) (and conf/routes) - #router = my.application.Router - - ## Action Creator - # https://www.playframework.com/documentation/latest/JavaActionCreator - # ~~~~~ - #actionCreator = null - - ## ErrorHandler - # https://www.playframework.com/documentation/latest/JavaRouting - # https://www.playframework.com/documentation/latest/ScalaRouting - # ~~~~~ - # If null, will attempt to load a class called ErrorHandler in the root package, - #errorHandler = null - - ## Filters - # https://www.playframework.com/documentation/latest/ScalaHttpFilters - # https://www.playframework.com/documentation/latest/JavaHttpFilters - # ~~~~~ - # Filters run code on every request. They can be used to perform - # common logic for all your actions, e.g. adding common headers. - # Defaults to "Filters" in the root package (aka "apps" folder) - # Alternatively you can explicitly register a class here. - #filters = my.application.Filters - - ## Session & Flash - # https://www.playframework.com/documentation/latest/JavaSessionFlash - # https://www.playframework.com/documentation/latest/ScalaSessionFlash - # ~~~~~ - session { - # Sets the cookie to be sent only over HTTPS. - #secure = true - - # Sets the cookie to be accessed only by the server. - #httpOnly = true - - # Sets the max-age field of the cookie to 5 minutes. - # NOTE: this only sets when the browser will discard the cookie. Play will consider any - # cookie value with a valid signature to be a valid session forever. To implement a server side session timeout, - # you need to put a timestamp in the session and check it at regular intervals to possibly expire it. - #maxAge = 300 - - # Sets the domain on the session cookie. - #domain = "example.com" - } - - flash { - # Sets the cookie to be sent only over HTTPS. - #secure = true - - # Sets the cookie to be accessed only by the server. - #httpOnly = true - } -} - -## Netty Provider -# https://www.playframework.com/documentation/latest/SettingsNetty -# ~~~~~ -play.server.netty { - # Whether the Netty wire should be logged - #log.wire = true - - # If you run Play on Linux, you can use Netty's native socket transport - # for higher performance with less garbage. - #transport = "native" -} - -## WS (HTTP Client) -# https://www.playframework.com/documentation/latest/ScalaWS#Configuring-WS -# ~~~~~ -# The HTTP client primarily used for REST APIs. The default client can be -# configured directly, but you can also create different client instances -# with customized settings. You must enable this by adding to build.sbt: -# -# libraryDependencies += ws // or javaWs if using java -# -play.ws { - # Sets HTTP requests not to follow 302 requests - #followRedirects = false - - # Sets the maximum number of open HTTP connections for the client. - #ahc.maxConnectionsTotal = 50 - - ## WS SSL - # https://www.playframework.com/documentation/latest/WsSSL - # ~~~~~ - ssl { - # Configuring HTTPS with Play WS does not require programming. You can - # set up both trustManager and keyManager for mutual authentication, and - # turn on JSSE debugging in development with a reload. - #debug.handshake = true - #trustManager = { - # stores = [ - # { type = "JKS", path = "exampletrust.jks" } - # ] - #} - } -} - -## Cache -# https://www.playframework.com/documentation/latest/JavaCache -# https://www.playframework.com/documentation/latest/ScalaCache -# ~~~~~ -# Play comes with an integrated cache API that can reduce the operational -# overhead of repeated requests. You must enable this by adding to build.sbt: -# -# libraryDependencies += cache -# -play.cache { - # If you want to bind several caches, you can bind the individually - #bindCaches = ["db-cache", "user-cache", "session-cache"] -} - -## Filters -# https://www.playframework.com/documentation/latest/Filters -# ~~~~~ -# There are a number of built-in filters that can be enabled and configured -# to give Play greater security. You must enable this by adding to build.sbt: -# -# libraryDependencies += filters -# -play.filters { - ## CORS filter configuration - # https://www.playframework.com/documentation/latest/CorsFilter - # ~~~~~ - # CORS is a protocol that allows web applications to make requests from the browser - # across different domains. - # NOTE: You MUST apply the CORS configuration before the CSRF filter, as CSRF has - # dependencies on CORS settings. - cors { - # Filter paths by a whitelist of path prefixes - #pathPrefixes = ["/some/path", ...] - - # The allowed origins. If null, all origins are allowed. - #allowedOrigins = ["http://www.example.com"] - - # The allowed HTTP methods. If null, all methods are allowed - #allowedHttpMethods = ["GET", "POST"] - } - - ## CSRF Filter - # https://www.playframework.com/documentation/latest/ScalaCsrf#Applying-a-global-CSRF-filter - # https://www.playframework.com/documentation/latest/JavaCsrf#Applying-a-global-CSRF-filter - # ~~~~~ - # Play supports multiple methods for verifying that a request is not a CSRF request. - # The primary mechanism is a CSRF token. This token gets placed either in the query string - # or body of every form submitted, and also gets placed in the users session. - # Play then verifies that both tokens are present and match. - csrf { - # Sets the cookie to be sent only over HTTPS - #cookie.secure = true - - # Defaults to CSRFErrorHandler in the root package. - #errorHandler = MyCSRFErrorHandler - } - - ## Security headers filter configuration - # https://www.playframework.com/documentation/latest/SecurityHeaders - # ~~~~~ - # Defines security headers that prevent XSS attacks. - # If enabled, then all options are set to the below configuration by default: - headers { - # The X-Frame-Options header. If null, the header is not set. - #frameOptions = "DENY" - - # The X-XSS-Protection header. If null, the header is not set. - #xssProtection = "1; mode=block" - - # The X-Content-Type-Options header. If null, the header is not set. - #contentTypeOptions = "nosniff" - - # The X-Permitted-Cross-Domain-Policies header. If null, the header is not set. - #permittedCrossDomainPolicies = "master-only" - - # The Content-Security-Policy header. If null, the header is not set. - #contentSecurityPolicy = "default-src 'self'" - } - - ## Allowed hosts filter configuration - # https://www.playframework.com/documentation/latest/AllowedHostsFilter - # ~~~~~ - # Play provides a filter that lets you configure which hosts can access your application. - # This is useful to prevent cache poisoning attacks. - hosts { - # Allow requests to example.com, its subdomains, and localhost:9000. - #allowed = [".example.com", "localhost:9000"] - } -} - -## Evolutions -# https://www.playframework.com/documentation/latest/Evolutions -# ~~~~~ -# Evolutions allows database scripts to be automatically run on startup in dev mode -# for database migrations. You must enable this by adding to build.sbt: -# -# libraryDependencies += evolutions -# -play.evolutions { - # You can disable evolutions for a specific datasource if necessary - #db.default.enabled = false -} - -## Database Connection Pool -# https://www.playframework.com/documentation/latest/SettingsJDBC -# ~~~~~ -# Play doesn't require a JDBC database to run, but you can easily enable one. -# -# libraryDependencies += jdbc -# -play.db { - # The combination of these two settings results in "db.default" as the - # default JDBC pool: - #config = "db" - #default = "default" - - # Play uses HikariCP as the default connection pool. You can override - # settings by changing the prototype: - prototype { - # Sets a fixed JDBC connection pool size of 50 - #hikaricp.minimumIdle = 50 - #hikaricp.maximumPoolSize = 50 - } -} - -## JDBC Datasource -# https://www.playframework.com/documentation/latest/JavaDatabase -# https://www.playframework.com/documentation/latest/ScalaDatabase -# ~~~~~ -# Once JDBC datasource is set up, you can work with several different -# database options: -# -# Slick (Scala preferred option): https://www.playframework.com/documentation/latest/PlaySlick -# JPA (Java preferred option): https://playframework.com/documentation/latest/JavaJPA -# EBean: https://playframework.com/documentation/latest/JavaEbean -# Anorm: https://www.playframework.com/documentation/latest/ScalaAnorm -# -db { - # You can declare as many datasources as you want. - # By convention, the default datasource is named `default` - - # https://www.playframework.com/documentation/latest/Developing-with-the-H2-Database - #default.driver = org.h2.Driver - #default.url = "jdbc:h2:mem:play" - #default.username = sa - #default.password = "" - - # You can turn on SQL logging for any datasource - # https://www.playframework.com/documentation/latest/Highlights25#Logging-SQL-statements - #default.logSql=true -} diff --git a/play-framework/routing-in-play/conf/logback.xml b/play-framework/routing-in-play/conf/logback.xml index 86ec12c0af..e8c982543f 100644 --- a/play-framework/routing-in-play/conf/logback.xml +++ b/play-framework/routing-in-play/conf/logback.xml @@ -27,12 +27,6 @@ - - - - - - diff --git a/play-framework/routing-in-play/conf/routes b/play-framework/routing-in-play/conf/routes index f72d8a1a14..43dc4c8733 100644 --- a/play-framework/routing-in-play/conf/routes +++ b/play-framework/routing-in-play/conf/routes @@ -1,7 +1,15 @@ -GET / controllers.HomeController.index(author="Baeldung",id:Int?=1) -GET /:author controllers.HomeController.index(author,id:Int?=1) -GET /greet/:name/:age controllers.HomeController.greet(name,age:Integer) -GET /square/$num<[0-9]+> controllers.HomeController.squareMe(num:Long) +# Routes +# This file defines all application routes (Higher priority routes first) +# ~~~~ + +# An example controller showing a sample home page +GET / controllers.HomeController.index +GET /writer controllers.HomeController.writer(author = "Baeldung", id: Int ?= 1) +GET /writer/:author controllers.HomeController.writer(author: String, id: Int ?= 1) +GET /baeldung/:id controllers.HomeController.viewUser(id: String) +GET /greet/:name/:age controllers.HomeController.greet(name: String, age: Integer) +GET /square/$num<[0-9]+> controllers.HomeController.squareMe(num: Long) +GET /*data controllers.HomeController.introduceMe(data) + # Map static resources from the /public folder to the /assets URL path -GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset) -GET /*data controllers.HomeController.introduceMe(data) +GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset) diff --git a/play-framework/routing-in-play/libexec/activator-launch-1.3.10.jar b/play-framework/routing-in-play/libexec/activator-launch-1.3.10.jar deleted file mode 100644 index 69050e7dec..0000000000 Binary files a/play-framework/routing-in-play/libexec/activator-launch-1.3.10.jar and /dev/null differ diff --git a/play-framework/routing-in-play/project/build.properties b/play-framework/routing-in-play/project/build.properties index 6d22e3f2d1..c0bab04941 100644 --- a/play-framework/routing-in-play/project/build.properties +++ b/play-framework/routing-in-play/project/build.properties @@ -1,4 +1 @@ -#Activator-generated Properties -#Fri Sep 30 14:25:10 EAT 2016 -template.uuid=26c759a5-daf0-4e02-bcfa-ac69725267c0 -sbt.version=0.13.11 +sbt.version=1.2.8 diff --git a/play-framework/routing-in-play/project/plugins.sbt b/play-framework/routing-in-play/project/plugins.sbt index e8e7f602f7..1c8c62a0d5 100644 --- a/play-framework/routing-in-play/project/plugins.sbt +++ b/play-framework/routing-in-play/project/plugins.sbt @@ -1,21 +1,7 @@ // The Play plugin -addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.8") +addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.7.3") -// Web plugins -addSbtPlugin("com.typesafe.sbt" % "sbt-coffeescript" % "1.0.0") -addSbtPlugin("com.typesafe.sbt" % "sbt-less" % "1.1.0") -addSbtPlugin("com.typesafe.sbt" % "sbt-jshint" % "1.0.4") -addSbtPlugin("com.typesafe.sbt" % "sbt-rjs" % "1.0.8") -addSbtPlugin("com.typesafe.sbt" % "sbt-digest" % "1.1.1") -addSbtPlugin("com.typesafe.sbt" % "sbt-mocha" % "1.1.0") -addSbtPlugin("org.irundaia.sbt" % "sbt-sassify" % "1.4.6") - -// Play enhancer - this automatically generates getters/setters for public fields -// and rewrites accessors of these fields to use the getters/setters. Remove this -// plugin if you prefer not to have this feature, or disable on a per project -// basis using disablePlugins(PlayEnhancer) in your build.sbt -addSbtPlugin("com.typesafe.sbt" % "sbt-play-enhancer" % "1.1.0") - -// Play Ebean support, to enable, uncomment this line, and enable in your build.sbt using -// enablePlugins(PlayEbean). -// addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "3.0.2") +// Defines scaffolding (found under .g8 folder) +// http://www.foundweekends.org/giter8/scaffolding.html +// sbt "g8Scaffold form" +addSbtPlugin("org.foundweekends.giter8" % "sbt-giter8-scaffold" % "0.11.0") diff --git a/play-framework/routing-in-play/public/javascripts/hello.js b/play-framework/routing-in-play/public/javascripts/hello.js deleted file mode 100644 index 02ee13c7ca..0000000000 --- a/play-framework/routing-in-play/public/javascripts/hello.js +++ /dev/null @@ -1,3 +0,0 @@ -if (window.console) { - console.log("Welcome to your Play application's JavaScript!"); -} diff --git a/play-framework/routing-in-play/public/javascripts/main.js b/play-framework/routing-in-play/public/javascripts/main.js new file mode 100644 index 0000000000..e69de29bb2 diff --git a/play-framework/routing-in-play/test/ApplicationUnitTest.java b/play-framework/routing-in-play/test/ApplicationUnitTest.java deleted file mode 100644 index 572ce282bc..0000000000 --- a/play-framework/routing-in-play/test/ApplicationUnitTest.java +++ /dev/null @@ -1,45 +0,0 @@ -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.fasterxml.jackson.databind.JsonNode; -import org.junit.*; - -import play.mvc.*; -import play.test.*; -import play.data.DynamicForm; -import play.data.validation.ValidationError; -import play.data.validation.Constraints.RequiredValidator; -import play.i18n.Lang; -import play.libs.F; -import play.libs.F.*; -import play.twirl.api.Content; - -import static play.test.Helpers.*; -import static org.junit.Assert.*; - - -/** - * - * Simple (JUnit) tests that can call all parts of a play app. - * If you are interested in mocking a whole application, see the wiki for more details. - * - */ -public class ApplicationUnitTest { - - @Test - public void simpleCheck() { - int a = 1 + 1; - assertEquals(2, a); - } - - @Test - public void renderTemplate() { - Content html = views.html.index.render("Your new application is ready."); - assertEquals("text/html", html.contentType()); - assertTrue(html.body().contains("Your new application is ready.")); - } - - -} diff --git a/play-framework/routing-in-play/test/IntegrationTest.java b/play-framework/routing-in-play/test/IntegrationTest.java deleted file mode 100644 index c53c71e124..0000000000 --- a/play-framework/routing-in-play/test/IntegrationTest.java +++ /dev/null @@ -1,25 +0,0 @@ -import org.junit.*; - -import play.mvc.*; -import play.test.*; - -import static play.test.Helpers.*; -import static org.junit.Assert.*; - -import static org.fluentlenium.core.filter.FilterConstructor.*; - -public class IntegrationTest { - - /** - * add your integration test here - * in this example we just check if the welcome page is being shown - */ - @Test - public void test() { - running(testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, browser -> { - browser.goTo("http://localhost:3333"); - assertTrue(browser.pageSource().contains("Your new application is ready.")); - }); - } - -} diff --git a/play-framework/routing-in-play/test/controllers/HomeControllerUnitTest.java b/play-framework/routing-in-play/test/controllers/HomeControllerUnitTest.java new file mode 100644 index 0000000000..b911242ac7 --- /dev/null +++ b/play-framework/routing-in-play/test/controllers/HomeControllerUnitTest.java @@ -0,0 +1,36 @@ +package controllers; + +import org.junit.Test; +import play.Application; +import play.inject.guice.GuiceApplicationBuilder; +import play.mvc.Http; +import play.mvc.Result; +import play.test.WithApplication; +import play.twirl.api.Html; + +import java.util.Optional; +import java.util.concurrent.CompletionStage; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static play.mvc.Http.Status.*; +import static play.test.Helpers.GET; +import static play.test.Helpers.route; + +public class HomeControllerUnitTest extends WithApplication { + + @Override + protected Application provideApplication() { + return new GuiceApplicationBuilder().build(); + } + + @Test + public void givenRequest_whenRootPath_ThenStatusOkay() { + Http.RequestBuilder request = new Http.RequestBuilder() + .method(GET) + .uri("/"); + + Result result = route(app, request); + assertEquals(OK, result.status()); + } +} diff --git a/play-framework/routing-in-play/.gitignore b/play-framework/student-api/.gitignore similarity index 94% rename from play-framework/routing-in-play/.gitignore rename to play-framework/student-api/.gitignore index eb372fc719..e497f3fc67 100644 --- a/play-framework/routing-in-play/.gitignore +++ b/play-framework/student-api/.gitignore @@ -1,6 +1,7 @@ logs target /.idea +/.g8 /.idea_modules /.classpath /.project diff --git a/play-framework/student-api/app/controllers/StudentController.java b/play-framework/student-api/app/controllers/StudentController.java new file mode 100644 index 0000000000..5373511560 --- /dev/null +++ b/play-framework/student-api/app/controllers/StudentController.java @@ -0,0 +1,91 @@ +package controllers; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import model.Student; +import play.libs.Json; +import play.libs.concurrent.HttpExecutionContext; +import play.mvc.Controller; +import play.mvc.Http; +import play.mvc.Result; +import store.StudentStore; +import utils.Util; + +import javax.inject.Inject; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletionStage; + +import static java.util.concurrent.CompletableFuture.supplyAsync; + +public class StudentController extends Controller { + private HttpExecutionContext ec; + private StudentStore studentStore; + + @Inject + public StudentController(HttpExecutionContext ec, StudentStore studentStore) { + this.studentStore = studentStore; + this.ec = ec; + } + + public CompletionStage create(Http.Request request) { + JsonNode json = request.body().asJson(); + return supplyAsync(() -> { + if (json == null) { + return badRequest(Util.createResponse("Expecting Json data", false)); + } + + Optional studentOptional = studentStore.addStudent(Json.fromJson(json, Student.class)); + return studentOptional.map(student -> { + JsonNode jsonObject = Json.toJson(student); + return created(Util.createResponse(jsonObject, true)); + }).orElse(internalServerError(Util.createResponse("Could not create data.", false))); + }, ec.current()); + } + + public CompletionStage listStudents() { + return supplyAsync(() -> { + Set result = studentStore.getAllStudents(); + ObjectMapper mapper = new ObjectMapper(); + JsonNode jsonData = mapper.convertValue(result, JsonNode.class); + return ok(Util.createResponse(jsonData, true)); + }, ec.current()); + } + + public CompletionStage retrieve(int id) { + return supplyAsync(() -> { + final Optional studentOptional = studentStore.getStudent(id); + return studentOptional.map(student -> { + JsonNode jsonObjects = Json.toJson(student); + return ok(Util.createResponse(jsonObjects, true)); + }).orElse(notFound(Util.createResponse("Student with id:" + id + " not found", false))); + }, ec.current()); + } + + public CompletionStage update(Http.Request request) { + JsonNode json = request.body().asJson(); + return supplyAsync(() -> { + if (json == null) { + return badRequest(Util.createResponse("Expecting Json data", false)); + } + Optional studentOptional = studentStore.updateStudent(Json.fromJson(json, Student.class)); + return studentOptional.map(student -> { + if (student == null) { + return notFound(Util.createResponse("Student not found", false)); + } + JsonNode jsonObject = Json.toJson(student); + return ok(Util.createResponse(jsonObject, true)); + }).orElse(internalServerError(Util.createResponse("Could not create data.", false))); + }, ec.current()); + } + + public CompletionStage delete(int id) { + return supplyAsync(() -> { + boolean status = studentStore.deleteStudent(id); + if (!status) { + return notFound(Util.createResponse("Student with id:" + id + " not found", false)); + } + return ok(Util.createResponse("Student with id:" + id + " deleted", true)); + }, ec.current()); + } +} diff --git a/play-framework/introduction/app/models/Student.java b/play-framework/student-api/app/model/Student.java similarity index 84% rename from play-framework/introduction/app/models/Student.java rename to play-framework/student-api/app/model/Student.java index dc539767bd..39cbfe0040 100644 --- a/play-framework/introduction/app/models/Student.java +++ b/play-framework/student-api/app/model/Student.java @@ -1,15 +1,19 @@ -package models; +package model; + public class Student { private String firstName; private String lastName; private int age; private int id; - public Student(){} - public Student(String firstName, String lastName, int age) { - super(); + + public Student() { + } + + public Student(String firstName, String lastName, int age, int id) { this.firstName = firstName; this.lastName = lastName; this.age = age; + this.id = id; } public String getFirstName() { @@ -43,5 +47,4 @@ public class Student { public void setId(int id) { this.id = id; } - } diff --git a/play-framework/student-api/app/store/StudentStore.java b/play-framework/student-api/app/store/StudentStore.java new file mode 100644 index 0000000000..315db5b916 --- /dev/null +++ b/play-framework/student-api/app/store/StudentStore.java @@ -0,0 +1,37 @@ +package store; + +import model.Student; + +import java.util.*; + +public class StudentStore { + private Map students = new HashMap<>(); + + public Optional addStudent(Student student) { + int id = students.size(); + student.setId(id); + students.put(id, student); + return Optional.ofNullable(student); + } + + public Optional getStudent(int id) { + return Optional.ofNullable(students.get(id)); + } + + public Set getAllStudents() { + return new HashSet<>(students.values()); + } + + public Optional updateStudent(Student student) { + int id = student.getId(); + if (students.containsKey(id)) { + students.put(id, student); + return Optional.ofNullable(student); + } + return Optional.empty(); + } + + public boolean deleteStudent(int id) { + return students.remove(id) != null; + } +} diff --git a/play-framework/introduction/app/util/Util.java b/play-framework/student-api/app/utils/Util.java similarity index 60% rename from play-framework/introduction/app/util/Util.java rename to play-framework/student-api/app/utils/Util.java index a853a4cb43..3fb9833ada 100644 --- a/play-framework/introduction/app/util/Util.java +++ b/play-framework/student-api/app/utils/Util.java @@ -1,17 +1,17 @@ -package util; +package utils; -import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import play.libs.Json; public class Util { public static ObjectNode createResponse(Object response, boolean ok) { ObjectNode result = Json.newObject(); - result.put("isSuccessfull", ok); - if (response instanceof String) + result.put("isSuccessful", ok); + if (response instanceof String) { result.put("body", (String) response); - else result.put("body", (JsonNode) response); - + } else { + result.putPOJO("body", response); + } return result; } -} \ No newline at end of file +} diff --git a/play-framework/student-api/build.sbt b/play-framework/student-api/build.sbt new file mode 100644 index 0000000000..13d3fe96cd --- /dev/null +++ b/play-framework/student-api/build.sbt @@ -0,0 +1,10 @@ +name := """student-api""" +organization := "com.baeldung" + +version := "1.0-SNAPSHOT" + +lazy val root = (project in file(".")).enablePlugins(PlayJava) + +scalaVersion := "2.13.0" + +libraryDependencies += guice diff --git a/play-framework/student-api/conf/application.conf b/play-framework/student-api/conf/application.conf new file mode 100644 index 0000000000..85c184dcb1 --- /dev/null +++ b/play-framework/student-api/conf/application.conf @@ -0,0 +1,2 @@ +# This is the main configuration file for the application. +# https://www.playframework.com/documentation/latest/ConfigFile diff --git a/play-framework/student-api/conf/logback.xml b/play-framework/student-api/conf/logback.xml new file mode 100644 index 0000000000..e8c982543f --- /dev/null +++ b/play-framework/student-api/conf/logback.xml @@ -0,0 +1,35 @@ + + + + + + + ${application.home:-.}/logs/application.log + + %date [%level] from %logger in %thread - %message%n%xException + + + + + + %coloredLevel %logger{15} - %message%n%xException{10} + + + + + + + + + + + + + + + + + + + + diff --git a/play-framework/student-api/conf/routes b/play-framework/student-api/conf/routes new file mode 100644 index 0000000000..f89b866953 --- /dev/null +++ b/play-framework/student-api/conf/routes @@ -0,0 +1,12 @@ +# Routes +# This file defines all application routes (Higher priority routes first) +# ~~~~ + +GET / controllers.StudentController.listStudents() +GET /:id controllers.StudentController.retrieve(id:Int) +POST / controllers.StudentController.create(request: Request) +PUT / controllers.StudentController.update(request: Request) +DELETE /:id controllers.StudentController.delete(id:Int) + +# Map static resources from the /public folder to the /assets URL path +GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset) diff --git a/play-framework/student-api/project/build.properties b/play-framework/student-api/project/build.properties new file mode 100644 index 0000000000..c0bab04941 --- /dev/null +++ b/play-framework/student-api/project/build.properties @@ -0,0 +1 @@ +sbt.version=1.2.8 diff --git a/play-framework/student-api/project/plugins.sbt b/play-framework/student-api/project/plugins.sbt new file mode 100644 index 0000000000..1c8c62a0d5 --- /dev/null +++ b/play-framework/student-api/project/plugins.sbt @@ -0,0 +1,7 @@ +// The Play plugin +addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.7.3") + +// Defines scaffolding (found under .g8 folder) +// http://www.foundweekends.org/giter8/scaffolding.html +// sbt "g8Scaffold form" +addSbtPlugin("org.foundweekends.giter8" % "sbt-giter8-scaffold" % "0.11.0") diff --git a/play-framework/student-api/test/ApplicationLiveTest.java b/play-framework/student-api/test/ApplicationLiveTest.java deleted file mode 100644 index beeef1a602..0000000000 --- a/play-framework/student-api/test/ApplicationLiveTest.java +++ /dev/null @@ -1,172 +0,0 @@ - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Arrays; - -import org.json.JSONArray; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import model.Student; -import play.test.*; -import static play.test.Helpers.*; - -public class ApplicationLiveTest{ - private static final String BASE_URL = "http://localhost:9000"; - - @Test -public void testInServer() throws Exception { - TestServer server = testServer(3333); - running(server, () -> { - try { - WSClient ws = play.libs.ws.WS.newClient(3333); - CompletionStage completionStage = ws.url("/").get(); - WSResponse response = completionStage.toCompletableFuture().get(); - ws.close(); - assertEquals(OK, response.getStatus()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - }); -} - @Test - public void whenCreatesRecord_thenCorrect() { - Student student = new Student("jody", "west", 50); - JSONObject obj = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))); - assertTrue(obj.getBoolean("isSuccessfull")); - JSONObject body = obj.getJSONObject("body"); - assertEquals(student.getAge(), body.getInt("age")); - assertEquals(student.getFirstName(), body.getString("firstName")); - assertEquals(student.getLastName(), body.getString("lastName")); - } - - @Test - public void whenDeletesCreatedRecord_thenCorrect() { - Student student = new Student("Usain", "Bolt", 25); - JSONObject ob1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body"); - int id = ob1.getInt("id"); - JSONObject obj1 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject())); - assertTrue(obj1.getBoolean("isSuccessfull")); - makeRequest(BASE_URL + "/" + id, "DELETE", null); - JSONObject obj2 = new JSONObject(makeRequest(BASE_URL + "/" + id, "POST", new JSONObject())); - assertFalse(obj2.getBoolean("isSuccessfull")); - } - - @Test - public void whenUpdatesCreatedRecord_thenCorrect() { - Student student = new Student("john", "doe", 50); - JSONObject body1 = new JSONObject(makeRequest(BASE_URL, "POST", new JSONObject(student))).getJSONObject("body"); - assertEquals(student.getAge(), body1.getInt("age")); - int newAge = 60; - body1.put("age", newAge); - JSONObject body2 = new JSONObject(makeRequest(BASE_URL, "PUT", body1)).getJSONObject("body"); - assertFalse(student.getAge() == body2.getInt("age")); - assertTrue(newAge == body2.getInt("age")); - } - - @Test - public void whenGetsAllRecords_thenCorrect() { - Student student1 = new Student("jane", "daisy", 50); - Student student2 = new Student("john", "daniel", 60); - Student student3 = new Student("don", "mason", 55); - Student student4 = new Student("scarlet", "ohara", 90); - - makeRequest(BASE_URL, "POST", new JSONObject(student1)); - makeRequest(BASE_URL, "POST", new JSONObject(student2)); - makeRequest(BASE_URL, "POST", new JSONObject(student3)); - makeRequest(BASE_URL, "POST", new JSONObject(student4)); - - JSONObject objects = new JSONObject(makeRequest(BASE_URL, "GET", null)); - assertTrue(objects.getBoolean("isSuccessfull")); - JSONArray array = objects.getJSONArray("body"); - assertTrue(array.length() >= 4); - } - - public static String makeRequest(String myUrl, String httpMethod, JSONObject parameters) { - - URL url = null; - try { - url = new URL(myUrl); - } catch (MalformedURLException e) { - e.printStackTrace(); - } - HttpURLConnection conn = null; - try { - - conn = (HttpURLConnection) url.openConnection(); - } catch (IOException e) { - e.printStackTrace(); - } - conn.setDoInput(true); - - conn.setReadTimeout(10000); - - conn.setRequestProperty("Content-Type", "application/json"); - DataOutputStream dos = null; - int respCode = 0; - String inputString = null; - try { - conn.setRequestMethod(httpMethod); - - if (Arrays.asList("POST", "PUT").contains(httpMethod)) { - String params = parameters.toString(); - - conn.setDoOutput(true); - - dos = new DataOutputStream(conn.getOutputStream()); - dos.writeBytes(params); - dos.flush(); - dos.close(); - } - respCode = conn.getResponseCode(); - if (respCode != 200 && respCode != 201) { - String error = inputStreamToString(conn.getErrorStream()); - return error; - } - inputString = inputStreamToString(conn.getInputStream()); - - } catch (IOException e) { - - e.printStackTrace(); - } - return inputString; - } - - public static String inputStreamToString(InputStream is) { - BufferedReader br = null; - StringBuilder sb = new StringBuilder(); - - String line; - try { - - br = new BufferedReader(new InputStreamReader(is)); - while ((line = br.readLine()) != null) { - sb.append(line); - } - - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - return sb.toString(); - - } -} diff --git a/play-framework/student-api/test/controllers/StudentControllerUnitTest.java b/play-framework/student-api/test/controllers/StudentControllerUnitTest.java new file mode 100644 index 0000000000..bf645b72f9 --- /dev/null +++ b/play-framework/student-api/test/controllers/StudentControllerUnitTest.java @@ -0,0 +1,95 @@ +package controllers; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.Test; +import play.Application; +import play.inject.guice.GuiceApplicationBuilder; +import play.libs.Json; +import play.mvc.Http; +import play.mvc.Result; +import play.test.WithApplication; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static play.mvc.Http.Status.OK; +import static play.test.Helpers.*; + +public class StudentControllerUnitTest extends WithApplication { + + @Override + protected Application provideApplication() { + return new GuiceApplicationBuilder().build(); + } + + @Test + public void givenStudentPostData_whenCreatingStudent_ThenShouldReturnCreatedStudent() { + final ObjectNode jsonNode = Json.newObject(); + jsonNode.put("firstName", "John"); + jsonNode.put("lastName", "Baeldung"); + jsonNode.put("age", 25); + + Http.RequestBuilder request = new Http.RequestBuilder() + .method(POST) + .bodyJson(jsonNode) + .uri("/"); + + Result result = route(app, request); + assertEquals(CREATED, result.status()); + assertTrue(result.contentType().isPresent()); + assertEquals("application/json", result.contentType().get()); + } + + @Test + public void givenUrlToListStudents_whenListingStudents_ThenShouldReturnStudentList() { + Http.RequestBuilder request = new Http.RequestBuilder() + .method(GET) + .uri("/"); + + Result result = route(app, request); + assertEquals(OK, result.status()); + assertTrue(result.contentType().isPresent()); + assertEquals("application/json", result.contentType().get()); + } + + @Test + public void givenUrlToRetrieveSingleStudent_whenRetrievingStudent_ThenShouldReturn404NotFound() { + Http.RequestBuilder request = new Http.RequestBuilder() + .method(GET) + .uri("/1"); + + Result result = route(app, request); + assertEquals(NOT_FOUND, result.status()); + assertTrue(result.contentType().isPresent()); + assertEquals("application/json", result.contentType().get()); + } + + @Test + public void givenUrlToUpdateStudent_whenaUpdatingStudent_ThenShouldFail() { + final ObjectNode jsonNode = Json.newObject(); + jsonNode.put("firstName", "John"); + jsonNode.put("lastName", "Baeldung"); + jsonNode.put("age", 25); + + Http.RequestBuilder request = new Http.RequestBuilder() + .method(PUT) + .bodyJson(jsonNode) + .uri("/"); + + Result result = route(app, request); + assertEquals(INTERNAL_SERVER_ERROR, result.status()); + assertTrue(result.contentType().isPresent()); + assertEquals("application/json", result.contentType().get()); + } + + @Test + public void givenIdToDeleteStudent_whenDeletingStudent_ThenShouldFail() { + Http.RequestBuilder request = new Http.RequestBuilder() + .method(DELETE) + .uri("/1"); + + Result result = route(app, request); + assertEquals(NOT_FOUND, result.status()); + assertTrue(result.contentType().isPresent()); + assertEquals("application/json", result.contentType().get()); + } +} diff --git a/pom.xml b/pom.xml index fc3567be51..7f92acef6c 100644 --- a/pom.xml +++ b/pom.xml @@ -350,6 +350,7 @@ apache-fop apache-geode apache-meecrowave + apache-olingo/olingo2 apache-opennlp apache-poi apache-pulsar @@ -369,13 +370,15 @@ axon azure + bazel blade - bootique cas cdi checker-plugin + cloud-foundry-uaa/cf-uaa-oauth2-client + cloud-foundry-uaa/cf-uaa-oauth2-resource-server core-groovy core-groovy-2 core-groovy-collections @@ -392,6 +395,7 @@ core-java-modules/core-java-collections core-java-modules/core-java-collections-list core-java-modules/core-java-collections-list-2 + core-java-modules/core-java-collections-list-3 core-java-modules/core-java-collections-array-list core-java-modules/core-java-collections-set core-java-modules/core-java-concurrency-basic @@ -401,6 +405,7 @@ core-java-modules/core-java-security core-java-modules/core-java-lang-syntax core-java-modules/core-java-lang + core-java-modules/core-java-lang-2 core-java-modules/core-java-lang-oop core-java-modules/core-java-lang-oop-2 core-java-modules @@ -438,6 +443,7 @@ gson guava guava-collections + guava-collections-set guava-modules guice @@ -457,10 +463,12 @@ java-collections-conversions java-collections-maps java-collections-maps-2 + java-jdi java-lite + java-math java-numbers java-numbers-2 java-rmi @@ -480,6 +488,7 @@ jee-7-security + jee-kotlin jersey jgit jgroups @@ -527,6 +536,7 @@ metrics microprofile + ml msf4j mustache @@ -560,9 +570,18 @@ software-security/sql-injection-samples tensorflow-java + spf4j spring-boot-flowable + spring-boot-mvc-2 + spring-boot-performance + spring-boot-properties + spring-security-kerberos oauth2-framework-impl + + spring-boot-nashorn + java-blockchain + @@ -724,6 +743,7 @@ spring-remoting spring-rest spring-rest-angular + spring-rest-compress spring-rest-full spring-rest-hal-browser spring-rest-query-language @@ -797,6 +817,9 @@ tensorflow-java spring-boot-flowable spring-security-kerberos + + spring-boot-nashorn + java-blockchain @@ -908,6 +931,7 @@ spring-remoting/remoting-rmi/remoting-rmi-server spring-rest spring-rest-angular + spring-rest-compress spring-rest-full spring-rest-simple spring-resttemplate @@ -946,6 +970,7 @@ spring-boot-flowable spring-security-kerberos + spring-boot-nashorn @@ -1056,6 +1081,7 @@ apache-fop apache-geode apache-meecrowave + apache-olingo/olingo2 apache-opennlp apache-poi apache-pulsar @@ -1074,12 +1100,14 @@ aws-lambda axon azure - + bazel bootique cas cdi checker-plugin + cloud-foundry-uaa/cf-uaa-oauth2-client + cloud-foundry-uaa/cf-uaa-oauth2-resource-server core-groovy core-groovy-2 core-groovy-collections @@ -1094,6 +1122,7 @@ core-java-modules/core-java-collections core-java-modules/core-java-collections-list core-java-modules/core-java-collections-list-2 + core-java-modules/core-java-collections-list-3 core-java-modules/core-java-collections-array-list core-java-modules/core-java-collections-set core-java-modules/core-java-concurrency-basic @@ -1103,6 +1132,7 @@ core-java-modules/core-java-security core-java-modules/core-java-lang-syntax core-java-modules/core-java-lang + core-java-modules/core-java-lang-2 core-java-modules/core-java-lang-oop core-java-modules/core-java-lang-oop-2 core-java-modules @@ -1137,6 +1167,7 @@ gson guava guava-collections + guava-collections-set guava-modules guice @@ -1156,9 +1187,11 @@ java-collections-conversions java-collections-maps java-collections-maps-2 + java-jdi java-ee-8-security-api java-lite + java-math java-numbers java-numbers-2 java-rmi @@ -1178,6 +1211,7 @@ jee-7-security + jee-kotlin jersey jgit jgroups @@ -1222,6 +1256,7 @@ metrics microprofile + ml msf4j mustache @@ -1252,6 +1287,11 @@ rxjava rxjava-2 oauth2-framework-impl + spf4j + spring-boot-performance + spring-boot-properties + + @@ -1399,6 +1439,7 @@ spring-remoting spring-rest spring-rest-angular + spring-rest-compress spring-rest-full spring-rest-hal-browser spring-rest-query-language diff --git a/quarkus/pom.xml b/quarkus/pom.xml index ceb2e2c0d4..5190d0932a 100644 --- a/quarkus/pom.xml +++ b/quarkus/pom.xml @@ -5,6 +5,8 @@ com.baeldung.quarkus quarkus 1.0-SNAPSHOT + quarkus + 2.22.0 0.15.0 diff --git a/spring-5-data-reactive/pom.xml b/spring-5-data-reactive/pom.xml index 5372803842..296da87529 100644 --- a/spring-5-data-reactive/pom.xml +++ b/spring-5-data-reactive/pom.xml @@ -14,6 +14,14 @@
    + + io.projectreactor + reactor-core + + + org.springframework.boot + spring-boot-starter-data-couchbase-reactive + org.springframework.boot spring-boot-starter-data-mongodb-reactive @@ -105,6 +113,12 @@ httpclient ${httpclient.version} + + com.couchbase.mock + CouchbaseMock + ${couchbaseMock.version} + test + @@ -224,6 +238,7 @@ 0.8.0.M8 4.5.2 1.4.199 + 1.5.23 diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/ReactiveCouchbaseApplication.java b/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/ReactiveCouchbaseApplication.java new file mode 100644 index 0000000000..917bcfdaa8 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/ReactiveCouchbaseApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.couchbase; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ReactiveCouchbaseApplication { + + public static void main(String[] args) { + SpringApplication.run(ReactiveCouchbaseApplication.class, args); + } +} diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/configuration/CouchbaseProperties.java b/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/configuration/CouchbaseProperties.java new file mode 100644 index 0000000000..480c96e986 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/configuration/CouchbaseProperties.java @@ -0,0 +1,40 @@ +package com.baeldung.couchbase.configuration; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; + +import java.util.Collections; +import java.util.List; + +@Configuration +public class CouchbaseProperties { + + private final List bootstrapHosts; + private final String bucketName; + private final String bucketPassword; + private final int port; + + public CouchbaseProperties(@Value("${spring.couchbase.bootstrap-hosts}") final List bootstrapHosts, @Value("${spring.couchbase.bucket.name}") final String bucketName, @Value("${spring.couchbase.bucket.password}") final String bucketPassword, + @Value("${spring.couchbase.port}") final int port) { + this.bootstrapHosts = Collections.unmodifiableList(bootstrapHosts); + this.bucketName = bucketName; + this.bucketPassword = bucketPassword; + this.port = port; + } + + public List getBootstrapHosts() { + return bootstrapHosts; + } + + public String getBucketName() { + return bucketName; + } + + public String getBucketPassword() { + return bucketPassword; + } + + public int getPort() { + return port; + } +} diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/configuration/N1QLReactiveCouchbaseConfiguration.java b/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/configuration/N1QLReactiveCouchbaseConfiguration.java new file mode 100644 index 0000000000..059bd36cae --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/configuration/N1QLReactiveCouchbaseConfiguration.java @@ -0,0 +1,15 @@ +package com.baeldung.couchbase.configuration; + +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.data.couchbase.repository.config.EnableReactiveCouchbaseRepositories; + +@Configuration +@EnableReactiveCouchbaseRepositories("com.baeldung.couchbase.domain.repository.n1ql") +@Primary +public class N1QLReactiveCouchbaseConfiguration extends ReactiveCouchbaseConfiguration { + + public N1QLReactiveCouchbaseConfiguration(CouchbaseProperties couchbaseProperties) { + super(couchbaseProperties); + } +} diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/configuration/ReactiveCouchbaseConfiguration.java b/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/configuration/ReactiveCouchbaseConfiguration.java new file mode 100644 index 0000000000..2f3b5486d8 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/configuration/ReactiveCouchbaseConfiguration.java @@ -0,0 +1,39 @@ +package com.baeldung.couchbase.configuration; + +import com.couchbase.client.java.env.CouchbaseEnvironment; +import com.couchbase.client.java.env.DefaultCouchbaseEnvironment; +import org.springframework.data.couchbase.config.AbstractReactiveCouchbaseConfiguration; + +import java.util.List; + +public abstract class ReactiveCouchbaseConfiguration extends AbstractReactiveCouchbaseConfiguration { + + private CouchbaseProperties couchbaseProperties; + + public ReactiveCouchbaseConfiguration(final CouchbaseProperties couchbaseProperties) { + this.couchbaseProperties = couchbaseProperties; + } + + @Override + protected List getBootstrapHosts() { + return couchbaseProperties.getBootstrapHosts(); + } + + @Override + protected String getBucketName() { + return couchbaseProperties.getBucketName(); + } + + @Override + protected String getBucketPassword() { + return couchbaseProperties.getBucketPassword(); + } + + @Override + public CouchbaseEnvironment couchbaseEnvironment() { + return DefaultCouchbaseEnvironment + .builder() + .bootstrapHttpDirectPort(couchbaseProperties.getPort()) + .build(); + } +} diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/configuration/ViewReactiveCouchbaseConfiguration.java b/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/configuration/ViewReactiveCouchbaseConfiguration.java new file mode 100644 index 0000000000..9b4d9b0319 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/configuration/ViewReactiveCouchbaseConfiguration.java @@ -0,0 +1,13 @@ +package com.baeldung.couchbase.configuration; + +import org.springframework.context.annotation.Configuration; +import org.springframework.data.couchbase.repository.config.EnableReactiveCouchbaseRepositories; + +@Configuration +@EnableReactiveCouchbaseRepositories("com.baeldung.couchbase.domain.repository.view") +public class ViewReactiveCouchbaseConfiguration extends ReactiveCouchbaseConfiguration { + + public ViewReactiveCouchbaseConfiguration(CouchbaseProperties couchbaseProperties) { + super(couchbaseProperties); + } +} diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/domain/Person.java b/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/domain/Person.java new file mode 100644 index 0000000000..285de34df8 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/domain/Person.java @@ -0,0 +1,43 @@ +package com.baeldung.couchbase.domain; + +import org.springframework.data.annotation.Id; +import org.springframework.data.couchbase.core.mapping.Document; + +import java.util.Objects; +import java.util.UUID; + +@Document +public class Person { + + @Id private UUID id; + private String firstName; + + public Person(final UUID id, final String firstName) { + this.id = id; + this.firstName = firstName; + } + + private Person() { + } + + public UUID getId() { + return id; + } + + public String getFirstName() { + return firstName; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Person person = (Person) o; + return Objects.equals(id, person.id) && Objects.equals(firstName, person.firstName); + } + + @Override + public int hashCode() { + return Objects.hash(id, firstName); + } +} diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLPersonRepository.java b/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLPersonRepository.java new file mode 100644 index 0000000000..6f73a77ceb --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLPersonRepository.java @@ -0,0 +1,16 @@ +package com.baeldung.couchbase.domain.repository.n1ql; + +import com.baeldung.couchbase.domain.Person; +import org.springframework.data.couchbase.core.query.N1qlPrimaryIndexed; +import org.springframework.data.repository.reactive.ReactiveCrudRepository; +import org.springframework.stereotype.Repository; +import reactor.core.publisher.Flux; + +import java.util.UUID; + +@Repository +@N1qlPrimaryIndexed +public interface N1QLPersonRepository extends ReactiveCrudRepository { + + Flux findAllByFirstName(final String firstName); +} diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLSortingPersonRepository.java b/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLSortingPersonRepository.java new file mode 100644 index 0000000000..57dd149425 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLSortingPersonRepository.java @@ -0,0 +1,13 @@ +package com.baeldung.couchbase.domain.repository.n1ql; + +import com.baeldung.couchbase.domain.Person; +import org.springframework.data.couchbase.core.query.N1qlPrimaryIndexed; +import org.springframework.data.repository.reactive.ReactiveSortingRepository; +import org.springframework.stereotype.Repository; + +import java.util.UUID; + +@Repository +@N1qlPrimaryIndexed +public interface N1QLSortingPersonRepository extends ReactiveSortingRepository { +} diff --git a/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/domain/repository/view/ViewPersonRepository.java b/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/domain/repository/view/ViewPersonRepository.java new file mode 100644 index 0000000000..28a7ec1b78 --- /dev/null +++ b/spring-5-data-reactive/src/main/java/com/baeldung/couchbase/domain/repository/view/ViewPersonRepository.java @@ -0,0 +1,20 @@ +package com.baeldung.couchbase.domain.repository.view; + +import com.baeldung.couchbase.domain.Person; +import org.springframework.data.couchbase.core.query.View; +import org.springframework.data.couchbase.core.query.ViewIndexed; +import org.springframework.data.repository.reactive.ReactiveCrudRepository; +import org.springframework.stereotype.Repository; +import reactor.core.publisher.Flux; + +import java.util.UUID; + +@Repository +@ViewIndexed(designDoc = ViewPersonRepository.DESIGN_DOCUMENT) +public interface ViewPersonRepository extends ReactiveCrudRepository { + + String DESIGN_DOCUMENT = "persons"; + + @View(designDocument = ViewPersonRepository.DESIGN_DOCUMENT) + Flux findByFirstName(String firstName); +} diff --git a/spring-5-data-reactive/src/test/java/com/baeldung/couchbase/domain/repository/CouchbaseMockConfiguration.java b/spring-5-data-reactive/src/test/java/com/baeldung/couchbase/domain/repository/CouchbaseMockConfiguration.java new file mode 100644 index 0000000000..2a09fce4b0 --- /dev/null +++ b/spring-5-data-reactive/src/test/java/com/baeldung/couchbase/domain/repository/CouchbaseMockConfiguration.java @@ -0,0 +1,54 @@ +package com.baeldung.couchbase.domain.repository; + +import com.baeldung.couchbase.configuration.CouchbaseProperties; +import com.couchbase.mock.Bucket; +import com.couchbase.mock.BucketConfiguration; +import com.couchbase.mock.CouchbaseMock; +import org.springframework.boot.test.context.TestConfiguration; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Collections; + +@TestConfiguration +public class CouchbaseMockConfiguration { + + private CouchbaseMock couchbaseMock; + + public CouchbaseMockConfiguration(final CouchbaseProperties couchbaseProperties) { + final BucketConfiguration bucketConfiguration = new BucketConfiguration(); + bucketConfiguration.numNodes = 1; + bucketConfiguration.numReplicas = 1; + bucketConfiguration.numVBuckets = 1024; + bucketConfiguration.name = couchbaseProperties.getBucketName(); + bucketConfiguration.type = Bucket.BucketType.COUCHBASE; + bucketConfiguration.password = couchbaseProperties.getBucketPassword(); + + try { + couchbaseMock = new CouchbaseMock(couchbaseProperties.getPort(), Collections.singletonList(bucketConfiguration)); + } catch (final IOException ex) { + throw new UncheckedIOException(ex); + } + } + + @PostConstruct + public void postConstruct() { + try { + couchbaseMock.start(); + } catch (final IOException ex) { + throw new UncheckedIOException(ex); + } + try { + couchbaseMock.waitForStartup(); + } catch (final InterruptedException ex) { + throw new RuntimeException(ex); + } + } + + @PreDestroy + public void preDestroy() { + couchbaseMock.stop(); + } +} diff --git a/spring-5-data-reactive/src/test/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLPersonRepositoryLiveTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLPersonRepositoryLiveTest.java new file mode 100644 index 0000000000..0c1b6bde6c --- /dev/null +++ b/spring-5-data-reactive/src/test/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLPersonRepositoryLiveTest.java @@ -0,0 +1,55 @@ +package com.baeldung.couchbase.domain.repository.n1ql; + +import com.baeldung.couchbase.domain.Person; +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.test.StepVerifier; + +import java.util.UUID; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class N1QLPersonRepositoryLiveTest { + + @Autowired private N1QLPersonRepository personRepository; + + @Test + public void shouldFindAll_byLastName() { + //Given + final String firstName = "John"; + final Person matchingPerson = new Person(UUID.randomUUID(), firstName); + final Person nonMatchingPerson = new Person(UUID.randomUUID(), "NotJohn"); + wrap(() -> { + personRepository + .save(matchingPerson) + .subscribe(); + personRepository + .save(nonMatchingPerson) + .subscribe(); + //When + final Flux allByFirstName = personRepository.findAllByFirstName(firstName); + //Then + StepVerifier + .create(allByFirstName) + .expectNext(matchingPerson) + .verifyComplete(); + + }, matchingPerson, nonMatchingPerson); + } + + private void wrap(final Runnable runnable, final Person... people) { + try { + runnable.run(); + } finally { + for (final Person person : people) { + personRepository + .delete(person) + .subscribe(); + } + } + } +} \ No newline at end of file diff --git a/spring-5-data-reactive/src/test/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLSortingPersonRepositoryLiveTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLSortingPersonRepositoryLiveTest.java new file mode 100644 index 0000000000..4ba2206e0a --- /dev/null +++ b/spring-5-data-reactive/src/test/java/com/baeldung/couchbase/domain/repository/n1ql/N1QLSortingPersonRepositoryLiveTest.java @@ -0,0 +1,60 @@ +package com.baeldung.couchbase.domain.repository.n1ql; + +import com.baeldung.couchbase.domain.Person; +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.Sort; +import org.springframework.test.context.junit4.SpringRunner; +import reactor.core.publisher.Flux; +import reactor.test.StepVerifier; + +import java.util.UUID; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class N1QLSortingPersonRepositoryLiveTest { + + @Autowired private N1QLSortingPersonRepository personRepository; + + @Test + public void shouldFindAll_sortedByFirstName() { + //Given + final Person firstPerson = new Person(UUID.randomUUID(), "John"); + final Person secondPerson = new Person(UUID.randomUUID(), "Mikki"); + wrap(() -> { + personRepository + .save(firstPerson) + .subscribe(); + personRepository + .save(secondPerson) + .subscribe(); + //When + final Flux allByFirstName = personRepository.findAll(Sort.by(Sort.Direction.DESC, "firstName")); + //Then + StepVerifier + .create(allByFirstName) + .expectNextMatches(person -> person + .getFirstName() + .equals(secondPerson.getFirstName())) + .expectNextMatches(person -> person + .getFirstName() + .equals(firstPerson.getFirstName())) + .verifyComplete(); + }, firstPerson, secondPerson); + } + + //workaround for deleteAll() + private void wrap(final Runnable runnable, final Person... people) { + try { + runnable.run(); + } finally { + for (final Person person : people) { + personRepository + .delete(person) + .subscribe(); + } + } + } +} \ No newline at end of file diff --git a/spring-5-data-reactive/src/test/java/com/baeldung/couchbase/domain/repository/view/ViewPersonRepositoryIntegrationTest.java b/spring-5-data-reactive/src/test/java/com/baeldung/couchbase/domain/repository/view/ViewPersonRepositoryIntegrationTest.java new file mode 100644 index 0000000000..712e7b0d37 --- /dev/null +++ b/spring-5-data-reactive/src/test/java/com/baeldung/couchbase/domain/repository/view/ViewPersonRepositoryIntegrationTest.java @@ -0,0 +1,79 @@ +package com.baeldung.couchbase.domain.repository.view; + +import com.baeldung.couchbase.configuration.CouchbaseProperties; +import com.baeldung.couchbase.configuration.ViewReactiveCouchbaseConfiguration; +import com.baeldung.couchbase.domain.Person; +import com.baeldung.couchbase.domain.repository.CouchbaseMockConfiguration; +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 java.util.UUID; + +@RunWith(SpringRunner.class) +@SpringBootTest(properties = { "spring.couchbase.port=10010" }, classes = { ViewReactiveCouchbaseConfiguration.class, CouchbaseProperties.class, CouchbaseMockConfiguration.class }) +public class ViewPersonRepositoryIntegrationTest { + + @Autowired private ViewPersonRepository personRepository; + + @Test + public void shouldSavePerson_findById_thenDeleteIt() { + //Given + final UUID id = UUID.randomUUID(); + final Person person = new Person(id, "John"); + wrap(() -> { + personRepository + .save(person) + .subscribe(); + //When + final Mono byId = personRepository.findById(id); + //Then + StepVerifier + .create(byId) + .expectNextMatches(result -> result + .getId() + .equals(id)) + .expectComplete() + .verify(); + }, person); + } + + @Test + public void shouldFindAll_thenDeleteIt() { + //Given + final Person person = new Person(UUID.randomUUID(), "John"); + final Person secondPerson = new Person(UUID.randomUUID(), "Mikki"); + wrap(() -> { + personRepository + .save(person) + .subscribe(); + personRepository + .save(secondPerson) + .subscribe(); + //When + final Flux all = personRepository.findAll(); + //Then + StepVerifier + .create(all) + .expectNextCount(2) + .verifyComplete(); + }, person, secondPerson); + } + + private void wrap(final Runnable runnable, final Person... people) { + try { + runnable.run(); + } finally { + for (final Person person : people) { + personRepository + .delete(person) + .subscribe(); + } + } + } +} \ No newline at end of file diff --git a/spring-5-mvc/pom.xml b/spring-5-mvc/pom.xml index 9569d52abf..be21db481a 100644 --- a/spring-5-mvc/pom.xml +++ b/spring-5-mvc/pom.xml @@ -86,6 +86,11 @@ javafaker 0.18 + + org.apache.httpcomponents + httpclient + ${httpclient.version} + @@ -167,5 +172,6 @@ 2.9.0 1.1.2 com.baeldung.Spring5Application + 4.5.8 diff --git a/spring-5-reactive-client/pom.xml b/spring-5-reactive-client/pom.xml index 1b71815eb4..70771f6832 100644 --- a/spring-5-reactive-client/pom.xml +++ b/spring-5-reactive-client/pom.xml @@ -56,7 +56,6 @@ - org.springframework.boot spring-boot-devtools @@ -89,6 +88,14 @@ org.projectlombok lombok + + + + org.eclipse.jetty + jetty-reactive-httpclient + ${jetty-reactive-httpclient.version} + test + @@ -110,6 +117,7 @@ 1.0 1.0 4.1 + 1.0.3 diff --git a/spring-5-reactive-client/src/test/java/com/baeldung/reactive/logging/WebClientLoggingIntegrationTest.java b/spring-5-reactive-client/src/test/java/com/baeldung/reactive/logging/WebClientLoggingIntegrationTest.java new file mode 100644 index 0000000000..95c63f267f --- /dev/null +++ b/spring-5-reactive-client/src/test/java/com/baeldung/reactive/logging/WebClientLoggingIntegrationTest.java @@ -0,0 +1,154 @@ +package com.baeldung.reactive.logging; + +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.Appender; +import com.baeldung.reactive.logging.filters.LogFilters; +import com.baeldung.reactive.logging.netty.CustomLogger; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.net.URI; +import lombok.AllArgsConstructor; +import lombok.Data; +import org.eclipse.jetty.client.api.Request; +import org.eclipse.jetty.util.ssl.SslContextFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.http.client.reactive.JettyClientHttpConnector; +import org.springframework.http.client.reactive.ReactorClientHttpConnector; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.netty.channel.BootstrapHandlers; +import reactor.netty.http.client.HttpClient; + +import static com.baeldung.reactive.logging.jetty.RequestLogEnhancer.enhance; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + + +public class WebClientLoggingIntegrationTest { + + @AllArgsConstructor + @Data + class Post { + private String title; + private String body; + private int userId; + } + + private Appender jettyAppender; + private Appender nettyAppender; + private Appender mockAppender; + private String sampleUrl = "https://jsonplaceholder.typicode.com/posts"; + + private Post post; + private String sampleResponseBody; + + @BeforeEach + private void setup() throws Exception { + + post = new Post("Learn WebClient logging with Baeldung!", "", 1); + sampleResponseBody = new ObjectMapper().writeValueAsString(post); + + ch.qos.logback.classic.Logger jetty = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.reactive.logging.jetty"); + jettyAppender = mock(Appender.class); + when(jettyAppender.getName()).thenReturn("com.baeldung.reactive.logging.jetty"); + jetty.addAppender(jettyAppender); + + ch.qos.logback.classic.Logger netty = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("reactor.netty.http.client"); + nettyAppender = mock(Appender.class); + when(nettyAppender.getName()).thenReturn("reactor.netty.http.client"); + netty.addAppender(nettyAppender); + + ch.qos.logback.classic.Logger test = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("com.baeldung.reactive"); + mockAppender = mock(Appender.class); + when(mockAppender.getName()).thenReturn("com.baeldung.reactive"); + test.addAppender(mockAppender); + + } + + @Test + public void givenJettyHttpClient_whenEndpointIsConsumed_thenRequestAndResponseBodyLogged() { + SslContextFactory.Client sslContextFactory = new SslContextFactory.Client(); + org.eclipse.jetty.client.HttpClient httpClient = new org.eclipse.jetty.client.HttpClient(sslContextFactory) { + @Override + public Request newRequest(URI uri) { + Request request = super.newRequest(uri); + return enhance(request); + } + }; + + WebClient + .builder() + .clientConnector(new JettyClientHttpConnector(httpClient)) + .build() + .post() + .uri(sampleUrl) + .body(BodyInserters.fromObject(post)) + .retrieve() + .bodyToMono(String.class) + .block(); + + verify(jettyAppender).doAppend(argThat(argument -> (((LoggingEvent) argument).getFormattedMessage()).contains(sampleResponseBody))); + } + + @Test + public void givenNettyHttpClientWithWiretap_whenEndpointIsConsumed_thenRequestAndResponseBodyLogged() { + + reactor.netty.http.client.HttpClient httpClient = HttpClient + .create() + .wiretap(true); + WebClient + .builder() + .clientConnector(new ReactorClientHttpConnector(httpClient)) + .build() + .post() + .uri(sampleUrl) + .body(BodyInserters.fromObject(post)) + .exchange() + .block(); + + verify(nettyAppender).doAppend(argThat(argument -> (((LoggingEvent) argument).getFormattedMessage()).contains("00000300"))); + } + + @Test + public void givenNettyHttpClientWithCustomLogger_whenEndpointIsConsumed_thenRequestAndResponseBodyLogged() { + + reactor.netty.http.client.HttpClient httpClient = HttpClient + .create() + .tcpConfiguration( + tc -> tc.bootstrap( + b -> BootstrapHandlers.updateLogSupport(b, new CustomLogger(HttpClient.class)))); + WebClient + .builder() + .clientConnector(new ReactorClientHttpConnector(httpClient)) + .build() + .post() + .uri(sampleUrl) + .body(BodyInserters.fromObject(post)) + .exchange() + .block(); + + verify(nettyAppender).doAppend(argThat(argument -> (((LoggingEvent) argument).getFormattedMessage()).contains(sampleResponseBody))); + } + + @Test + public void givenDefaultHttpClientWithFilter_whenEndpointIsConsumed_thenRequestAndResponseLogged() { + WebClient + .builder() + .filters(exchangeFilterFunctions -> { + exchangeFilterFunctions.addAll(LogFilters.prepareFilters()); + }) + .build() + .post() + .uri(sampleUrl) + .body(BodyInserters.fromObject(post)) + .exchange() + .block(); + + verify(mockAppender).doAppend(argThat(argument -> (((LoggingEvent) argument).getFormattedMessage()).contains("domain=.typicode.com;"))); + } + + +} diff --git a/spring-5-reactive-client/src/test/java/com/baeldung/reactive/logging/filters/LogFilters.java b/spring-5-reactive-client/src/test/java/com/baeldung/reactive/logging/filters/LogFilters.java new file mode 100644 index 0000000000..c1c3d3e895 --- /dev/null +++ b/spring-5-reactive-client/src/test/java/com/baeldung/reactive/logging/filters/LogFilters.java @@ -0,0 +1,54 @@ +package com.baeldung.reactive.logging.filters; + +import java.util.Arrays; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.reactive.function.client.ExchangeFilterFunction; +import reactor.core.publisher.Mono; + +@Slf4j +public class LogFilters { + public static List prepareFilters() { + return Arrays.asList(logRequest(), logResponse()); + } + + private static ExchangeFilterFunction logRequest() { + return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> { + if (log.isDebugEnabled()) { + StringBuilder sb = new StringBuilder("Request: \n") + .append(clientRequest.method()) + .append(" ") + .append(clientRequest.url()); + clientRequest + .headers() + .forEach((name, values) -> values.forEach(value -> sb + .append("\n") + .append(name) + .append(":") + .append(value))); + log.debug(sb.toString()); + } + return Mono.just(clientRequest); + }); + } + + private static ExchangeFilterFunction logResponse() { + return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> { + if (log.isDebugEnabled()) { + StringBuilder sb = new StringBuilder("Response: \n") + .append("Status: ") + .append(clientResponse.rawStatusCode()); + clientResponse + .headers() + .asHttpHeaders() + .forEach((key, value1) -> value1.forEach(value -> sb + .append("\n") + .append(key) + .append(":") + .append(value))); + log.debug(sb.toString()); + } + return Mono.just(clientResponse); + }); + } +} diff --git a/spring-5-reactive-client/src/test/java/com/baeldung/reactive/logging/jetty/RequestLogEnhancer.java b/spring-5-reactive-client/src/test/java/com/baeldung/reactive/logging/jetty/RequestLogEnhancer.java new file mode 100644 index 0000000000..43e3660743 --- /dev/null +++ b/spring-5-reactive-client/src/test/java/com/baeldung/reactive/logging/jetty/RequestLogEnhancer.java @@ -0,0 +1,93 @@ +package com.baeldung.reactive.logging.jetty; + +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Locale; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.jetty.client.api.Request; +import org.eclipse.jetty.http.HttpField; +import org.eclipse.jetty.http.HttpFields; +import org.eclipse.jetty.http.HttpHeader; + +@Slf4j +public class RequestLogEnhancer { + + public static Request enhance(Request request) { + StringBuilder group = new StringBuilder(); + request.onRequestBegin(theRequest -> group + .append("Request ") + .append(theRequest.getMethod()) + .append(" ") + .append(theRequest.getURI()) + .append("\n")); + request.onRequestHeaders(theRequest -> { + for (HttpField header : theRequest.getHeaders()) + group + .append(header) + .append("\n"); + }); + request.onRequestContent((theRequest, content) -> { + group.append(toString(content, getCharset(theRequest.getHeaders()))); + }); + request.onRequestSuccess(theRequest -> { + log.debug(group.toString()); + group.delete(0, group.length()); + }); + group.append("\n"); + request.onResponseBegin(theResponse -> { + group + .append("Response \n") + .append(theResponse.getVersion()) + .append(" ") + .append(theResponse.getStatus()); + if (theResponse.getReason() != null) { + group + .append(" ") + .append(theResponse.getReason()); + } + group.append("\n"); + }); + request.onResponseHeaders(theResponse -> { + for (HttpField header : theResponse.getHeaders()) + group + .append(header) + .append("\n"); + }); + request.onResponseContent((theResponse, content) -> { + group.append(toString(content, getCharset(theResponse.getHeaders()))); + }); + request.onResponseSuccess(theResponse -> { + log.debug(group.toString()); + }); + return request; + } + + private static String toString(ByteBuffer buffer, Charset charset) { + byte[] bytes; + if (buffer.hasArray()) { + bytes = new byte[buffer.capacity()]; + System.arraycopy(buffer.array(), 0, bytes, 0, buffer.capacity()); + } else { + bytes = new byte[buffer.remaining()]; + buffer.get(bytes, 0, bytes.length); + } + return new String(bytes, charset); + } + + private static Charset getCharset(HttpFields headers) { + String contentType = headers.get(HttpHeader.CONTENT_TYPE); + if (contentType != null) { + String[] tokens = contentType + .toLowerCase(Locale.US) + .split("charset="); + if (tokens.length == 2) { + String encoding = tokens[1].replaceAll("[;\"]", ""); + return Charset.forName(encoding); + } + } + return StandardCharsets.UTF_8; + } + +} + diff --git a/spring-5-reactive-client/src/test/java/com/baeldung/reactive/logging/netty/CustomLogger.java b/spring-5-reactive-client/src/test/java/com/baeldung/reactive/logging/netty/CustomLogger.java new file mode 100644 index 0000000000..9f2a4d127f --- /dev/null +++ b/spring-5-reactive-client/src/test/java/com/baeldung/reactive/logging/netty/CustomLogger.java @@ -0,0 +1,42 @@ +package com.baeldung.reactive.logging.netty; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.logging.LoggingHandler; +import java.nio.charset.Charset; + +import static io.netty.util.internal.PlatformDependent.allocateUninitializedArray; +import static java.lang.Math.max; +import static java.nio.charset.Charset.defaultCharset; + +public class CustomLogger extends LoggingHandler { + public CustomLogger(Class clazz) { + super(clazz); + } + + @Override + protected String format(ChannelHandlerContext ctx, String event, Object arg) { + if (arg instanceof ByteBuf) { + ByteBuf msg = (ByteBuf) arg; + return decode(msg, msg.readerIndex(), msg.readableBytes(), defaultCharset()); + } + return super.format(ctx, event, arg); + } + + private String decode(ByteBuf src, int readerIndex, int len, Charset charset) { + if (len != 0) { + byte[] array; + int offset; + if (src.hasArray()) { + array = src.array(); + offset = src.arrayOffset() + readerIndex; + } else { + array = allocateUninitializedArray(max(len, 1024)); + offset = 0; + src.getBytes(readerIndex, array, 0, len); + } + return new String(array, offset, len, charset); + } + return ""; + } +} diff --git a/spring-5-reactive-client/src/test/resources/logback-test.xml b/spring-5-reactive-client/src/test/resources/logback-test.xml index 7072369b8d..42cb0865c5 100644 --- a/spring-5-reactive-client/src/test/resources/logback-test.xml +++ b/spring-5-reactive-client/src/test/resources/logback-test.xml @@ -6,11 +6,15 @@ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - + + + + + - + \ No newline at end of file diff --git a/spring-all/src/main/java/org/baeldung/sample/App.java b/spring-all/src/main/java/org/baeldung/autowire/sample/App.java similarity index 90% rename from spring-all/src/main/java/org/baeldung/sample/App.java rename to spring-all/src/main/java/org/baeldung/autowire/sample/App.java index 17fc49fc8c..ed0c90d5b1 100644 --- a/spring-all/src/main/java/org/baeldung/sample/App.java +++ b/spring-all/src/main/java/org/baeldung/autowire/sample/App.java @@ -1,4 +1,4 @@ -package org.baeldung.sample; +package org.baeldung.autowire.sample; import org.springframework.context.annotation.AnnotationConfigApplicationContext; diff --git a/spring-all/src/main/java/org/baeldung/sample/AppConfig.java b/spring-all/src/main/java/org/baeldung/autowire/sample/AppConfig.java similarity index 66% rename from spring-all/src/main/java/org/baeldung/sample/AppConfig.java rename to spring-all/src/main/java/org/baeldung/autowire/sample/AppConfig.java index 8a177d2611..117dfe1027 100644 --- a/spring-all/src/main/java/org/baeldung/sample/AppConfig.java +++ b/spring-all/src/main/java/org/baeldung/autowire/sample/AppConfig.java @@ -1,10 +1,10 @@ -package org.baeldung.sample; +package org.baeldung.autowire.sample; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration -@ComponentScan("org.baeldung.sample") +@ComponentScan("org.baeldung.autowire.sample") public class AppConfig { } diff --git a/spring-all/src/main/java/org/baeldung/sample/BarFormatter.java b/spring-all/src/main/java/org/baeldung/autowire/sample/BarFormatter.java similarity index 83% rename from spring-all/src/main/java/org/baeldung/sample/BarFormatter.java rename to spring-all/src/main/java/org/baeldung/autowire/sample/BarFormatter.java index 8396653970..f7e730fdc6 100644 --- a/spring-all/src/main/java/org/baeldung/sample/BarFormatter.java +++ b/spring-all/src/main/java/org/baeldung/autowire/sample/BarFormatter.java @@ -1,4 +1,4 @@ -package org.baeldung.sample; +package org.baeldung.autowire.sample; import org.springframework.stereotype.Component; diff --git a/spring-all/src/main/java/org/baeldung/autowire/sample/FooDAO.java b/spring-all/src/main/java/org/baeldung/autowire/sample/FooDAO.java new file mode 100644 index 0000000000..3d3deaa077 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/autowire/sample/FooDAO.java @@ -0,0 +1,5 @@ +package org.baeldung.autowire.sample; + +public class FooDAO { + +} diff --git a/spring-all/src/main/java/org/baeldung/sample/FooFormatter.java b/spring-all/src/main/java/org/baeldung/autowire/sample/FooFormatter.java similarity index 83% rename from spring-all/src/main/java/org/baeldung/sample/FooFormatter.java rename to spring-all/src/main/java/org/baeldung/autowire/sample/FooFormatter.java index 68cb7f81f2..5fdacbadd4 100644 --- a/spring-all/src/main/java/org/baeldung/sample/FooFormatter.java +++ b/spring-all/src/main/java/org/baeldung/autowire/sample/FooFormatter.java @@ -1,4 +1,4 @@ -package org.baeldung.sample; +package org.baeldung.autowire.sample; import org.springframework.stereotype.Component; diff --git a/spring-all/src/main/java/org/baeldung/sample/FooService.java b/spring-all/src/main/java/org/baeldung/autowire/sample/FooService.java similarity index 88% rename from spring-all/src/main/java/org/baeldung/sample/FooService.java rename to spring-all/src/main/java/org/baeldung/autowire/sample/FooService.java index 711711f205..a3638960cc 100644 --- a/spring-all/src/main/java/org/baeldung/sample/FooService.java +++ b/spring-all/src/main/java/org/baeldung/autowire/sample/FooService.java @@ -1,4 +1,4 @@ -package org.baeldung.sample; +package org.baeldung.autowire.sample; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; diff --git a/spring-all/src/main/java/org/baeldung/sample/Formatter.java b/spring-all/src/main/java/org/baeldung/autowire/sample/Formatter.java similarity index 59% rename from spring-all/src/main/java/org/baeldung/sample/Formatter.java rename to spring-all/src/main/java/org/baeldung/autowire/sample/Formatter.java index ab29c2b848..05cd5f1c26 100644 --- a/spring-all/src/main/java/org/baeldung/sample/Formatter.java +++ b/spring-all/src/main/java/org/baeldung/autowire/sample/Formatter.java @@ -1,4 +1,4 @@ -package org.baeldung.sample; +package org.baeldung.autowire.sample; public interface Formatter { diff --git a/spring-all/src/main/java/org/baeldung/sample/FormatterType.java b/spring-all/src/main/java/org/baeldung/autowire/sample/FormatterType.java similarity index 91% rename from spring-all/src/main/java/org/baeldung/sample/FormatterType.java rename to spring-all/src/main/java/org/baeldung/autowire/sample/FormatterType.java index d4d82dd022..ea1eec055a 100644 --- a/spring-all/src/main/java/org/baeldung/sample/FormatterType.java +++ b/spring-all/src/main/java/org/baeldung/autowire/sample/FormatterType.java @@ -1,4 +1,4 @@ -package org.baeldung.sample; +package org.baeldung.autowire.sample; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/spring-all/src/main/java/org/baeldung/startup/ProfileManager.java b/spring-all/src/main/java/org/baeldung/profiles/ProfileManager.java similarity index 93% rename from spring-all/src/main/java/org/baeldung/startup/ProfileManager.java rename to spring-all/src/main/java/org/baeldung/profiles/ProfileManager.java index 41db539265..b4cb10e690 100644 --- a/spring-all/src/main/java/org/baeldung/startup/ProfileManager.java +++ b/spring-all/src/main/java/org/baeldung/profiles/ProfileManager.java @@ -1,4 +1,4 @@ -package org.baeldung.startup; +package org.baeldung.profiles; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; diff --git a/spring-all/src/main/java/org/baeldung/sample/FooDAO.java b/spring-all/src/main/java/org/baeldung/sample/FooDAO.java deleted file mode 100644 index 151c0c38de..0000000000 --- a/spring-all/src/main/java/org/baeldung/sample/FooDAO.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.sample; - -public class FooDAO { - -} diff --git a/spring-all/src/test/java/org/baeldung/sample/FooServiceIntegrationTest.java b/spring-all/src/test/java/org/baeldung/autowire/sample/FooServiceIntegrationTest.java similarity index 94% rename from spring-all/src/test/java/org/baeldung/sample/FooServiceIntegrationTest.java rename to spring-all/src/test/java/org/baeldung/autowire/sample/FooServiceIntegrationTest.java index 6b518395a1..941fc4baff 100644 --- a/spring-all/src/test/java/org/baeldung/sample/FooServiceIntegrationTest.java +++ b/spring-all/src/test/java/org/baeldung/autowire/sample/FooServiceIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.sample; +package org.baeldung.autowire.sample; import org.junit.Assert; import org.junit.Test; diff --git a/spring-boot-di/pom.xml b/spring-boot-di/pom.xml index ec40c04566..b07d7c6385 100644 --- a/spring-boot-di/pom.xml +++ b/spring-boot-di/pom.xml @@ -3,8 +3,8 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - spring-boot-mvc - spring-boot-mvc + spring-boot-di + spring-boot-di jar Module For Spring Boot DI diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomResponseController.java b/spring-boot-mvc/src/main/java/com/baeldung/responseentity/CustomResponseController.java similarity index 98% rename from spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomResponseController.java rename to spring-boot-mvc/src/main/java/com/baeldung/responseentity/CustomResponseController.java index a29a6252f2..098c5e4794 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomResponseController.java +++ b/spring-boot-mvc/src/main/java/com/baeldung/responseentity/CustomResponseController.java @@ -1,4 +1,4 @@ -package com.baeldung.annotations; +package com.baeldung.responseentity; import java.io.IOException; import java.time.Year; diff --git a/spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomResponseWithBuilderController.java b/spring-boot-mvc/src/main/java/com/baeldung/responseentity/CustomResponseWithBuilderController.java similarity index 97% rename from spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomResponseWithBuilderController.java rename to spring-boot-mvc/src/main/java/com/baeldung/responseentity/CustomResponseWithBuilderController.java index 9a77029128..2e06060e6d 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/annotations/CustomResponseWithBuilderController.java +++ b/spring-boot-mvc/src/main/java/com/baeldung/responseentity/CustomResponseWithBuilderController.java @@ -1,4 +1,4 @@ -package com.baeldung.annotations; +package com.baeldung.responseentity; import java.time.Year; diff --git a/spring-boot-mvc/src/main/java/com/baeldung/swaggerboot/Application.java b/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/Application.java similarity index 88% rename from spring-boot-mvc/src/main/java/com/baeldung/swaggerboot/Application.java rename to spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/Application.java index 14e46b2306..51598aeacb 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/swaggerboot/Application.java +++ b/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/Application.java @@ -1,4 +1,4 @@ -package com.baeldung.swaggerboot; +package com.baeldung.swagger2boot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-mvc/src/main/java/com/baeldung/swaggerboot/configuration/SpringFoxConfig.java b/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java similarity index 97% rename from spring-boot-mvc/src/main/java/com/baeldung/swaggerboot/configuration/SpringFoxConfig.java rename to spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java index 3041dfdcc8..68e2c55deb 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/swaggerboot/configuration/SpringFoxConfig.java +++ b/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.swaggerboot.configuration; +package com.baeldung.swagger2boot.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; diff --git a/spring-boot-mvc/src/main/java/com/baeldung/swaggerboot/controller/RegularRestController.java b/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java similarity index 84% rename from spring-boot-mvc/src/main/java/com/baeldung/swaggerboot/controller/RegularRestController.java rename to spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java index 676937f7d7..df8714d041 100644 --- a/spring-boot-mvc/src/main/java/com/baeldung/swaggerboot/controller/RegularRestController.java +++ b/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java @@ -1,4 +1,4 @@ -package com.baeldung.swaggerboot.controller; +package com.baeldung.swagger2boot.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; diff --git a/spring-boot-nashorn/README.md b/spring-boot-nashorn/README.md new file mode 100644 index 0000000000..1ca43927ee --- /dev/null +++ b/spring-boot-nashorn/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: +- []() + diff --git a/spring-boot-nashorn/pom.xml b/spring-boot-nashorn/pom.xml new file mode 100644 index 0000000000..0f43752993 --- /dev/null +++ b/spring-boot-nashorn/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + com.baeldung.nashorn + spring-boot-nashorn + spring-boot-nashorn + 1.0 + jar + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + + \ No newline at end of file diff --git a/spring-boot-nashorn/src/main/java/com/baeldung/nashorn/Application.java b/spring-boot-nashorn/src/main/java/com/baeldung/nashorn/Application.java new file mode 100644 index 0000000000..b3cf1acd79 --- /dev/null +++ b/spring-boot-nashorn/src/main/java/com/baeldung/nashorn/Application.java @@ -0,0 +1,20 @@ +package com.baeldung.nashorn; + +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 Application extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(Application.class); + } + + public static void main(String[] args) throws Exception { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-boot-nashorn/src/main/java/com/baeldung/nashorn/controller/MyRestController.java b/spring-boot-nashorn/src/main/java/com/baeldung/nashorn/controller/MyRestController.java new file mode 100644 index 0000000000..86340d3d6a --- /dev/null +++ b/spring-boot-nashorn/src/main/java/com/baeldung/nashorn/controller/MyRestController.java @@ -0,0 +1,14 @@ +package com.baeldung.nashorn.controller; + +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class MyRestController { + + @RequestMapping("/next/{last}/{secondLast}") + public int index(@PathVariable("last") int last, @PathVariable("secondLast") int secondLast) throws Exception { + return last + secondLast; + } +} diff --git a/spring-boot-nashorn/src/main/java/com/baeldung/nashorn/controller/MyWebController.java b/spring-boot-nashorn/src/main/java/com/baeldung/nashorn/controller/MyWebController.java new file mode 100644 index 0000000000..78af6b966a --- /dev/null +++ b/spring-boot-nashorn/src/main/java/com/baeldung/nashorn/controller/MyWebController.java @@ -0,0 +1,32 @@ +package com.baeldung.nashorn.controller; + +import java.io.InputStreamReader; +import java.util.Map; + +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +@Controller +public class MyWebController { + + @RequestMapping("/") + public String index(Map model) throws Exception { + + ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn"); + + getClass().getResource("classpath:storedProcedures.sql"); + + nashorn.eval(new InputStreamReader(new ClassPathResource("static/js/react.js").getInputStream())); + nashorn.eval(new InputStreamReader(new ClassPathResource("static/js/react-dom-server.js").getInputStream())); + + nashorn.eval(new InputStreamReader(new ClassPathResource("static/app.js").getInputStream())); + Object html = nashorn.eval("ReactDOMServer.renderToString(" + "React.createElement(App, {data: [0,1,1]})" + ");"); + + model.put("content", String.valueOf(html)); + return "index"; + } +} diff --git a/spring-boot-nashorn/src/main/resources/application.properties b/spring-boot-nashorn/src/main/resources/application.properties new file mode 100644 index 0000000000..ae00fe72f8 --- /dev/null +++ b/spring-boot-nashorn/src/main/resources/application.properties @@ -0,0 +1,2 @@ +spring.mvc.view.prefix: /WEB-INF/jsp/ +spring.mvc.view.suffix: .jsp \ No newline at end of file diff --git a/spring-boot-nashorn/src/main/resources/static/app.js b/spring-boot-nashorn/src/main/resources/static/app.js new file mode 100644 index 0000000000..e5d79217dd --- /dev/null +++ b/spring-boot-nashorn/src/main/resources/static/app.js @@ -0,0 +1,37 @@ +var App = React.createClass({displayName: "App", + + handleSubmit: function () { + var last = this.state.data[this.state.data.length-1]; + var secondLast = this.state.data[this.state.data.length-2]; + $.ajax({ + url: '/next/'+last+'/'+secondLast, + dataType: 'text', + success: function (msg) { + var series = this.state.data; + series.push(msg); + this.setState({data: series}); + }.bind(this), + error: function (xhr, status, err) { + console.error("/next", status, err.toString()); + }.bind(this) + }); + }, + + componentDidMount: function() { + this.setState({data: this.props.data}); + }, + + getInitialState: function () { + return {data: []}; + }, + + render: function () { + return ( + React.createElement("div", {className: "app"}, + React.createElement("h2", null, "Fibonacci Generator"), + React.createElement("h2", null, this.state.data.toString()), + React.createElement("input", {type: "submit", value: "Next", onClick: this.handleSubmit}) + ) + ); + } +}); \ No newline at end of file diff --git a/spring-boot-nashorn/src/main/resources/static/js/react-dom-server.js b/spring-boot-nashorn/src/main/resources/static/js/react-dom-server.js new file mode 100644 index 0000000000..91050111c3 --- /dev/null +++ b/spring-boot-nashorn/src/main/resources/static/js/react-dom-server.js @@ -0,0 +1,42 @@ +/** + * ReactDOMServer v0.14.3 + * + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ +// Based off https://github.com/ForbesLindesay/umd/blob/master/template.js +;(function(f) { + // CommonJS + if (typeof exports === "object" && typeof module !== "undefined") { + module.exports = f(require('react')); + + // RequireJS + } else if (typeof define === "function" && define.amd) { + define(['react'], f); + + // + + + + +
    ${content}
    + + + + \ No newline at end of file diff --git a/spring-boot-ops/pom.xml b/spring-boot-ops/pom.xml index f36434b682..f578a24163 100644 --- a/spring-boot-ops/pom.xml +++ b/spring-boot-ops/pom.xml @@ -85,11 +85,17 @@ ${jquery.version} - + org.springframework.cloud spring-cloud-context ${springcloud.version} + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + @@ -190,7 +196,8 @@ 2.2 18.0 3.1.7 - 2.0.2.RELEASE + 2.0.2.RELEASE + 4.5.8 diff --git a/spring-boot-ops/src/main/java/com/baeldung/properties/ConfProperties.java b/spring-boot-ops/src/main/java/com/baeldung/properties/ConfProperties.java index 0b6041bb06..c6413324f3 100644 --- a/spring-boot-ops/src/main/java/com/baeldung/properties/ConfProperties.java +++ b/spring-boot-ops/src/main/java/com/baeldung/properties/ConfProperties.java @@ -6,13 +6,13 @@ import org.springframework.stereotype.Component; @Component public class ConfProperties { - @Value("${url}") + @Value("${db.url}") private String url; - @Value("${username}") + @Value("${db.username}") private String username; - @Value("${password}") + @Value("${db.password}") private String password; public String getUrl() { diff --git a/spring-boot-ops/src/main/resources/external/conf.properties b/spring-boot-ops/src/main/resources/external/conf.properties index cfcd23dc76..944b31cc5c 100644 --- a/spring-boot-ops/src/main/resources/external/conf.properties +++ b/spring-boot-ops/src/main/resources/external/conf.properties @@ -1,4 +1,4 @@ -url=jdbc:postgresql://localhost:5432/ -username=admin -password=root +db.url=jdbc:postgresql://localhost:5432/ +db.username=admin +db.password=root spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationIntegrationTest.java b/spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationManualTest.java similarity index 84% rename from spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationIntegrationTest.java rename to spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationManualTest.java index 14e80c3ac7..35b488f9d8 100644 --- a/spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationIntegrationTest.java +++ b/spring-boot-ops/src/test/java/com/baeldung/restart/RestartApplicationManualTest.java @@ -2,17 +2,16 @@ package com.baeldung.restart; import static org.junit.Assert.assertEquals; -import org.junit.After; -import org.junit.Before; import org.junit.Test; import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; -import java.time.Duration; - -public class RestartApplicationIntegrationTest { +/** + * We have to make sure that while running this test, 8080 and 8090 ports are free. + * Otherwise it will fail. + */ +public class RestartApplicationManualTest { private TestRestTemplate restTemplate = new TestRestTemplate(); diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigProperties.java b/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ConfigProperties.java similarity index 98% rename from spring-boot-properties/src/main/java/com/baeldung/properties/ConfigProperties.java rename to spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ConfigProperties.java index b690c8e305..47df784885 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigProperties.java +++ b/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/ConfigProperties.java @@ -1,4 +1,4 @@ -package com.baeldung.properties; +package com.baeldung.configurationproperties; import java.util.List; import java.util.Map; diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/conversion/Employee.java b/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/Employee.java similarity index 91% rename from spring-boot-properties/src/main/java/com/baeldung/properties/conversion/Employee.java rename to spring-boot-properties/src/main/java/com/baeldung/configurationproperties/Employee.java index 52c7881dfc..20f4792a8e 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/conversion/Employee.java +++ b/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/Employee.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.conversion; +package com.baeldung.configurationproperties; public class Employee { diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/conversion/EmployeeConverter.java b/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/EmployeeConverter.java similarity index 91% rename from spring-boot-properties/src/main/java/com/baeldung/properties/conversion/EmployeeConverter.java rename to spring-boot-properties/src/main/java/com/baeldung/configurationproperties/EmployeeConverter.java index 6ec19cae72..83ef22be34 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/conversion/EmployeeConverter.java +++ b/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/EmployeeConverter.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.conversion; +package com.baeldung.configurationproperties; import org.springframework.boot.context.properties.ConfigurationPropertiesBinding; import org.springframework.core.convert.converter.Converter; diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/Item.java b/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/Item.java similarity index 90% rename from spring-boot-properties/src/main/java/com/baeldung/properties/Item.java rename to spring-boot-properties/src/main/java/com/baeldung/configurationproperties/Item.java index 741bbba144..d0f0d2987a 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/Item.java +++ b/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/Item.java @@ -1,4 +1,4 @@ -package com.baeldung.properties; +package com.baeldung.configurationproperties; public class Item { diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/conversion/PropertiesConversionApplication.java b/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/PropertiesConversionApplication.java similarity index 91% rename from spring-boot-properties/src/main/java/com/baeldung/properties/conversion/PropertiesConversionApplication.java rename to spring-boot-properties/src/main/java/com/baeldung/configurationproperties/PropertiesConversionApplication.java index f00a26e9c4..ccfd1d6f6f 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/conversion/PropertiesConversionApplication.java +++ b/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/PropertiesConversionApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.conversion; +package com.baeldung.configurationproperties; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/conversion/PropertyConversion.java b/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/PropertyConversion.java similarity index 97% rename from spring-boot-properties/src/main/java/com/baeldung/properties/conversion/PropertyConversion.java rename to spring-boot-properties/src/main/java/com/baeldung/configurationproperties/PropertyConversion.java index b9c890306f..52d4925d82 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/conversion/PropertyConversion.java +++ b/spring-boot-properties/src/main/java/com/baeldung/configurationproperties/PropertyConversion.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.conversion; +package com.baeldung.configurationproperties; import java.time.Duration; import java.time.temporal.ChronoUnit; diff --git a/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java b/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java index ee9671c755..41f26d51f7 100644 --- a/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java +++ b/spring-boot-properties/src/main/java/com/baeldung/properties/ConfigPropertiesDemoApplication.java @@ -4,6 +4,8 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.ComponentScan; +import com.baeldung.configurationproperties.ConfigProperties; + @SpringBootApplication @ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class }) public class ConfigPropertiesDemoApplication { diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/ConfigPropertiesIntegrationTest.java b/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ConfigPropertiesIntegrationTest.java similarity index 91% rename from spring-boot-properties/src/test/java/com/baeldung/properties/ConfigPropertiesIntegrationTest.java rename to spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ConfigPropertiesIntegrationTest.java index 4777551132..141400b1fe 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/ConfigPropertiesIntegrationTest.java +++ b/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/ConfigPropertiesIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.properties; +package com.baeldung.configurationproperties; import org.junit.Assert; import org.junit.Test; @@ -8,6 +8,10 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.configurationproperties.ConfigProperties; +import com.baeldung.properties.AdditionalProperties; +import com.baeldung.properties.ConfigPropertiesDemoApplication; + @RunWith(SpringRunner.class) @SpringBootTest(classes = ConfigPropertiesDemoApplication.class) @TestPropertySource("classpath:configprops-test.properties") diff --git a/spring-boot-properties/src/test/java/com/baeldung/properties/conversion/PropertiesConversionIntegrationTest.java b/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/PropertiesConversionIntegrationTest.java similarity index 89% rename from spring-boot-properties/src/test/java/com/baeldung/properties/conversion/PropertiesConversionIntegrationTest.java rename to spring-boot-properties/src/test/java/com/baeldung/configurationproperties/PropertiesConversionIntegrationTest.java index 53bad329ea..1bdc8bff9b 100644 --- a/spring-boot-properties/src/test/java/com/baeldung/properties/conversion/PropertiesConversionIntegrationTest.java +++ b/spring-boot-properties/src/test/java/com/baeldung/configurationproperties/PropertiesConversionIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.properties.conversion; +package com.baeldung.configurationproperties; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -12,8 +12,8 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.unit.DataSize; -import com.baeldung.properties.conversion.PropertiesConversionApplication; -import com.baeldung.properties.conversion.PropertyConversion; +import com.baeldung.configurationproperties.PropertiesConversionApplication; +import com.baeldung.configurationproperties.PropertyConversion; @RunWith(SpringRunner.class) @SpringBootTest(classes = PropertiesConversionApplication.class) diff --git a/spring-boot-rest/src/main/java/com/baeldung/web/controller/ExamplePostController.java b/spring-boot-rest/src/main/java/com/baeldung/requestresponsebody/ExamplePostController.java similarity index 91% rename from spring-boot-rest/src/main/java/com/baeldung/web/controller/ExamplePostController.java rename to spring-boot-rest/src/main/java/com/baeldung/requestresponsebody/ExamplePostController.java index 1519d95d4d..90211b11a3 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/web/controller/ExamplePostController.java +++ b/spring-boot-rest/src/main/java/com/baeldung/requestresponsebody/ExamplePostController.java @@ -1,7 +1,7 @@ -package com.baeldung.web.controller; +package com.baeldung.requestresponsebody; import com.baeldung.services.ExampleService; -import com.baeldung.transfer.ResponseTransfer; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -10,7 +10,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; -import com.baeldung.transfer.LoginForm; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; diff --git a/spring-boot-rest/src/main/java/com/baeldung/transfer/LoginForm.java b/spring-boot-rest/src/main/java/com/baeldung/requestresponsebody/LoginForm.java similarity index 93% rename from spring-boot-rest/src/main/java/com/baeldung/transfer/LoginForm.java rename to spring-boot-rest/src/main/java/com/baeldung/requestresponsebody/LoginForm.java index caafcdb500..36c7946918 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/transfer/LoginForm.java +++ b/spring-boot-rest/src/main/java/com/baeldung/requestresponsebody/LoginForm.java @@ -1,4 +1,4 @@ -package com.baeldung.transfer; +package com.baeldung.requestresponsebody; public class LoginForm { private String username; diff --git a/spring-boot-rest/src/main/java/com/baeldung/transfer/ResponseTransfer.java b/spring-boot-rest/src/main/java/com/baeldung/requestresponsebody/ResponseTransfer.java similarity index 86% rename from spring-boot-rest/src/main/java/com/baeldung/transfer/ResponseTransfer.java rename to spring-boot-rest/src/main/java/com/baeldung/requestresponsebody/ResponseTransfer.java index d4fb282c1b..60fc698792 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/transfer/ResponseTransfer.java +++ b/spring-boot-rest/src/main/java/com/baeldung/requestresponsebody/ResponseTransfer.java @@ -1,4 +1,4 @@ -package com.baeldung.transfer; +package com.baeldung.requestresponsebody; public class ResponseTransfer { diff --git a/spring-boot-rest/src/main/java/com/baeldung/services/ExampleService.java b/spring-boot-rest/src/main/java/com/baeldung/services/ExampleService.java index 48d98b41db..f2734ffa39 100644 --- a/spring-boot-rest/src/main/java/com/baeldung/services/ExampleService.java +++ b/spring-boot-rest/src/main/java/com/baeldung/services/ExampleService.java @@ -1,8 +1,9 @@ package com.baeldung.services; -import com.baeldung.transfer.LoginForm; import org.springframework.stereotype.Service; +import com.baeldung.requestresponsebody.LoginForm; + @Service public class ExampleService { diff --git a/spring-boot-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerRequestIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerRequestIntegrationTest.java index fc533072c8..a277d5a685 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerRequestIntegrationTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerRequestIntegrationTest.java @@ -17,9 +17,9 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.baeldung.SpringBootRestApplication; +import com.baeldung.requestresponsebody.ExamplePostController; +import com.baeldung.requestresponsebody.LoginForm; import com.baeldung.services.ExampleService; -import com.baeldung.transfer.LoginForm; -import com.baeldung.web.controller.ExamplePostController; @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringBootRestApplication.class) diff --git a/spring-boot-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerResponseIntegrationTest.java b/spring-boot-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerResponseIntegrationTest.java index cbe21b1d90..f8c70b0f4a 100644 --- a/spring-boot-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerResponseIntegrationTest.java +++ b/spring-boot-rest/src/test/java/com/baeldung/controllers/ExamplePostControllerResponseIntegrationTest.java @@ -18,9 +18,9 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.baeldung.SpringBootRestApplication; +import com.baeldung.requestresponsebody.ExamplePostController; +import com.baeldung.requestresponsebody.LoginForm; import com.baeldung.services.ExampleService; -import com.baeldung.transfer.LoginForm; -import com.baeldung.web.controller.ExamplePostController; @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringBootRestApplication.class) diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/SpringBootSecurityApplication.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/autoconfig/SpringBootSecurityApplication.java similarity index 80% rename from spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/SpringBootSecurityApplication.java rename to spring-boot-security/src/main/java/com/baeldung/springbootsecurity/autoconfig/SpringBootSecurityApplication.java index 7007c15596..3afeda66a4 100644 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/SpringBootSecurityApplication.java +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/autoconfig/SpringBootSecurityApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.springbootsecurity.basic_auth; +package com.baeldung.springbootsecurity.autoconfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -7,7 +7,7 @@ import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfi @SpringBootApplication(exclude = { SecurityAutoConfiguration.class // ,ManagementWebSecurityAutoConfiguration.class -}, scanBasePackages = "com.baeldung.springbootsecurity.basic_auth") +}, scanBasePackages = "com.baeldung.springbootsecurity.autoconfig") public class SpringBootSecurityApplication { public static void main(String[] args) { SpringApplication.run(SpringBootSecurityApplication.class, args); diff --git a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicConfiguration.java b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/autoconfig/config/BasicConfiguration.java similarity index 95% rename from spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicConfiguration.java rename to spring-boot-security/src/main/java/com/baeldung/springbootsecurity/autoconfig/config/BasicConfiguration.java index 3cfa45421c..7060792df5 100644 --- a/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/basic_auth/config/BasicConfiguration.java +++ b/spring-boot-security/src/main/java/com/baeldung/springbootsecurity/autoconfig/config/BasicConfiguration.java @@ -1,4 +1,4 @@ -package com.baeldung.springbootsecurity.basic_auth.config; +package com.baeldung.springbootsecurity.autoconfig.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; diff --git a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicConfigurationIntegrationTest.java b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/autoconfig/config/BasicConfigurationIntegrationTest.java similarity index 93% rename from spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicConfigurationIntegrationTest.java rename to spring-boot-security/src/test/java/com/baeldung/springbootsecurity/autoconfig/config/BasicConfigurationIntegrationTest.java index f221712513..a28d0f5e26 100644 --- a/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/basic_auth/BasicConfigurationIntegrationTest.java +++ b/spring-boot-security/src/test/java/com/baeldung/springbootsecurity/autoconfig/config/BasicConfigurationIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.springbootsecurity.basic_auth; +package com.baeldung.springbootsecurity.autoconfig.config; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -18,6 +18,8 @@ import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.springbootsecurity.autoconfig.SpringBootSecurityApplication; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = RANDOM_PORT, classes = SpringBootSecurityApplication.class) public class BasicConfigurationIntegrationTest { diff --git a/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java deleted file mode 100644 index c0298daeb1..0000000000 --- a/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.SpringCloudConfigClientApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringCloudConfigClientApplication.class) -public class SpringContextIntegrationTest { - - @Test - public void contextLoads() { - } - -} diff --git a/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextLiveTest.java index 8a33efef43..a401d41e1e 100644 --- a/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextLiveTest.java +++ b/spring-cloud-bus/spring-cloud-config-client/src/test/java/org/baeldung/SpringContextLiveTest.java @@ -7,12 +7,27 @@ import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.SpringCloudConfigClientApplication; +/** + * This LiveTest requires: + * 1- The 'spring-cloud-bus/spring-cloud-config-server' service running, with valid Spring Cloud Config properties, for instance: + * 1.1- `spring.cloud.config.server.git.uri` pointing to a valid URI, which has `user.role` and `user.password` properties configured in a properties file. For example, to achieve this in a dev environment: + * 1.1.1- `cd my/custom/path` + * 1.1.2- `git init .` + * 1.1.3- `echo user.role=Programmer >> application.properties` + * 1.1.4- `echo user.password=d3v3L >> application.properties` + * 1.1.5- `git add .` + * 1.1.6- `git commit -m 'inital commit'` + * 1.1.7- 'spring-cloud-bus/spring-cloud-config-server' with property `spring.cloud.config.server.git.uri=my/custom/path` + * + * Note: This is enough to run the ContextTest successfully, but to get the full functionality shown in the related article, we'll need also a RabbitMQ instance running (e.g. `docker run -d --hostname my-rabbit --name some-rabbit -p 15672:15672 -p 5672:5672 rabbitmq:3-management`) + * + */ @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringCloudConfigClientApplication.class) public class SpringContextLiveTest { - @Test - public void contextLoads() { - } + @Test + public void contextLoads() { + } } diff --git a/spring-cloud-data-flow/apache-spark-job/pom.xml b/spring-cloud-data-flow/apache-spark-job/pom.xml index 671e8ed71a..306b23c60a 100644 --- a/spring-cloud-data-flow/apache-spark-job/pom.xml +++ b/spring-cloud-data-flow/apache-spark-job/pom.xml @@ -4,6 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 apache-spark-job + apache-spark-job spring-cloud-data-flow diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-etl/pom.xml b/spring-cloud-data-flow/spring-cloud-data-flow-etl/pom.xml index ab34271273..0274b5fed1 100644 --- a/spring-cloud-data-flow/spring-cloud-data-flow-etl/pom.xml +++ b/spring-cloud-data-flow/spring-cloud-data-flow-etl/pom.xml @@ -3,7 +3,7 @@ 4.0.0 spring-cloud-data-flow-etl 0.0.1-SNAPSHOT - etl + spring-cloud-data-flow-etl pom diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/pom.xml b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/pom.xml index cf583c216a..7166b0fd32 100644 --- a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/pom.xml +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/pom.xml @@ -1,5 +1,6 @@ - 4.0.0 data-flow-server @@ -12,7 +13,7 @@ parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../../parent-boot-1 @@ -20,6 +21,16 @@ org.springframework.cloud spring-cloud-starter-dataflow-server-local + + org.hibernate + hibernate-core + ${hibernate.compatible.version} + + + org.hibernate + hibernate-entitymanager + ${hibernate.compatible.version} + @@ -42,8 +53,9 @@ - 1.1.0.RELEASE - Brixton.SR7 + 1.3.1.RELEASE + Edgware.SR6 + 5.2.12.Final diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/main/resources/application.properties b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/main/resources/application.properties new file mode 100644 index 0000000000..20ad5d5bcb --- /dev/null +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/main/resources/application.properties @@ -0,0 +1,2 @@ +#spring.datasource.url=jdbc:h2:mem:dataflow +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect \ No newline at end of file diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/org/baeldung/SpringContextLiveTest.java deleted file mode 100644 index 980c096f5e..0000000000 --- a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/java/org/baeldung/SpringContextLiveTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.cloud.DataFlowServerApplication; -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(classes = DataFlowServerApplication.class) -public class SpringContextLiveTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/resources/application.properties b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/resources/application.properties new file mode 100644 index 0000000000..70e3e5c65b --- /dev/null +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-server/src/test/resources/application.properties @@ -0,0 +1 @@ +spring.datasource.url=jdbc:h2:mem:dataflow \ No newline at end of file diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-shell/pom.xml b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-shell/pom.xml index 52cb204201..9c379624d3 100644 --- a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-shell/pom.xml +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/data-flow-shell/pom.xml @@ -12,7 +12,7 @@ parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../../parent-boot-1 diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/log-sink/pom.xml b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/log-sink/pom.xml index ecabb91a98..73fb82d79f 100644 --- a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/log-sink/pom.xml +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/log-sink/pom.xml @@ -12,7 +12,7 @@ parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../../parent-boot-1 diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/pom.xml b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/pom.xml index e5c6830393..bcb0ace973 100644 --- a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/pom.xml +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/pom.xml @@ -1,15 +1,16 @@ 4.0.0 - spring-cloud-data-flow-stream + spring-cloud-data-flow-stream-processing 0.0.1-SNAPSHOT - spring-cloud-data-flow-stream + spring-cloud-data-flow-stream-processing pom com.baeldung parent-modules 1.0.0-SNAPSHOT + ../../ diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-processor/pom.xml b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-processor/pom.xml index de354ca698..28a9d3e6e0 100644 --- a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-processor/pom.xml +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-processor/pom.xml @@ -12,7 +12,7 @@ parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../../parent-boot-1 diff --git a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-source/pom.xml b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-source/pom.xml index a4d06e13d2..3b748fd7df 100644 --- a/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-source/pom.xml +++ b/spring-cloud-data-flow/spring-cloud-data-flow-stream-processing/time-source/pom.xml @@ -12,7 +12,7 @@ parent-boot-1 com.baeldung 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../../parent-boot-1 diff --git a/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml b/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml index 89c9318c4e..b6b5a1cf0f 100644 --- a/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml +++ b/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml @@ -1,4 +1,5 @@ - 4.0.0 org.baeldung.cloud @@ -43,6 +44,11 @@ org.springframework.cloud spring-cloud-task-batch + + com.h2database + h2 + test + diff --git a/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/main/java/com/baeldung/task/TaskDemo.java b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/main/java/com/baeldung/task/TaskDemo.java index be2a173589..30e17cb956 100644 --- a/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/main/java/com/baeldung/task/TaskDemo.java +++ b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/main/java/com/baeldung/task/TaskDemo.java @@ -14,6 +14,13 @@ import org.springframework.cloud.task.configuration.EnableTask; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; +/** + * This Application requires: + * * a MySql instance running, that allows a root user with no password, and with a database named + * + * (e.g. with the following command `docker run -p 3306:3306 --name bael-mysql -e MYSQL_ALLOW_EMPTY_PASSWORD=true -e MYSQL_DATABASE=springcloud mysql:latest`) + * + */ @SpringBootApplication @EnableTask @EnableBatchProcessing diff --git a/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 60% rename from spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/org/baeldung/SpringContextLiveTest.java rename to spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/org/baeldung/SpringContextIntegrationTest.java index ddbcbf65ea..0caa626c14 100644 --- a/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/org/baeldung/SpringContextLiveTest.java +++ b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -10,18 +10,10 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baeldung.task.JobConfiguration; import com.baeldung.task.TaskDemo; -/** - * This Live Test requires: - * * a MySql instance running, that allows a root user with no password, and with a database named - * - * (e.g. with the following command `docker run -p 3306:3306 --name bael-mysql -e MYSQL_ALLOW_EMPTY_PASSWORD=true -e MYSQL_DATABASE=springcloud mysql:latest`) - * - */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootApplication -@ContextConfiguration(classes = { JobConfiguration.class, TaskDemo.class }, initializers = { - ConfigFileApplicationContextInitializer.class }) -public class SpringContextLiveTest { +@ContextConfiguration(classes = { JobConfiguration.class, TaskDemo.class }, initializers = { ConfigFileApplicationContextInitializer.class }) +public class SpringContextIntegrationTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { diff --git a/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/resources/application.yml b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/resources/application.yml new file mode 100644 index 0000000000..794ac4d247 --- /dev/null +++ b/spring-cloud/spring-cloud-task/springcloudtaskbatch/src/test/resources/application.yml @@ -0,0 +1,11 @@ +spring: + datasource: + url: jdbc:h2:mem:springcloud + username: sa + password: + jpa: + hibernate: + ddl-auto: create-drop + properties: + hibernate: + dialect: org.hibernate.dialect.H2Dialect \ No newline at end of file diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml index 6b5547aba9..d68beda64a 100644 --- a/spring-core-2/pom.xml +++ b/spring-core-2/pom.xml @@ -4,6 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-core-2 + spring-core-2 com.baeldung diff --git a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java b/spring-core/src/test/java/com/baeldung/classpathfileaccess/SpringResourceIntegrationTest.java similarity index 99% rename from spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java rename to spring-core/src/test/java/com/baeldung/classpathfileaccess/SpringResourceIntegrationTest.java index c7a2984045..b57a64a8c6 100644 --- a/spring-core/src/test/java/com/baeldung/resource/SpringResourceIntegrationTest.java +++ b/spring-core/src/test/java/com/baeldung/classpathfileaccess/SpringResourceIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.resource; +package com.baeldung.classpathfileaccess; import static org.junit.Assert.assertEquals; diff --git a/spring-data-rest/README.md b/spring-data-rest/README.md index abbacb69cc..4b89a24bbc 100644 --- a/spring-data-rest/README.md +++ b/spring-data-rest/README.md @@ -17,7 +17,6 @@ To view the running application, visit [http://localhost:8080](http://localhost: - [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) - [Customizing HTTP Endpoints in Spring Data REST](https://www.baeldung.com/spring-data-rest-customize-http-endpoints) diff --git a/spring-di/pom.xml b/spring-di/pom.xml index 62456ba31c..f3ad380778 100644 --- a/spring-di/pom.xml +++ b/spring-di/pom.xml @@ -6,6 +6,7 @@ spring-di 1.0-SNAPSHOT war + spring-di parent-boot-2 diff --git a/spring-freemarker/src/main/java/com/baeldung/freemarker/controller/SpringController.java b/spring-freemarker/src/main/java/com/baeldung/freemarker/controller/SpringController.java index 18b42f06ea..6f6b5994f3 100644 --- a/spring-freemarker/src/main/java/com/baeldung/freemarker/controller/SpringController.java +++ b/spring-freemarker/src/main/java/com/baeldung/freemarker/controller/SpringController.java @@ -1,9 +1,10 @@ package com.baeldung.freemarker.controller; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; +import java.util.*; +import com.baeldung.freemarker.method.LastCharMethod; +import freemarker.template.DefaultObjectWrapperBuilder; +import freemarker.template.Version; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; @@ -43,4 +44,12 @@ public class SpringController { return "redirect:/cars"; } -} + @RequestMapping(value = "/commons", method = RequestMethod.GET) + public String showCommonsPage(Model model) { + model.addAttribute("statuses", Arrays.asList("200 OK", "404 Not Found", "500 Internal Server Error")); + model.addAttribute("lastChar", new LastCharMethod()); + model.addAttribute("random", new Random()); + model.addAttribute("statics", new DefaultObjectWrapperBuilder(new Version("2.3.28")).build().getStaticModels()); + return "commons"; + } +} \ No newline at end of file diff --git a/spring-freemarker/src/main/java/com/baeldung/freemarker/method/LastCharMethod.java b/spring-freemarker/src/main/java/com/baeldung/freemarker/method/LastCharMethod.java new file mode 100644 index 0000000000..956a512f56 --- /dev/null +++ b/spring-freemarker/src/main/java/com/baeldung/freemarker/method/LastCharMethod.java @@ -0,0 +1,16 @@ +package com.baeldung.freemarker.method; + +import freemarker.template.TemplateMethodModelEx; +import freemarker.template.TemplateModelException; +import org.springframework.util.StringUtils; + +import java.util.List; + +public class LastCharMethod implements TemplateMethodModelEx { + public Object exec(List arguments) throws TemplateModelException { + if (arguments.size() != 1 || StringUtils.isEmpty(arguments.get(0))) + throw new TemplateModelException("Wrong arguments!"); + String argument = arguments.get(0).toString(); + return argument.charAt(argument.length() - 1); + } +} diff --git a/spring-freemarker/src/main/webapp/WEB-INF/views/ftl/commons.ftl b/spring-freemarker/src/main/webapp/WEB-INF/views/ftl/commons.ftl new file mode 100644 index 0000000000..eea1e6f683 --- /dev/null +++ b/spring-freemarker/src/main/webapp/WEB-INF/views/ftl/commons.ftl @@ -0,0 +1,28 @@ +

    Testing is a property exists: ${student???c}

    +<#if status??> +

    Property value: ${status.reason}

    +<#else> +

    Missing property

    + + +

    Iterating a sequence:

    +<#list statuses> +
      + <#items as status> +
    • ${status}
    • + +
    + <#else> +

    No statuses available

    + + +

    Using static methods

    +<#assign MathUtils=statics['java.lang.Math']> +

    PI value: ${MathUtils.PI}

    +

    2*10 is: ${MathUtils.pow(2, 10)}

    + +

    Using bean method

    +

    Random value: ${random.nextInt()}

    + +

    Use custom method

    +

    Last char example: ${lastChar('mystring')}

    \ No newline at end of file diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index cb16e91bc4..ea0acdcb00 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -8,17 +8,20 @@ war - parent-spring-5 + parent-boot-2 com.baeldung 0.0.1-SNAPSHOT - ../parent-spring-5 + ../parent-boot-2 - org.springframework - spring-webmvc - ${spring.version} + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat javax.servlet @@ -33,7 +36,11 @@ javax.servlet jstl - ${jstl.version} + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided @@ -55,17 +62,6 @@ - - commons-fileupload - commons-fileupload - ${commons-fileupload.version} - - - commons-io - commons-io - - - net.sourceforge.htmlunit htmlunit @@ -106,9 +102,8 @@ 2.4.0 - org.springframework - spring-test - ${spring.version} + org.springframework.boot + spring-boot-starter-test test @@ -134,15 +129,8 @@ 2.8.5 - org.springframework - spring-websocket - ${spring.version} - - - - org.springframework - spring-messaging - ${spring.version} + org.springframework.boot + spring-boot-starter-websocket org.glassfish @@ -296,6 +284,7 @@ 3.16-beta1 3.0.1-b09 + com.baeldung.SpringMVCApplication diff --git a/spring-mvc-java/src/main/java/com/baeldung/SpringMVCApplication.java b/spring-mvc-java/src/main/java/com/baeldung/SpringMVCApplication.java new file mode 100644 index 0000000000..a456dc125e --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/SpringMVCApplication.java @@ -0,0 +1,12 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +@SpringBootApplication +public class SpringMVCApplication extends SpringBootServletInitializer { + public static void main(String[] args) { + SpringApplication.run(SpringMVCApplication.class, args); + } +} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/aop/LoggingAspect.java b/spring-mvc-java/src/main/java/com/baeldung/aop/LoggingAspect.java index 7ae37404be..169d664471 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/aop/LoggingAspect.java +++ b/spring-mvc-java/src/main/java/com/baeldung/aop/LoggingAspect.java @@ -23,15 +23,15 @@ public class LoggingAspect { } }; - @Pointcut("@target(org.springframework.stereotype.Repository)") + @Pointcut("within(com.baeldung..*) && execution(* com.baeldung.dao.FooDao.*(..))") public void repositoryMethods() { } - @Pointcut("@annotation(com.baeldung.aop.annotations.Loggable)") + @Pointcut("within(com.baeldung..*) && @annotation(com.baeldung.aop.annotations.Loggable)") public void loggableMethods() { } - @Pointcut("@args(com.baeldung.aop.annotations.Entity)") + @Pointcut("within(com.baeldung..*) && @args(com.baeldung.aop.annotations.Entity)") public void methodsAcceptingEntities() { } diff --git a/spring-mvc-java/src/main/java/com/baeldung/aop/PerformanceAspect.java b/spring-mvc-java/src/main/java/com/baeldung/aop/PerformanceAspect.java index 1f2076adff..8f374cc1e5 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/aop/PerformanceAspect.java +++ b/spring-mvc-java/src/main/java/com/baeldung/aop/PerformanceAspect.java @@ -15,7 +15,7 @@ public class PerformanceAspect { private static Logger logger = Logger.getLogger(PerformanceAspect.class.getName()); - @Pointcut("within(@org.springframework.stereotype.Repository *)") + @Pointcut("within(com.baeldung..*) && execution(* com.baeldung.dao.FooDao.*(..))") public void repositoryClassMethods() { } diff --git a/spring-mvc-java/src/main/java/com/baeldung/aop/PublishingAspect.java b/spring-mvc-java/src/main/java/com/baeldung/aop/PublishingAspect.java index 7791c63e7b..a45402dc18 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/aop/PublishingAspect.java +++ b/spring-mvc-java/src/main/java/com/baeldung/aop/PublishingAspect.java @@ -20,11 +20,11 @@ public class PublishingAspect { this.eventPublisher = eventPublisher; } - @Pointcut("@target(org.springframework.stereotype.Repository)") + @Pointcut("within(com.baeldung..*) && execution(* com.baeldung.dao.FooDao.*(..))") public void repositoryMethods() { } - @Pointcut("execution(* *..create*(Long,..))") + @Pointcut("within(com.baeldung..*) && execution(* com.baeldung.dao.FooDao.create*(Long,..))") public void firstLongParamMethods() { } diff --git a/spring-mvc-java/src/main/java/com/baeldung/config/AppInitializer.java b/spring-mvc-java/src/main/java/com/baeldung/config/AppInitializer.java deleted file mode 100644 index eec12f466f..0000000000 --- a/spring-mvc-java/src/main/java/com/baeldung/config/AppInitializer.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.config; - -import org.springframework.web.WebApplicationInitializer; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -public class AppInitializer implements WebApplicationInitializer { - - @Override - public void onStartup(ServletContext container) throws ServletException { - AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); - - context.scan("com.baeldung"); - - container.addListener(new ContextLoaderListener(context)); - - ServletRegistration.Dynamic dispatcher = container.addServlet("mvc", new DispatcherServlet(context)); - dispatcher.setLoadOnStartup(1); - dispatcher.addMapping("/"); - - // final MultipartConfigElement multipartConfigElement = new - // MultipartConfigElement(TMP_FOLDER, MAX_UPLOAD_SIZE, - // MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2); - // - // appServlet.setMultipartConfig(multipartConfigElement); - } - -} diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 44fef92917..96e300464b 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -3,9 +3,6 @@ package com.baeldung.spring.web.config; import java.util.ArrayList; import java.util.List; -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.ComponentScan; @@ -15,7 +12,6 @@ import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.http.MediaType; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; @@ -26,8 +22,9 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; import org.springframework.web.util.UrlPathHelper; import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; import org.thymeleaf.spring4.view.ThymeleafViewResolver; -import org.thymeleaf.templateresolver.ServletContextTemplateResolver; +import org.thymeleaf.templateresolver.ITemplateResolver; import com.baeldung.excel.ExcelPOIHelper; @@ -35,9 +32,6 @@ import com.baeldung.excel.ExcelPOIHelper; @Configuration @ComponentScan(basePackages = { "com.baeldung.web.controller" }) public class WebConfig implements WebMvcConfigurer { - - @Autowired - private ServletContext ctx; @Override public void addViewControllers(final ViewControllerRegistry registry) { @@ -64,11 +58,11 @@ public class WebConfig implements WebMvcConfigurer { @Bean @Description("Thymeleaf template resolver serving HTML 5") - public ServletContextTemplateResolver templateResolver() { - final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(ctx); + public ITemplateResolver templateResolver() { + final SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); - templateResolver.setTemplateMode("HTML5"); + templateResolver.setTemplateMode("HTML"); return templateResolver; } @@ -92,15 +86,6 @@ public class WebConfig implements WebMvcConfigurer { public void addResourceHandlers(final ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } - - @Bean(name = "multipartResolver") - public CommonsMultipartResolver multipartResolver() { - - final CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); - multipartResolver.setMaxUploadSize(100000); - - return multipartResolver; - } @Override public void extendMessageConverters(final List> converters) { diff --git a/spring-mvc-java/src/main/resources/application.properties b/spring-mvc-java/src/main/resources/application.properties new file mode 100644 index 0000000000..00c491c271 --- /dev/null +++ b/spring-mvc-java/src/main/resources/application.properties @@ -0,0 +1,5 @@ +server.servlet.context-path=/spring-mvc-java +spring.servlet.multipart.max-file-size=1MB +spring.servlet.multipart.max-request-size=1MB +spring.servlet.multipart.enabled=true +spring.servlet.multipart.location=${java.io.tmpdir} \ No newline at end of file diff --git a/spring-mvc-java/src/test/java/com/baeldung/SpringContextIntegrationTest.java b/spring-mvc-java/src/test/java/com/baeldung/SpringContextIntegrationTest.java index 4c06917325..ae91d4dc1e 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/SpringContextIntegrationTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -3,15 +3,12 @@ package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.config.AppInitializer; +import com.baeldung.config.TestConfig; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { AppInitializer.class }, loader = AnnotationConfigContextLoader.class) -@WebAppConfiguration +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = {TestConfig.class}) public class SpringContextIntegrationTest { @Test diff --git a/spring-mvc-java/src/test/java/com/baeldung/SpringContextTest.java b/spring-mvc-java/src/test/java/com/baeldung/SpringContextTest.java index 9777addb61..8943ecb548 100644 --- a/spring-mvc-java/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-mvc-java/src/test/java/com/baeldung/SpringContextTest.java @@ -3,15 +3,12 @@ package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.config.AppInitializer; +import com.baeldung.config.TestConfig; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { AppInitializer.class }, loader = AnnotationConfigContextLoader.class) -@WebAppConfiguration +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = {TestConfig.class}) public class SpringContextTest { @Test diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java b/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java new file mode 100644 index 0000000000..f16d5f877f --- /dev/null +++ b/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/SpringListValidationApplication.java @@ -0,0 +1,17 @@ +package com.baeldung.validation.listvalidation; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@ComponentScan(basePackages = "com.baeldung.validation.listvalidation") +@Configuration +@SpringBootApplication +public class SpringListValidationApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringListValidationApplication.class, args); + } + +} diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraint.java b/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraint.java new file mode 100644 index 0000000000..b5adab5d86 --- /dev/null +++ b/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraint.java @@ -0,0 +1,18 @@ +package com.baeldung.validation.listvalidation.constraint; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +import javax.validation.Constraint; +import javax.validation.Payload; + +@Constraint(validatedBy = MaxSizeConstraintValidator.class) +@Retention(RetentionPolicy.RUNTIME) +public @interface MaxSizeConstraint { + + String message() default "The input list cannot contain more than 4 movies."; + + Class[] groups() default {}; + + Class[] payload() default {}; +} diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraintValidator.java b/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraintValidator.java new file mode 100644 index 0000000000..0154fb636a --- /dev/null +++ b/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraintValidator.java @@ -0,0 +1,21 @@ +package com.baeldung.validation.listvalidation.constraint; + +import java.util.List; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; + +import com.baeldung.validation.listvalidation.model.Movie; + +public class MaxSizeConstraintValidator implements ConstraintValidator> { + + @Override + public boolean isValid(List values, ConstraintValidatorContext context) { + boolean isValid = true; + if (values.size() > 4) { + isValid = false; + } + return isValid; + } + +} diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/controller/MovieController.java b/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/controller/MovieController.java new file mode 100644 index 0000000000..45639cf303 --- /dev/null +++ b/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/controller/MovieController.java @@ -0,0 +1,31 @@ +package com.baeldung.validation.listvalidation.controller; + +import java.util.List; + +import javax.validation.Valid; +import javax.validation.constraints.NotEmpty; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.validation.annotation.Validated; +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.RestController; + +import com.baeldung.validation.listvalidation.constraint.MaxSizeConstraint; +import com.baeldung.validation.listvalidation.model.Movie; +import com.baeldung.validation.listvalidation.service.MovieService; + +@Validated +@RestController +@RequestMapping("/movies") +public class MovieController { + + @Autowired + private MovieService movieService; + + @PostMapping + public void addAll(@RequestBody @NotEmpty(message = "Input movie list cannot be empty.") @MaxSizeConstraint List<@Valid Movie> movies) { + movieService.addAll(movies); + } +} diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/exception/ConstraintViolationExceptionHandler.java b/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/exception/ConstraintViolationExceptionHandler.java new file mode 100644 index 0000000000..742be27f61 --- /dev/null +++ b/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/exception/ConstraintViolationExceptionHandler.java @@ -0,0 +1,36 @@ +package com.baeldung.validation.listvalidation.exception; + +import java.util.Set; + +import javax.validation.ConstraintViolation; +import javax.validation.ConstraintViolationException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class ConstraintViolationExceptionHandler { + + private final Logger logger = LoggerFactory.getLogger(ConstraintViolationExceptionHandler.class); + + @ExceptionHandler(ConstraintViolationException.class) + public ResponseEntity handle(ConstraintViolationException constraintViolationException) { + Set> violations = constraintViolationException.getConstraintViolations(); + String errorMessage = ""; + if (!violations.isEmpty()) { + StringBuilder builder = new StringBuilder(); + violations.forEach(violation -> builder.append("\n" + violation.getMessage())); + errorMessage = builder.toString(); + } else { + errorMessage = "ConstraintViolationException occured."; + } + + logger.error(errorMessage); + return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST); + } + +} diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/model/Movie.java b/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/model/Movie.java new file mode 100644 index 0000000000..f5a49877bf --- /dev/null +++ b/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/model/Movie.java @@ -0,0 +1,40 @@ +package com.baeldung.validation.listvalidation.model; + +import java.util.UUID; + +import javax.validation.constraints.NotEmpty; + +public class Movie { + + private String id; + + @NotEmpty(message = "Movie name cannot be empty.") + private String name; + + public Movie(String name) { + this.id = UUID.randomUUID() + .toString(); + this.name = name; + } + + public Movie(){ + + } + + 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-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/service/MovieService.java b/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/service/MovieService.java new file mode 100644 index 0000000000..0339df595d --- /dev/null +++ b/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/service/MovieService.java @@ -0,0 +1,55 @@ +package com.baeldung.validation.listvalidation.service; + +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import com.baeldung.validation.listvalidation.model.Movie; + +@Service +public class MovieService { + + private final Logger logger = LoggerFactory.getLogger(MovieService.class); + + private static List moviesData; + + static { + moviesData = new ArrayList<>(); + + Movie m1 = new Movie("MovieABC"); + moviesData.add(m1); + + Movie m2 = new Movie("MovieDEF"); + moviesData.add(m2); + + } + + public Movie get(String name) { + Movie movie = null; + for (Movie m : moviesData) { + if (name.equalsIgnoreCase(m.getName())) { + movie = m; + logger.info("Found movie with name {} : {} ", name, movie); + } + } + + return movie; + } + + public void add(Movie movie) { + if (get(movie.getName()) == null) { + moviesData.add(movie); + logger.info("Added new movie - {}", movie.getName()); + } + } + + public void addAll(List movies) { + for (Movie movie : movies) { + add(movie); + } + } + +} diff --git a/spring-mvc-simple-2/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java b/spring-mvc-simple-2/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java new file mode 100644 index 0000000000..cddc6c6bd9 --- /dev/null +++ b/spring-mvc-simple-2/src/test/java/com/baeldung/validation/listvalidation/MovieControllerIntegrationTest.java @@ -0,0 +1,83 @@ +package com.baeldung.validation.listvalidation; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import com.baeldung.validation.listvalidation.model.Movie; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringListValidationApplication.class) +@AutoConfigureMockMvc +public class MovieControllerIntegrationTest { + + @Autowired + private MockMvc mvc; + + ObjectMapper objectMapper = new ObjectMapper(); + + @Test + public void givenValidMovieList_whenAddingMovieList_thenIsOK() throws Exception { + List movies = new ArrayList<>(); + Movie movie = new Movie("Movie3"); + movies.add(movie); + mvc.perform(MockMvcRequestBuilders.post("/movies") + .contentType(MediaType.APPLICATION_JSON_UTF8) + .content(objectMapper.writeValueAsString(movies))) + .andExpect(MockMvcResultMatchers.status() + .isOk()); + } + + @Test + public void givenEmptyMovieList_whenAddingMovieList_thenThrowBadRequest() throws Exception { + List movies = new ArrayList<>(); + mvc.perform(MockMvcRequestBuilders.post("/movies") + .contentType(MediaType.APPLICATION_JSON_UTF8) + .content(objectMapper.writeValueAsString(movies))) + .andExpect(MockMvcResultMatchers.status() + .isBadRequest()); + } + + @Test + public void givenEmptyMovieName_whenAddingMovieList_thenThrowBadRequest() throws Exception { + Movie movie = new Movie(""); + mvc.perform(MockMvcRequestBuilders.post("/movies") + .contentType(MediaType.APPLICATION_JSON_UTF8) + .content(objectMapper.writeValueAsString(Arrays.asList(movie)))) + .andExpect(MockMvcResultMatchers.status() + .isBadRequest()); + } + + @Test + public void given5MoviesInputList_whenAddingMovieList_thenThrowBadRequest() throws Exception { + Movie movie1 = new Movie("Movie1"); + Movie movie2 = new Movie("Movie2"); + Movie movie3 = new Movie("Movie3"); + Movie movie4 = new Movie("Movie4"); + Movie movie5 = new Movie("Movie5"); + List movies = new ArrayList<>(); + movies.add(movie1); + movies.add(movie2); + movies.add(movie3); + movies.add(movie4); + movies.add(movie5); + mvc.perform(MockMvcRequestBuilders.post("/movies") + .contentType(MediaType.APPLICATION_JSON_UTF8) + .content(objectMapper.writeValueAsString(movies))) + .andExpect(MockMvcResultMatchers.status() + .isBadRequest()); + } + +} diff --git a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/RequestParamController.java b/spring-mvc-simple/src/main/java/com/baeldung/spring/requestparam/RequestParamController.java similarity index 96% rename from spring-mvc-simple/src/main/java/com/baeldung/spring/controller/RequestParamController.java rename to spring-mvc-simple/src/main/java/com/baeldung/spring/requestparam/RequestParamController.java index a9846f1ba9..bcb1fe5a82 100644 --- a/spring-mvc-simple/src/main/java/com/baeldung/spring/controller/RequestParamController.java +++ b/spring-mvc-simple/src/main/java/com/baeldung/spring/requestparam/RequestParamController.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.controller; +package com.baeldung.spring.requestparam; import java.util.List; import java.util.Map; @@ -47,7 +47,7 @@ public class RequestParamController { @GetMapping("/api/foos4") @ResponseBody public String getFoos4(@RequestParam List id){ - return "ID are " + id; + return "IDs are " + id; } @GetMapping("/foos/{id}") diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GreetingController.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GreetingController.java new file mode 100644 index 0000000000..dfa50fcb26 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/GreetingController.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.controller; + +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 +public class GreetingController { + + @RequestMapping(value = "/greeting", method = RequestMethod.GET) + public String get(ModelMap model) { + model.addAttribute("message", "Hello, World!"); + return "greeting"; + } +} \ No newline at end of file diff --git a/spring-mvc-xml/src/main/webapp/WEB-INF/view/greeting.jsp b/spring-mvc-xml/src/main/webapp/WEB-INF/view/greeting.jsp new file mode 100644 index 0000000000..ac17c75ab7 --- /dev/null +++ b/spring-mvc-xml/src/main/webapp/WEB-INF/view/greeting.jsp @@ -0,0 +1,9 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Greeting + + +

    ${message}

    + + \ No newline at end of file diff --git a/spring-rest-compress/README.md b/spring-rest-compress/README.md new file mode 100644 index 0000000000..238c28e4b5 --- /dev/null +++ b/spring-rest-compress/README.md @@ -0,0 +1,5 @@ +========================================================================= +## How to compress requests using the Spring RestTemplate Example Project + +### Relevant Articles: +- [How to compress requests using the Spring RestTemplate]() diff --git a/spring-rest-compress/pom.xml b/spring-rest-compress/pom.xml new file mode 100644 index 0000000000..d5afc5708d --- /dev/null +++ b/spring-rest-compress/pom.xml @@ -0,0 +1,66 @@ + + + 4.0.0 + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../parent-boot-2 + + com.baeldung + spring-rest-compress + 0.0.1-SNAPSHOT + spring-rest-compress + + + 1.8 + 2.6 + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + + org.springframework.boot + spring-boot-starter-jetty + + + + org.apache.httpcomponents + httpclient + + + + commons-io + commons-io + ${commons-io.version} + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/CompressingClientHttpRequestInterceptor.java b/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/CompressingClientHttpRequestInterceptor.java new file mode 100644 index 0000000000..7d5326246d --- /dev/null +++ b/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/CompressingClientHttpRequestInterceptor.java @@ -0,0 +1,38 @@ +package org.baeldung.spring.rest.compress; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpHeaders; +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; + +public class CompressingClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { + + private static final Logger LOG = LoggerFactory.getLogger(CompressingClientHttpRequestInterceptor.class); + + private static final String GZIP_ENCODING = "gzip"; + + /** + * Compress a request body using Gzip and add Http headers. + * + * @param req + * @param body + * @param exec + * @return + * @throws IOException + */ + @Override + public ClientHttpResponse intercept(HttpRequest req, byte[] body, ClientHttpRequestExecution exec) + throws IOException { + LOG.info("Compressing request..."); + HttpHeaders httpHeaders = req.getHeaders(); + httpHeaders.add(HttpHeaders.CONTENT_ENCODING, GZIP_ENCODING); + httpHeaders.add(HttpHeaders.ACCEPT_ENCODING, GZIP_ENCODING); + return exec.execute(req, GzipUtils.compress(body)); + } + +} diff --git a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/GzipUtils.java b/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/GzipUtils.java new file mode 100644 index 0000000000..75420ca6d8 --- /dev/null +++ b/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/GzipUtils.java @@ -0,0 +1,52 @@ +package org.baeldung.spring.rest.compress; + +import org.apache.commons.codec.Charsets; +import org.apache.commons.io.IOUtils; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +public class GzipUtils { + + /** + * Gzip a string. + * + * @param text + * @return + * @throws Exception + */ + public static byte[] compress(String text) throws Exception { + return GzipUtils.compress(text.getBytes(Charsets.UTF_8)); + } + + /** + * Gzip a byte array. + * + * @param body + * @return + * @throws IOException + */ + public static byte[] compress(byte[] body) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(baos)) { + gzipOutputStream.write(body); + } + return baos.toByteArray(); + } + + /** + * Decompress a Gzipped byte array to a String. + * + * @param body + * @return + * @throws IOException + */ + public static String decompress(byte[] body) throws IOException { + try (GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(body))) { + return IOUtils.toString(gzipInputStream, Charsets.UTF_8); + } + } +} diff --git a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/JettyWebServerConfiguration.java b/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/JettyWebServerConfiguration.java new file mode 100644 index 0000000000..784814b04d --- /dev/null +++ b/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/JettyWebServerConfiguration.java @@ -0,0 +1,38 @@ +package org.baeldung.spring.rest.compress; + +import org.eclipse.jetty.server.handler.HandlerCollection; +import org.eclipse.jetty.server.handler.gzip.GzipHandler; +import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Configure Jetty web server so it handles compressed requests. + */ +@Configuration +public class JettyWebServerConfiguration { + + private static final int MIN_BYTES = 1; + + /** + * Customise the Jetty web server to automatically decompress requests. + */ + @Bean + public JettyServletWebServerFactory jettyServletWebServerFactory() { + + JettyServletWebServerFactory factory = new JettyServletWebServerFactory(); + factory.addServerCustomizers(server -> { + + GzipHandler gzipHandler = new GzipHandler(); + // Enable request decompression + gzipHandler.setInflateBufferSize(MIN_BYTES); + gzipHandler.setHandler(server.getHandler()); + + HandlerCollection handlerCollection = new HandlerCollection(gzipHandler); + server.setHandler(handlerCollection); + }); + + return factory; + } + +} diff --git a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/Message.java b/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/Message.java new file mode 100644 index 0000000000..d3450b227c --- /dev/null +++ b/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/Message.java @@ -0,0 +1,29 @@ +package org.baeldung.spring.rest.compress; + +public class Message { + + private String text; + + public Message() { + } + + public Message(String text) { + this.text = text; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("Message {"); + sb.append("text='").append(text).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/MessageController.java b/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/MessageController.java new file mode 100644 index 0000000000..657c3cfec8 --- /dev/null +++ b/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/MessageController.java @@ -0,0 +1,38 @@ +package org.baeldung.spring.rest.compress; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Map; + +@RestController +public class MessageController { + + protected static final String PROCESSED = "Processed "; + + protected static final String REQUEST_MAPPING = "process"; + + private static final Logger LOG = LoggerFactory.getLogger(MessageController.class); + + /** + * A simple endpoint that responds with "Processed " + supplied Message content. + * + * @param headers + * @param message + * @return + */ + @PostMapping(value = REQUEST_MAPPING) + public ResponseEntity processMessage(@RequestHeader Map headers, + @RequestBody Message message) { + + // Print headers + headers.forEach((k, v) -> LOG.info(k + "=" + v)); + + return ResponseEntity.ok(PROCESSED + message.getText()); + } +} diff --git a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/RestTemplateConfiguration.java b/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/RestTemplateConfiguration.java new file mode 100644 index 0000000000..e1d0f985d9 --- /dev/null +++ b/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/RestTemplateConfiguration.java @@ -0,0 +1,21 @@ +package org.baeldung.spring.rest.compress; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +@Configuration +public class RestTemplateConfiguration { + + /** + * A RestTemplate that compresses requests. + * + * @return RestTemplate + */ + @Bean + public RestTemplate getRestTemplate() { + RestTemplate restTemplate = new RestTemplate(); + restTemplate.getInterceptors().add(new CompressingClientHttpRequestInterceptor()); + return restTemplate; + } +} diff --git a/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/SpringCompressRequestApplication.java b/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/SpringCompressRequestApplication.java new file mode 100644 index 0000000000..3082e3c277 --- /dev/null +++ b/spring-rest-compress/src/main/java/org/baeldung/spring/rest/compress/SpringCompressRequestApplication.java @@ -0,0 +1,15 @@ +package org.baeldung.spring.rest.compress; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@EnableAutoConfiguration +public class SpringCompressRequestApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringCompressRequestApplication.class, args); + } + +} diff --git a/spring-rest-compress/src/test/java/org/baeldung/spring/rest/compress/GzipUtilsUnitTest.java b/spring-rest-compress/src/test/java/org/baeldung/spring/rest/compress/GzipUtilsUnitTest.java new file mode 100644 index 0000000000..d238c9ec7c --- /dev/null +++ b/spring-rest-compress/src/test/java/org/baeldung/spring/rest/compress/GzipUtilsUnitTest.java @@ -0,0 +1,19 @@ +package org.baeldung.spring.rest.compress; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class GzipUtilsUnitTest { + + @Test + public void givenCompressedText_whenDecompressed_thenSuccessful() throws Exception { + final String expectedText = "Hello Baeldung!"; + byte[] compressedText = GzipUtils.compress(expectedText); + String decompressedText = GzipUtils.decompress(compressedText); + assertNotNull(compressedText); + assertEquals(expectedText, decompressedText); + } + +} \ No newline at end of file diff --git a/spring-rest-compress/src/test/java/org/baeldung/spring/rest/compress/MessageControllerUnitTest.java b/spring-rest-compress/src/test/java/org/baeldung/spring/rest/compress/MessageControllerUnitTest.java new file mode 100644 index 0000000000..9658204917 --- /dev/null +++ b/spring-rest-compress/src/test/java/org/baeldung/spring/rest/compress/MessageControllerUnitTest.java @@ -0,0 +1,56 @@ +package org.baeldung.spring.rest.compress; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestTemplate; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class MessageControllerUnitTest { + + private static final Logger LOG = LoggerFactory.getLogger(MessageControllerUnitTest.class); + + @Autowired + private RestTemplate restTemplate; + + @LocalServerPort + private int randomServerPort; + + /** + * As a further test you can intercept the request body, using a tool like + * Wireshark, to see the request body is actually gzipped. + * + * @throws Exception + */ + @Test + public void givenRestTemplate_whenPostCompressedRequest_thenRespondsSuccessfully() throws Exception { + + final String text = "Hello Baeldung!"; + Message message = new Message(text); + + HttpEntity request = new HttpEntity<>(message); + String uri = String.format("http://localhost:%s/%s", randomServerPort, MessageController.REQUEST_MAPPING); + + ResponseEntity responseEntity = restTemplate.postForEntity(uri, request, String.class); + + String response = responseEntity.getBody(); + LOG.info("Got response [{}]", response); + + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + assertNotNull(response); + assertEquals(MessageController.PROCESSED + text, response); + } + +} diff --git a/spring-rest-simple/src/main/java/com/baeldung/config/MvcConfig.java b/spring-rest-simple/src/main/java/com/baeldung/config/MvcConfig.java index d169f7e9d4..48b627a344 100644 --- a/spring-rest-simple/src/main/java/com/baeldung/config/MvcConfig.java +++ b/spring-rest-simple/src/main/java/com/baeldung/config/MvcConfig.java @@ -26,7 +26,7 @@ import java.util.List; */ @Configuration @EnableWebMvc -@ComponentScan({ "com.baeldung.web" }) +@ComponentScan({ "com.baeldung.web", "com.baeldung.requestmapping" }) public class MvcConfig implements WebMvcConfigurer { public MvcConfig() { @@ -66,7 +66,6 @@ public class MvcConfig implements WebMvcConfigurer { public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.defaultContentType(MediaType.APPLICATION_JSON); } - @Override public void addCorsMappings(CorsRegistry registry) { diff --git a/spring-rest-simple/src/main/java/com/baeldung/web/controller/BarMappingExamplesController.java b/spring-rest-simple/src/main/java/com/baeldung/requestmapping/BarMappingExamplesController.java similarity index 97% rename from spring-rest-simple/src/main/java/com/baeldung/web/controller/BarMappingExamplesController.java rename to spring-rest-simple/src/main/java/com/baeldung/requestmapping/BarMappingExamplesController.java index 3611a4e6cc..e238c545cf 100644 --- a/spring-rest-simple/src/main/java/com/baeldung/web/controller/BarMappingExamplesController.java +++ b/spring-rest-simple/src/main/java/com/baeldung/requestmapping/BarMappingExamplesController.java @@ -1,4 +1,4 @@ -package com.baeldung.web.controller; +package com.baeldung.requestmapping; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-rest-simple/src/main/java/com/baeldung/web/controller/BazzNewMappingsExampleController.java b/spring-rest-simple/src/main/java/com/baeldung/requestmapping/BazzNewMappingsExampleController.java similarity index 98% rename from spring-rest-simple/src/main/java/com/baeldung/web/controller/BazzNewMappingsExampleController.java rename to spring-rest-simple/src/main/java/com/baeldung/requestmapping/BazzNewMappingsExampleController.java index 6c7da0296f..0c64006fd4 100644 --- a/spring-rest-simple/src/main/java/com/baeldung/web/controller/BazzNewMappingsExampleController.java +++ b/spring-rest-simple/src/main/java/com/baeldung/requestmapping/BazzNewMappingsExampleController.java @@ -1,4 +1,4 @@ -package com.baeldung.web.controller; +package com.baeldung.requestmapping; import java.util.Arrays; import java.util.List; diff --git a/spring-rest-simple/src/main/java/com/baeldung/web/controller/FooMappingExamplesController.java b/spring-rest-simple/src/main/java/com/baeldung/requestmapping/FooMappingExamplesController.java similarity index 98% rename from spring-rest-simple/src/main/java/com/baeldung/web/controller/FooMappingExamplesController.java rename to spring-rest-simple/src/main/java/com/baeldung/requestmapping/FooMappingExamplesController.java index ec75e4c859..2c11e36141 100644 --- a/spring-rest-simple/src/main/java/com/baeldung/web/controller/FooMappingExamplesController.java +++ b/spring-rest-simple/src/main/java/com/baeldung/requestmapping/FooMappingExamplesController.java @@ -1,4 +1,4 @@ -package com.baeldung.web.controller; +package com.baeldung.requestmapping; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; diff --git a/spring-rest-simple/src/test/java/com/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java b/spring-rest-simple/src/test/java/com/baeldung/requestmapping/BazzNewMappingsExampleIntegrationTest.java similarity index 98% rename from spring-rest-simple/src/test/java/com/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java rename to spring-rest-simple/src/test/java/com/baeldung/requestmapping/BazzNewMappingsExampleIntegrationTest.java index 4f0395e914..a6039b54c7 100644 --- a/spring-rest-simple/src/test/java/com/baeldung/web/test/BazzNewMappingsExampleIntegrationTest.java +++ b/spring-rest-simple/src/test/java/com/baeldung/requestmapping/BazzNewMappingsExampleIntegrationTest.java @@ -1,5 +1,5 @@ -package com.baeldung.web.test; +package com.baeldung.requestmapping; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; diff --git a/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java b/spring-resttemplate/src/test/java/org/baeldung/resttemplate/RestTemplateBasicLiveTest.java similarity index 99% rename from spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java rename to spring-resttemplate/src/test/java/org/baeldung/resttemplate/RestTemplateBasicLiveTest.java index ff3034a50d..54e416d008 100644 --- a/spring-resttemplate/src/test/java/org/baeldung/client/RestTemplateBasicLiveTest.java +++ b/spring-resttemplate/src/test/java/org/baeldung/resttemplate/RestTemplateBasicLiveTest.java @@ -1,4 +1,4 @@ -package org.baeldung.client; +package org.baeldung.resttemplate; import static org.apache.commons.codec.binary.Base64.encodeBase64; import static org.baeldung.client.Consts.APPLICATION_PORT; diff --git a/spring-security-core/src/main/java/org/baeldung/app/App.java b/spring-security-core/src/main/java/com/baeldung/app/App.java similarity index 92% rename from spring-security-core/src/main/java/org/baeldung/app/App.java rename to spring-security-core/src/main/java/com/baeldung/app/App.java index bf719b3b12..d23df9adef 100644 --- a/spring-security-core/src/main/java/org/baeldung/app/App.java +++ b/spring-security-core/src/main/java/com/baeldung/app/App.java @@ -1,4 +1,4 @@ -package org.baeldung.app; +package com.baeldung.app; import javax.servlet.Filter; @@ -12,9 +12,9 @@ import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; @SpringBootApplication -@EnableJpaRepositories("org.baeldung.repository") -@ComponentScan("org.baeldung") -@EntityScan("org.baeldung.entity") +@EnableJpaRepositories("com.baeldung.repository") +@ComponentScan("com.baeldung") +@EntityScan("com.baeldung.entity") public class App extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(App.class, args); diff --git a/spring-security-core/src/main/java/org/baeldung/auditing/ExposeAttemptedPathAuthorizationAuditListener.java b/spring-security-core/src/main/java/com/baeldung/auditing/ExposeAttemptedPathAuthorizationAuditListener.java similarity index 98% rename from spring-security-core/src/main/java/org/baeldung/auditing/ExposeAttemptedPathAuthorizationAuditListener.java rename to spring-security-core/src/main/java/com/baeldung/auditing/ExposeAttemptedPathAuthorizationAuditListener.java index bc36ac08b3..615d14584f 100644 --- a/spring-security-core/src/main/java/org/baeldung/auditing/ExposeAttemptedPathAuthorizationAuditListener.java +++ b/spring-security-core/src/main/java/com/baeldung/auditing/ExposeAttemptedPathAuthorizationAuditListener.java @@ -1,4 +1,4 @@ -package org.baeldung.auditing; +package com.baeldung.auditing; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.actuate.security.AbstractAuthorizationAuditListener; diff --git a/spring-security-core/src/main/java/org/baeldung/auditing/LoginAttemptsLogger.java b/spring-security-core/src/main/java/com/baeldung/auditing/LoginAttemptsLogger.java similarity index 97% rename from spring-security-core/src/main/java/org/baeldung/auditing/LoginAttemptsLogger.java rename to spring-security-core/src/main/java/com/baeldung/auditing/LoginAttemptsLogger.java index bf0781bced..d06c3e24e1 100644 --- a/spring-security-core/src/main/java/org/baeldung/auditing/LoginAttemptsLogger.java +++ b/spring-security-core/src/main/java/com/baeldung/auditing/LoginAttemptsLogger.java @@ -1,4 +1,4 @@ -package org.baeldung.auditing; +package com.baeldung.auditing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-security-core/src/main/java/org/baeldung/config/DatabaseLoader.java b/spring-security-core/src/main/java/com/baeldung/config/DatabaseLoader.java similarity index 86% rename from spring-security-core/src/main/java/org/baeldung/config/DatabaseLoader.java rename to spring-security-core/src/main/java/com/baeldung/config/DatabaseLoader.java index e311f62fff..7f22c3ec99 100644 --- a/spring-security-core/src/main/java/org/baeldung/config/DatabaseLoader.java +++ b/spring-security-core/src/main/java/com/baeldung/config/DatabaseLoader.java @@ -1,11 +1,12 @@ -package org.baeldung.config; +package com.baeldung.config; -import org.baeldung.entity.Task; -import org.baeldung.repository.TaskRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; +import com.baeldung.entity.Task; +import com.baeldung.repository.TaskRepository; + @Component public class DatabaseLoader implements CommandLineRunner { diff --git a/spring-security-core/src/main/java/org/baeldung/config/WebSecurityConfig.java b/spring-security-core/src/main/java/com/baeldung/config/WebSecurityConfig.java similarity index 98% rename from spring-security-core/src/main/java/org/baeldung/config/WebSecurityConfig.java rename to spring-security-core/src/main/java/com/baeldung/config/WebSecurityConfig.java index df7c7d1611..be11a0fde5 100644 --- a/spring-security-core/src/main/java/org/baeldung/config/WebSecurityConfig.java +++ b/spring-security-core/src/main/java/com/baeldung/config/WebSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.config; +package com.baeldung.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; diff --git a/spring-security-core/src/main/java/org/baeldung/controller/TaskController.java b/spring-security-core/src/main/java/com/baeldung/controller/TaskController.java similarity index 90% rename from spring-security-core/src/main/java/org/baeldung/controller/TaskController.java rename to spring-security-core/src/main/java/com/baeldung/controller/TaskController.java index d99109c543..91156354b1 100644 --- a/spring-security-core/src/main/java/org/baeldung/controller/TaskController.java +++ b/spring-security-core/src/main/java/com/baeldung/controller/TaskController.java @@ -1,7 +1,5 @@ -package org.baeldung.controller; +package com.baeldung.controller; -import org.baeldung.entity.Task; -import org.baeldung.service.TaskService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; @@ -9,6 +7,9 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; +import com.baeldung.entity.Task; +import com.baeldung.service.TaskService; + @Controller @RequestMapping("api/tasks") public class TaskController { diff --git a/spring-security-core/src/main/java/org/baeldung/entity/Task.java b/spring-security-core/src/main/java/com/baeldung/entity/Task.java similarity index 96% rename from spring-security-core/src/main/java/org/baeldung/entity/Task.java rename to spring-security-core/src/main/java/com/baeldung/entity/Task.java index 5d3321ef2e..9103c342cc 100644 --- a/spring-security-core/src/main/java/org/baeldung/entity/Task.java +++ b/spring-security-core/src/main/java/com/baeldung/entity/Task.java @@ -1,4 +1,4 @@ -package org.baeldung.entity; +package com.baeldung.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/spring-security-core/src/main/java/org/baeldung/filter/CustomFilter.java b/spring-security-core/src/main/java/com/baeldung/filter/CustomFilter.java similarity index 97% rename from spring-security-core/src/main/java/org/baeldung/filter/CustomFilter.java rename to spring-security-core/src/main/java/com/baeldung/filter/CustomFilter.java index 35596eae16..e748b373b7 100644 --- a/spring-security-core/src/main/java/org/baeldung/filter/CustomFilter.java +++ b/spring-security-core/src/main/java/com/baeldung/filter/CustomFilter.java @@ -1,4 +1,4 @@ -package org.baeldung.filter; +package com.baeldung.filter; import java.io.IOException; diff --git a/spring-security-core/src/main/java/org/baeldung/methodsecurity/annotation/IsViewer.java b/spring-security-core/src/main/java/com/baeldung/methodsecurity/annotation/IsViewer.java similarity index 85% rename from spring-security-core/src/main/java/org/baeldung/methodsecurity/annotation/IsViewer.java rename to spring-security-core/src/main/java/com/baeldung/methodsecurity/annotation/IsViewer.java index 711784adbb..bde4456f8e 100644 --- a/spring-security-core/src/main/java/org/baeldung/methodsecurity/annotation/IsViewer.java +++ b/spring-security-core/src/main/java/com/baeldung/methodsecurity/annotation/IsViewer.java @@ -1,4 +1,4 @@ -package org.baeldung.methodsecurity.annotation; +package com.baeldung.methodsecurity.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/spring-security-core/src/main/java/org/baeldung/methodsecurity/config/MethodSecurityConfig.java b/spring-security-core/src/main/java/com/baeldung/methodsecurity/config/MethodSecurityConfig.java similarity index 91% rename from spring-security-core/src/main/java/org/baeldung/methodsecurity/config/MethodSecurityConfig.java rename to spring-security-core/src/main/java/com/baeldung/methodsecurity/config/MethodSecurityConfig.java index 4749c730dc..239f7067a4 100644 --- a/spring-security-core/src/main/java/org/baeldung/methodsecurity/config/MethodSecurityConfig.java +++ b/spring-security-core/src/main/java/com/baeldung/methodsecurity/config/MethodSecurityConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.methodsecurity.config; +package com.baeldung.methodsecurity.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; diff --git a/spring-security-core/src/main/java/org/baeldung/methodsecurity/entity/CustomUser.java b/spring-security-core/src/main/java/com/baeldung/methodsecurity/entity/CustomUser.java similarity index 91% rename from spring-security-core/src/main/java/org/baeldung/methodsecurity/entity/CustomUser.java rename to spring-security-core/src/main/java/com/baeldung/methodsecurity/entity/CustomUser.java index fb9174befa..7daaef5984 100644 --- a/spring-security-core/src/main/java/org/baeldung/methodsecurity/entity/CustomUser.java +++ b/spring-security-core/src/main/java/com/baeldung/methodsecurity/entity/CustomUser.java @@ -1,4 +1,4 @@ -package org.baeldung.methodsecurity.entity; +package com.baeldung.methodsecurity.entity; import java.util.Collection; diff --git a/spring-security-core/src/main/java/org/baeldung/methodsecurity/repository/UserRoleRepository.java b/spring-security-core/src/main/java/com/baeldung/methodsecurity/repository/UserRoleRepository.java similarity index 92% rename from spring-security-core/src/main/java/org/baeldung/methodsecurity/repository/UserRoleRepository.java rename to spring-security-core/src/main/java/com/baeldung/methodsecurity/repository/UserRoleRepository.java index fc1a32289d..eef39189a7 100644 --- a/spring-security-core/src/main/java/org/baeldung/methodsecurity/repository/UserRoleRepository.java +++ b/spring-security-core/src/main/java/com/baeldung/methodsecurity/repository/UserRoleRepository.java @@ -1,16 +1,17 @@ -package org.baeldung.methodsecurity.repository; +package com.baeldung.methodsecurity.repository; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.baeldung.methodsecurity.entity.CustomUser; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; +import com.baeldung.methodsecurity.entity.CustomUser; + @Service public class UserRoleRepository { diff --git a/spring-security-core/src/main/java/org/baeldung/methodsecurity/service/CustomUserDetailsService.java b/spring-security-core/src/main/java/com/baeldung/methodsecurity/service/CustomUserDetailsService.java similarity index 80% rename from spring-security-core/src/main/java/org/baeldung/methodsecurity/service/CustomUserDetailsService.java rename to spring-security-core/src/main/java/com/baeldung/methodsecurity/service/CustomUserDetailsService.java index 91171468bb..685621b55f 100644 --- a/spring-security-core/src/main/java/org/baeldung/methodsecurity/service/CustomUserDetailsService.java +++ b/spring-security-core/src/main/java/com/baeldung/methodsecurity/service/CustomUserDetailsService.java @@ -1,11 +1,12 @@ -package org.baeldung.methodsecurity.service; +package com.baeldung.methodsecurity.service; -import org.baeldung.methodsecurity.repository.UserRoleRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.stereotype.Service; +import com.baeldung.methodsecurity.repository.UserRoleRepository; + @Service("userDetailService") public class CustomUserDetailsService implements UserDetailsService { diff --git a/spring-security-core/src/main/java/org/baeldung/methodsecurity/service/SystemService.java b/spring-security-core/src/main/java/com/baeldung/methodsecurity/service/SystemService.java similarity index 84% rename from spring-security-core/src/main/java/org/baeldung/methodsecurity/service/SystemService.java rename to spring-security-core/src/main/java/com/baeldung/methodsecurity/service/SystemService.java index 5f29d7dee6..623d51d34f 100644 --- a/spring-security-core/src/main/java/org/baeldung/methodsecurity/service/SystemService.java +++ b/spring-security-core/src/main/java/com/baeldung/methodsecurity/service/SystemService.java @@ -1,4 +1,4 @@ -package org.baeldung.methodsecurity.service; +package com.baeldung.methodsecurity.service; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; diff --git a/spring-security-core/src/main/java/org/baeldung/methodsecurity/service/UserRoleService.java b/spring-security-core/src/main/java/com/baeldung/methodsecurity/service/UserRoleService.java similarity index 92% rename from spring-security-core/src/main/java/org/baeldung/methodsecurity/service/UserRoleService.java rename to spring-security-core/src/main/java/com/baeldung/methodsecurity/service/UserRoleService.java index 30bbdbc10f..4d090fd90c 100644 --- a/spring-security-core/src/main/java/org/baeldung/methodsecurity/service/UserRoleService.java +++ b/spring-security-core/src/main/java/com/baeldung/methodsecurity/service/UserRoleService.java @@ -1,13 +1,10 @@ -package org.baeldung.methodsecurity.service; +package com.baeldung.methodsecurity.service; import java.util.List; import java.util.stream.Collectors; import javax.annotation.security.RolesAllowed; -import org.baeldung.methodsecurity.annotation.IsViewer; -import org.baeldung.methodsecurity.entity.CustomUser; -import org.baeldung.methodsecurity.repository.UserRoleRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.security.access.prepost.PostAuthorize; @@ -18,6 +15,10 @@ import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; +import com.baeldung.methodsecurity.annotation.IsViewer; +import com.baeldung.methodsecurity.entity.CustomUser; +import com.baeldung.methodsecurity.repository.UserRoleRepository; + @Service public class UserRoleService { diff --git a/spring-security-core/src/main/java/org/baeldung/repository/TaskRepository.java b/spring-security-core/src/main/java/com/baeldung/repository/TaskRepository.java similarity index 66% rename from spring-security-core/src/main/java/org/baeldung/repository/TaskRepository.java rename to spring-security-core/src/main/java/com/baeldung/repository/TaskRepository.java index 651b11684f..afb999719c 100644 --- a/spring-security-core/src/main/java/org/baeldung/repository/TaskRepository.java +++ b/spring-security-core/src/main/java/com/baeldung/repository/TaskRepository.java @@ -1,8 +1,9 @@ -package org.baeldung.repository; +package com.baeldung.repository; -import org.baeldung.entity.Task; import org.springframework.data.repository.CrudRepository; +import com.baeldung.entity.Task; + public interface TaskRepository extends CrudRepository { } diff --git a/spring-security-core/src/main/java/org/baeldung/service/TaskService.java b/spring-security-core/src/main/java/com/baeldung/service/TaskService.java similarity index 86% rename from spring-security-core/src/main/java/org/baeldung/service/TaskService.java rename to spring-security-core/src/main/java/com/baeldung/service/TaskService.java index 4efa3b0294..1269eb4fd0 100644 --- a/spring-security-core/src/main/java/org/baeldung/service/TaskService.java +++ b/spring-security-core/src/main/java/com/baeldung/service/TaskService.java @@ -1,12 +1,13 @@ -package org.baeldung.service; +package com.baeldung.service; -import org.baeldung.entity.Task; -import org.baeldung.repository.TaskRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PostFilter; import org.springframework.security.access.prepost.PreFilter; import org.springframework.stereotype.Service; +import com.baeldung.entity.Task; +import com.baeldung.repository.TaskRepository; + @Service public class TaskService { diff --git a/spring-security-core/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-core/src/test/java/com/baeldung/SpringContextIntegrationTest.java similarity index 87% rename from spring-security-core/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-security-core/src/test/java/com/baeldung/SpringContextIntegrationTest.java index 5698afa417..1cdff1342c 100644 --- a/spring-security-core/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-security-core/src/test/java/com/baeldung/SpringContextIntegrationTest.java @@ -1,11 +1,12 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.app.App; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.app.App; + @RunWith(SpringRunner.class) @SpringBootTest(classes = App.class) public class SpringContextIntegrationTest { diff --git a/spring-security-core/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-core/src/test/java/com/baeldung/SpringContextTest.java similarity index 87% rename from spring-security-core/src/test/java/org/baeldung/SpringContextTest.java rename to spring-security-core/src/test/java/com/baeldung/SpringContextTest.java index 1707c706ae..bca6450fb1 100644 --- a/spring-security-core/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-security-core/src/test/java/com/baeldung/SpringContextTest.java @@ -1,11 +1,12 @@ -package org.baeldung; +package com.baeldung; -import org.baeldung.app.App; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.app.App; + @RunWith(SpringRunner.class) @SpringBootTest(classes = App.class) public class SpringContextTest { diff --git a/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestClassLevelSecurity.java b/spring-security-core/src/test/java/com/baeldung/methodsecurity/ClassLevelSecurityIntegrationTest.java similarity index 85% rename from spring-security-core/src/test/java/org/baeldung/methodsecurity/TestClassLevelSecurity.java rename to spring-security-core/src/test/java/com/baeldung/methodsecurity/ClassLevelSecurityIntegrationTest.java index 502fd50c46..943bfda72c 100644 --- a/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestClassLevelSecurity.java +++ b/spring-security-core/src/test/java/com/baeldung/methodsecurity/ClassLevelSecurityIntegrationTest.java @@ -1,8 +1,7 @@ -package org.baeldung.methodsecurity; +package com.baeldung.methodsecurity; import static org.junit.Assert.*; -import org.baeldung.methodsecurity.service.SystemService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -13,15 +12,17 @@ import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.methodsecurity.service.SystemService; + @RunWith(SpringRunner.class) @ContextConfiguration -public class TestClassLevelSecurity { +public class ClassLevelSecurityIntegrationTest { @Autowired SystemService systemService; @Configuration - @ComponentScan("org.baeldung.methodsecurity.*") + @ComponentScan("com.baeldung.methodsecurity.*") public static class SpringConfig { } diff --git a/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java b/spring-security-core/src/test/java/com/baeldung/methodsecurity/MethodSecurityIntegrationTest.java similarity index 94% rename from spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java rename to spring-security-core/src/test/java/com/baeldung/methodsecurity/MethodSecurityIntegrationTest.java index 009d9af9fc..81b150f43e 100644 --- a/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestMethodSecurity.java +++ b/spring-security-core/src/test/java/com/baeldung/methodsecurity/MethodSecurityIntegrationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.methodsecurity; +package com.baeldung.methodsecurity; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -6,7 +6,6 @@ import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; -import org.baeldung.methodsecurity.service.UserRoleService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -19,15 +18,17 @@ import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.methodsecurity.service.UserRoleService; + @RunWith(SpringRunner.class) @ContextConfiguration -public class TestMethodSecurity { +public class MethodSecurityIntegrationTest { @Autowired UserRoleService userRoleService; @Configuration - @ComponentScan("org.baeldung.methodsecurity.*") + @ComponentScan("com.baeldung.methodsecurity.*") public static class SpringConfig { } diff --git a/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestWithMockUserAtClassLevel.java b/spring-security-core/src/test/java/com/baeldung/methodsecurity/MockUserAtClassLevelIntegrationTest.java similarity index 79% rename from spring-security-core/src/test/java/org/baeldung/methodsecurity/TestWithMockUserAtClassLevel.java rename to spring-security-core/src/test/java/com/baeldung/methodsecurity/MockUserAtClassLevelIntegrationTest.java index 4df1af8ca9..fead89f75a 100644 --- a/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestWithMockUserAtClassLevel.java +++ b/spring-security-core/src/test/java/com/baeldung/methodsecurity/MockUserAtClassLevelIntegrationTest.java @@ -1,8 +1,7 @@ -package org.baeldung.methodsecurity; +package com.baeldung.methodsecurity; import static org.junit.Assert.assertEquals; -import org.baeldung.methodsecurity.service.UserRoleService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -12,10 +11,12 @@ import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.methodsecurity.service.UserRoleService; + @RunWith(SpringRunner.class) @ContextConfiguration @WithMockUser(username = "john", roles = { "VIEWER" }) -public class TestWithMockUserAtClassLevel { +public class MockUserAtClassLevelIntegrationTest { @Test public void givenRoleViewer_whenCallGetUsername_thenReturnUsername() { @@ -27,7 +28,7 @@ public class TestWithMockUserAtClassLevel { UserRoleService userService; @Configuration - @ComponentScan("org.baeldung.methodsecurity.*") + @ComponentScan("com.baeldung.methodsecurity.*") public static class SpringConfig { } diff --git a/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestWithUserDetails.java b/spring-security-core/src/test/java/com/baeldung/methodsecurity/UserDetailsIntegrationTest.java similarity index 86% rename from spring-security-core/src/test/java/org/baeldung/methodsecurity/TestWithUserDetails.java rename to spring-security-core/src/test/java/com/baeldung/methodsecurity/UserDetailsIntegrationTest.java index 3ef5996554..d43a26a5ff 100644 --- a/spring-security-core/src/test/java/org/baeldung/methodsecurity/TestWithUserDetails.java +++ b/spring-security-core/src/test/java/com/baeldung/methodsecurity/UserDetailsIntegrationTest.java @@ -1,9 +1,7 @@ -package org.baeldung.methodsecurity; +package com.baeldung.methodsecurity; import static org.junit.Assert.assertEquals; -import org.baeldung.methodsecurity.entity.CustomUser; -import org.baeldung.methodsecurity.service.UserRoleService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -14,15 +12,18 @@ import org.springframework.security.test.context.support.WithUserDetails; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.methodsecurity.entity.CustomUser; +import com.baeldung.methodsecurity.service.UserRoleService; + @RunWith(SpringRunner.class) @ContextConfiguration -public class TestWithUserDetails { +public class UserDetailsIntegrationTest { @Autowired UserRoleService userService; @Configuration - @ComponentScan("org.baeldung.methodsecurity.*") + @ComponentScan("com.baeldung.methodsecurity.*") public static class SpringConfig { } diff --git a/spring-security-core/src/test/java/org/baeldung/methodsecurity/WithMockJohnViewer.java b/spring-security-core/src/test/java/com/baeldung/methodsecurity/WithMockJohnViewer.java similarity index 73% rename from spring-security-core/src/test/java/org/baeldung/methodsecurity/WithMockJohnViewer.java rename to spring-security-core/src/test/java/com/baeldung/methodsecurity/WithMockJohnViewer.java index 5e1e882f3d..f05a6bc20e 100644 --- a/spring-security-core/src/test/java/org/baeldung/methodsecurity/WithMockJohnViewer.java +++ b/spring-security-core/src/test/java/com/baeldung/methodsecurity/WithMockJohnViewer.java @@ -1,4 +1,4 @@ -package org.baeldung.methodsecurity; +package com.baeldung.methodsecurity; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; diff --git a/spring-security-core/src/test/java/org/baeldung/test/LiveTest.java b/spring-security-core/src/test/java/com/baeldung/test/LiveTest.java similarity index 98% rename from spring-security-core/src/test/java/org/baeldung/test/LiveTest.java rename to spring-security-core/src/test/java/com/baeldung/test/LiveTest.java index 7243d3efd5..6bcb2e8f0f 100644 --- a/spring-security-core/src/test/java/org/baeldung/test/LiveTest.java +++ b/spring-security-core/src/test/java/com/baeldung/test/LiveTest.java @@ -1,11 +1,10 @@ -package org.baeldung.test; +package com.baeldung.test; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.baeldung.app.App; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; @@ -20,6 +19,8 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import com.baeldung.app.App; + @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = App.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @FixMethodOrder(MethodSorters.NAME_ASCENDING) diff --git a/spring-security-mvc-boot/pom.xml b/spring-security-mvc-boot/pom.xml index 906bebf442..0063a2d82b 100644 --- a/spring-security-mvc-boot/pom.xml +++ b/spring-security-mvc-boot/pom.xml @@ -7,7 +7,7 @@ spring-security-mvc-boot 0.0.1-SNAPSHOT spring-security-mvc-boot - pom + war Spring Security MVC Boot @@ -46,6 +46,20 @@ org.springframework.security spring-security-data
    + + mysql + mysql-connector-java + runtime + + + com.h2database + h2 + + + org.postgresql + postgresql + runtime + org.hamcrest hamcrest-core @@ -214,13 +228,22 @@ - - spring-security-mvc-boot-default - spring-security-mvc-boot-mysql - spring-security-mvc-boot-postgre - + org.baeldung.custom.Application + + + + + + + + + 1.1.2 1.6.1 2.6.11 diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/pom.xml b/spring-security-mvc-boot/spring-security-mvc-boot-default/pom.xml deleted file mode 100644 index 8f7f18f093..0000000000 --- a/spring-security-mvc-boot/spring-security-mvc-boot-default/pom.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - 4.0.0 - com.baeldung - spring-security-mvc-boot-default - 0.0.1-SNAPSHOT - spring-security-mvc-boot-default - jar - Spring Security MVC Boot - - - spring-security-mvc-boot - com.baeldung - 0.0.1-SNAPSHOT - ../ - - - - - com.h2database - h2 - - - - - org.baeldung.custom.Application - - - - - - - - - - - diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/pom.xml b/spring-security-mvc-boot/spring-security-mvc-boot-mysql/pom.xml deleted file mode 100644 index 765953c557..0000000000 --- a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - 4.0.0 - com.baeldung - spring-security-mvc-boot-mysql - 0.0.1-SNAPSHOT - spring-security-mvc-boot-mysql - jar - Spring Security MVC Boot using MySQL - - - spring-security-mvc-boot - com.baeldung - 0.0.1-SNAPSHOT - .. - - - - - mysql - mysql-connector-java - runtime - - - - diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/pom.xml b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/pom.xml deleted file mode 100644 index e68e47b596..0000000000 --- a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - 4.0.0 - com.baeldung - spring-security-mvc-boot-postgre - 0.0.1-SNAPSHOT - spring-security-mvc-boot-postgre - jar - Spring Security MVC Boot using PostgreSQL - - - spring-security-mvc-boot - com.baeldung - 0.0.1-SNAPSHOT - .. - - - - - org.postgresql - postgresql - runtime - - - - diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/SpringContextIntegrationTest.java b/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/SpringContextIntegrationTest.java deleted file mode 100644 index f133ef73be..0000000000 --- a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/SpringContextIntegrationTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.jdbcauthentication.postgre; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.jdbcauthentication.postgre.PostgreJdbcAuthenticationApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = PostgreJdbcAuthenticationApplication.class) -public class SpringContextIntegrationTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/AppConfig.java b/spring-security-mvc-boot/src/main/java/com/baeldung/AppConfig.java similarity index 96% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/AppConfig.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/AppConfig.java index 16bbe8b326..8719e39a20 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/AppConfig.java +++ b/spring-security-mvc-boot/src/main/java/com/baeldung/AppConfig.java @@ -18,7 +18,7 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @SpringBootApplication -@PropertySource("classpath:persistence-h2.properties") +@PropertySource({"classpath:persistence-h2.properties", "classpath:application-defaults.properties"}) @EnableJpaRepositories(basePackages = { "com.baeldung.data.repositories" }) @EnableWebMvc @Import(SpringSecurityConfig.class) diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/SpringSecurityConfig.java b/spring-security-mvc-boot/src/main/java/com/baeldung/SpringSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/SpringSecurityConfig.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/SpringSecurityConfig.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/data/repositories/TweetRepository.java b/spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/TweetRepository.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/data/repositories/TweetRepository.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/TweetRepository.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/data/repositories/UserRepository.java b/spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/UserRepository.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/data/repositories/UserRepository.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/data/repositories/UserRepository.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/models/AppUser.java b/spring-security-mvc-boot/src/main/java/com/baeldung/models/AppUser.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/models/AppUser.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/models/AppUser.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/models/Tweet.java b/spring-security-mvc-boot/src/main/java/com/baeldung/models/Tweet.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/models/Tweet.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/models/Tweet.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/AppUserPrincipal.java b/spring-security-mvc-boot/src/main/java/com/baeldung/security/AppUserPrincipal.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/AppUserPrincipal.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/security/AppUserPrincipal.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java b/spring-security-mvc-boot/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/security/AuthenticationSuccessHandlerImpl.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/CustomUserDetailsService.java b/spring-security-mvc-boot/src/main/java/com/baeldung/security/CustomUserDetailsService.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/security/CustomUserDetailsService.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/security/CustomUserDetailsService.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/util/DummyContentUtil.java b/spring-security-mvc-boot/src/main/java/com/baeldung/util/DummyContentUtil.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/com/baeldung/util/DummyContentUtil.java rename to spring-security-mvc-boot/src/main/java/com/baeldung/util/DummyContentUtil.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/Application.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/Application.java similarity index 77% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/Application.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/Application.java index 682d429963..2bd0da48d2 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/Application.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/Application.java @@ -3,8 +3,10 @@ package org.baeldung.custom; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.PropertySource; @SpringBootApplication +@PropertySource("classpath:application-defaults.properties") public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MethodSecurityConfig.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/MvcConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MvcConfig.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/MvcConfig.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/MvcConfig.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/SecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/config/SecurityConfig.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/config/SecurityConfig.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/SetupData.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/SetupData.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/SetupData.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/SetupData.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/OrganizationRepository.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/PrivilegeRepository.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/dao/UserRepository.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Foo.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Foo.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Foo.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Foo.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Organization.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Organization.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Organization.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Organization.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Privilege.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Privilege.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/Privilege.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/Privilege.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/User.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/User.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/persistence/model/User.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/persistence/model/User.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionHandler.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomMethodSecurityExpressionRoot.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/CustomPermissionEvaluator.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MySecurityExpressionRoot.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserDetailsService.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/security/MyUserPrincipal.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/web/MainController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/custom/web/MainController.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/custom/web/MainController.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/IpApplication.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/IpApplication.java similarity index 77% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/IpApplication.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/ip/IpApplication.java index fd270686a2..b68abbaed1 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/IpApplication.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/IpApplication.java @@ -3,8 +3,10 @@ package org.baeldung.ip; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.annotation.PropertySource; @SpringBootApplication +@PropertySource("classpath:application-defaults.properties") public class IpApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(IpApplication.class, args); diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/CustomIpAuthenticationProvider.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/SecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/SecurityConfig.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityConfig.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/ip/config/SecurityXmlConfig.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/web/MainController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ip/web/MainController.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/ip/web/MainController.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java b/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java similarity index 79% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java index 6bd30414ef..6936cdc560 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/h2/H2JdbcAuthenticationApplication.java @@ -2,10 +2,12 @@ package org.baeldung.jdbcauthentication.h2; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @SpringBootApplication @EnableWebSecurity +@PropertySource("classpath:application-defaults.properties") public class H2JdbcAuthenticationApplication { public static void main(String[] args) { diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java b/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/h2/config/SecurityConfiguration.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/h2/web/UserController.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java b/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java similarity index 66% rename from spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java index 238a48730c..52934e0096 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/mysql/MySqlJdbcAuthenticationApplication.java @@ -1,9 +1,11 @@ -package com.baeldung.jdbcauthentication.mysql; +package org.baeldung.jdbcauthentication.mysql; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; @SpringBootApplication +@PropertySource("classpath:application-mysql.properties") public class MySqlJdbcAuthenticationApplication { public static void main(String[] args) { diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java b/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java similarity index 95% rename from spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java index a0584818cd..157c0be748 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/mysql/config/SecurityConfiguration.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbcauthentication.mysql.config; +package org.baeldung.jdbcauthentication.mysql.config; import javax.sql.DataSource; diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/mysql/web/UserController.java similarity index 88% rename from spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/mysql/web/UserController.java index ed15f8bfe6..f1060b5f78 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/java/com/baeldung/jdbcauthentication/mysql/web/UserController.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/mysql/web/UserController.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbcauthentication.mysql.web; +package org.baeldung.jdbcauthentication.mysql.web; import java.security.Principal; diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java b/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java similarity index 66% rename from spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java index d4b555e8c6..2c4d1a5255 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/postgre/PostgreJdbcAuthenticationApplication.java @@ -1,9 +1,11 @@ -package com.baeldung.jdbcauthentication.postgre; +package org.baeldung.jdbcauthentication.postgre; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; @SpringBootApplication +@PropertySource("classpath:application-postgre.properties") public class PostgreJdbcAuthenticationApplication { public static void main(String[] args) { diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java b/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java similarity index 93% rename from spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java index 85dc9d364c..ba79635852 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/postgre/config/SecurityConfiguration.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbcauthentication.postgre.config; +package org.baeldung.jdbcauthentication.postgre.config; import javax.sql.DataSource; diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/postgre/web/UserController.java similarity index 88% rename from spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/postgre/web/UserController.java index da85a46562..c8fd3812b1 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/java/com/baeldung/jdbcauthentication/postgre/web/UserController.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/jdbcauthentication/postgre/web/UserController.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbcauthentication.postgre.web; +package org.baeldung.jdbcauthentication.postgre.web; import java.security.Principal; diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java b/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/CustomAuthenticationProvider.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthController.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java b/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java similarity index 78% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java index 077f558bd2..1f641298c3 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersApplication.java @@ -2,8 +2,10 @@ package org.baeldung.multipleauthproviders; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; @SpringBootApplication +@PropertySource("classpath:application-defaults.properties") // @ImportResource({ "classpath*:spring-security-multiple-auth-providers.xml" }) public class MultipleAuthProvidersApplication { public static void main(String[] args) { diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/multipleauthproviders/MultipleAuthProvidersSecurityConfig.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java b/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java similarity index 77% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java index 4e5fafcd99..847dab073e 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsApplication.java @@ -2,8 +2,10 @@ package org.baeldung.multipleentrypoints; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; @SpringBootApplication +@PropertySource("classpath:application-defaults.properties") // @ImportResource({"classpath*:spring-security-multiple-entry.xml"}) public class MultipleEntryPointsApplication { public static void main(String[] args) { diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/MultipleEntryPointsSecurityConfig.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/PagesController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/PagesController.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multipleentrypoints/PagesController.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/multipleentrypoints/PagesController.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java b/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java similarity index 78% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java index d25324eb54..90bb5e4260 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginApplication.java @@ -3,8 +3,10 @@ package org.baeldung.multiplelogin; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.PropertySource; @SpringBootApplication +@PropertySource("classpath:application-defaults.properties") @ComponentScan("org.baeldung.multiplelogin") public class MultipleLoginApplication { public static void main(String[] args) { diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginMvcConfig.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/MultipleLoginSecurityConfig.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/UsersController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/UsersController.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/multiplelogin/UsersController.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/multiplelogin/UsersController.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/CustomAuthenticationProvider.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyLogoutSuccessHandler.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/MyUserDetailsService.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/RolesAuthoritiesApplication.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/MvcConfig.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/config/SecurityConfig.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Privilege.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/Role.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Role.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/Role.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/Role.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/User.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/User.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/model/User.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/model/User.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/IUserService.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/PrivilegeRepository.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/RoleRepository.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/SetupDataLoader.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserRepository.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java b/spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/rolesauthorities/persistence/UserService.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java similarity index 78% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java index 70fe30abdc..17c249067c 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java +++ b/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/HttpsEnabledApplication.java @@ -2,8 +2,10 @@ package org.baeldung.ssl; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; @SpringBootApplication +@PropertySource("classpath:application-defaults.properties") public class HttpsEnabledApplication { public static void main(String... args) { diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/SecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/SecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/SecurityConfig.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/ssl/SecurityConfig.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/WelcomeController.java b/spring-security-mvc-boot/src/main/java/org/baeldung/ssl/WelcomeController.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/ssl/WelcomeController.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/ssl/WelcomeController.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/MinuteBasedVoter.java b/spring-security-mvc-boot/src/main/java/org/baeldung/voter/MinuteBasedVoter.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/MinuteBasedVoter.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/voter/MinuteBasedVoter.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/VoterApplication.java b/spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterApplication.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/VoterApplication.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterApplication.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/VoterMvcConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterMvcConfig.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/VoterMvcConfig.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/voter/VoterMvcConfig.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/WebSecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/voter/WebSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/WebSecurityConfig.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/voter/WebSecurityConfig.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/XmlSecurityConfig.java b/spring-security-mvc-boot/src/main/java/org/baeldung/voter/XmlSecurityConfig.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/java/org/baeldung/voter/XmlSecurityConfig.java rename to spring-security-mvc-boot/src/main/java/org/baeldung/voter/XmlSecurityConfig.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application.properties b/spring-security-mvc-boot/src/main/resources/application-defaults.properties similarity index 76% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application.properties rename to spring-security-mvc-boot/src/main/resources/application-defaults.properties index 365dedab9e..e2032c4a6b 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application.properties +++ b/spring-security-mvc-boot/src/main/resources/application-defaults.properties @@ -1,4 +1,3 @@ -server.port=8082 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 @@ -8,7 +7,7 @@ spring.jpa.database=H2 spring.jpa.show-sql=false spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect -logging.level.org.springframework.security.web.FilterChainProxy=DEBUG +#logging.level.org.springframework.security.web.FilterChainProxy=DEBUG spring.h2.console.enabled=true spring.h2.console.path=/h2-console \ No newline at end of file diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/application.properties b/spring-security-mvc-boot/src/main/resources/application-mysql.properties similarity index 77% rename from spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/application.properties rename to spring-security-mvc-boot/src/main/resources/application-mysql.properties index 2962475108..568d0c5ca3 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/application.properties +++ b/spring-security-mvc-boot/src/main/resources/application-mysql.properties @@ -1,8 +1,9 @@ -server.port=8082 - +spring.datasource.platform=mysql spring.datasource.url=jdbc:mysql://localhost:3306/jdbc_authentication spring.datasource.username=root spring.datasource.password=pass spring.datasource.initialization-mode=always spring.jpa.hibernate.ddl-auto=none + +spring.profiles.active=mysql diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/application.properties b/spring-security-mvc-boot/src/main/resources/application-postgre.properties similarity index 86% rename from spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/application.properties rename to spring-security-mvc-boot/src/main/resources/application-postgre.properties index 2940c5121e..69faece45e 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/application.properties +++ b/spring-security-mvc-boot/src/main/resources/application-postgre.properties @@ -1,5 +1,4 @@ -server.port=8082 - +spring.datasource.platform=postgre spring.datasource.url=jdbc:postgresql://localhost:5432/jdbc_authentication spring.datasource.username=postgres spring.datasource.password=pass diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application-ssl.properties b/spring-security-mvc-boot/src/main/resources/application-ssl.properties similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/application-ssl.properties rename to spring-security-mvc-boot/src/main/resources/application-ssl.properties diff --git a/spring-security-mvc-boot/src/main/resources/application.properties b/spring-security-mvc-boot/src/main/resources/application.properties new file mode 100644 index 0000000000..3cf12afeb9 --- /dev/null +++ b/spring-security-mvc-boot/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=8082 diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/data.sql b/spring-security-mvc-boot/src/main/resources/data-mysql.sql similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/data.sql rename to spring-security-mvc-boot/src/main/resources/data-mysql.sql diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/data.sql b/spring-security-mvc-boot/src/main/resources/data-postgre.sql similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/data.sql rename to spring-security-mvc-boot/src/main/resources/data-postgre.sql diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/keystore/baeldung.p12 b/spring-security-mvc-boot/src/main/resources/keystore/baeldung.p12 similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/keystore/baeldung.p12 rename to spring-security-mvc-boot/src/main/resources/keystore/baeldung.p12 diff --git a/testing-modules/testing/src/main/resources/logback.xml b/spring-security-mvc-boot/src/main/resources/logback.xml similarity index 100% rename from testing-modules/testing/src/main/resources/logback.xml rename to spring-security-mvc-boot/src/main/resources/logback.xml diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/persistence-h2.properties b/spring-security-mvc-boot/src/main/resources/persistence-h2.properties similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/persistence-h2.properties rename to spring-security-mvc-boot/src/main/resources/persistence-h2.properties diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/schema.sql b/spring-security-mvc-boot/src/main/resources/schema-mysql.sql similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/main/resources/schema.sql rename to spring-security-mvc-boot/src/main/resources/schema-mysql.sql diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/schema.sql b/spring-security-mvc-boot/src/main/resources/schema-postgre.sql similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/main/resources/schema.sql rename to spring-security-mvc-boot/src/main/resources/schema-postgre.sql diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-custom-voter.xml b/spring-security-mvc-boot/src/main/resources/spring-security-custom-voter.xml similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-custom-voter.xml rename to spring-security-mvc-boot/src/main/resources/spring-security-custom-voter.xml diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-ip.xml b/spring-security-mvc-boot/src/main/resources/spring-security-ip.xml similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-ip.xml rename to spring-security-mvc-boot/src/main/resources/spring-security-ip.xml diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-multiple-auth-providers.xml b/spring-security-mvc-boot/src/main/resources/spring-security-multiple-auth-providers.xml similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-multiple-auth-providers.xml rename to spring-security-mvc-boot/src/main/resources/spring-security-multiple-auth-providers.xml diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-multiple-entry.xml b/spring-security-mvc-boot/src/main/resources/spring-security-multiple-entry.xml similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/spring-security-multiple-entry.xml rename to spring-security-mvc-boot/src/main/resources/spring-security-multiple-entry.xml diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/403.html b/spring-security-mvc-boot/src/main/resources/templates/403.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/403.html rename to spring-security-mvc-boot/src/main/resources/templates/403.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/adminPage.html b/spring-security-mvc-boot/src/main/resources/templates/adminPage.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/adminPage.html rename to spring-security-mvc-boot/src/main/resources/templates/adminPage.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/index.html b/spring-security-mvc-boot/src/main/resources/templates/index.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/index.html rename to spring-security-mvc-boot/src/main/resources/templates/index.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/login.html b/spring-security-mvc-boot/src/main/resources/templates/login.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/login.html rename to spring-security-mvc-boot/src/main/resources/templates/login.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/loginAdmin.html b/spring-security-mvc-boot/src/main/resources/templates/loginAdmin.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/loginAdmin.html rename to spring-security-mvc-boot/src/main/resources/templates/loginAdmin.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/loginUser.html b/spring-security-mvc-boot/src/main/resources/templates/loginUser.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/loginUser.html rename to spring-security-mvc-boot/src/main/resources/templates/loginUser.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/login.html b/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/login.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/login.html rename to spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/login.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/loginWithWarning.html b/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/loginWithWarning.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/loginWithWarning.html rename to spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/loginWithWarning.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html b/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html rename to spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/multipleHttpLinks.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myAdminPage.html b/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myAdminPage.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myAdminPage.html rename to spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myAdminPage.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myGuestPage.html b/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myGuestPage.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myGuestPage.html rename to spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myGuestPage.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html b/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html rename to spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myPrivateUserPage.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myUserPage.html b/spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myUserPage.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/multipleHttpElems/myUserPage.html rename to spring-security-mvc-boot/src/main/resources/templates/multipleHttpElems/myUserPage.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/private.html b/spring-security-mvc-boot/src/main/resources/templates/private.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/private.html rename to spring-security-mvc-boot/src/main/resources/templates/private.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/protectedLinks.html b/spring-security-mvc-boot/src/main/resources/templates/protectedLinks.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/protectedLinks.html rename to spring-security-mvc-boot/src/main/resources/templates/protectedLinks.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/home.html b/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/home.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/home.html rename to spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/home.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/login.html b/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/login.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/login.html rename to spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/login.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbyauthority.html b/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyauthority.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbyauthority.html rename to spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyauthority.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbynothing.html b/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbynothing.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbynothing.html rename to spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbynothing.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbyrole.html b/spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyrole.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/rolesauthorities/protectedbyrole.html rename to spring-security-mvc-boot/src/main/resources/templates/rolesauthorities/protectedbyrole.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/ssl/welcome.html b/spring-security-mvc-boot/src/main/resources/templates/ssl/welcome.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/ssl/welcome.html rename to spring-security-mvc-boot/src/main/resources/templates/ssl/welcome.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/userPage.html b/spring-security-mvc-boot/src/main/resources/templates/userPage.html similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/main/resources/templates/userPage.html rename to spring-security-mvc-boot/src/main/resources/templates/userPage.html diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java b/spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java rename to spring-security-mvc-boot/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/SpringContextIntegrationTest.java rename to spring-security-mvc-boot/src/test/java/org/baeldung/SpringContextIntegrationTest.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/SpringContextIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/h2/SpringContextIntegrationTest.java similarity index 74% rename from spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/SpringContextIntegrationTest.java rename to spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/h2/SpringContextIntegrationTest.java index 2c19e2c0ca..55a7b9e2be 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/SpringContextIntegrationTest.java +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/h2/SpringContextIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbcauthentication.mysql; +package org.baeldung.jdbcauthentication.h2; import org.junit.Test; import org.junit.runner.RunWith; @@ -6,7 +6,7 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) -@SpringBootTest(classes = MySqlJdbcAuthenticationApplication.class) +@SpringBootTest(classes = H2JdbcAuthenticationApplication.class) public class SpringContextIntegrationTest { @Test diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java rename to spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/h2/web/UserControllerLiveTest.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java similarity index 95% rename from spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java rename to spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java index 79bc84ea69..261063cbb6 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-mysql/src/test/java/com/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/mysql/web/UserControllerLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbcauthentication.mysql.web; +package org.baeldung.jdbcauthentication.mysql.web; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java similarity index 92% rename from spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java rename to spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java index b5f4379c0a..82bf6df8db 100644 --- a/spring-security-mvc-boot/spring-security-mvc-boot-postgre/src/test/java/com/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java +++ b/spring-security-mvc-boot/src/test/java/org/baeldung/jdbcauthentication/postgre/web/UserControllerLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbcauthentication.postgre.web; +package org.baeldung.jdbcauthentication.postgre.web; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; @@ -10,7 +10,7 @@ import org.springframework.http.HttpStatus; * This Live Test requires: * * a PostgreSQL instance running, that allows a 'root' user with password 'pass', and with a database named jdbc_authentication * (e.g. with the following command `docker run -p 5432:5432 --name bael-postgre -e POSTGRES_PASSWORD=pass -e POSTGRES_DB=jdbc_authentication postgres:latest`) - * * the service up and running + * * the service up and running * */ public class UserControllerLiveTest { diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/ApplicationLiveTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/ApplicationLiveTest.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/ApplicationLiveTest.java rename to spring-security-mvc-boot/src/test/java/org/baeldung/web/ApplicationLiveTest.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java rename to spring-security-mvc-boot/src/test/java/org/baeldung/web/CustomUserDetailsServiceIntegrationTest.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java rename to spring-security-mvc-boot/src/test/java/org/baeldung/web/HttpsApplicationIntegrationTest.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/IpLiveTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/IpLiveTest.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/IpLiveTest.java rename to spring-security-mvc-boot/src/test/java/org/baeldung/web/IpLiveTest.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java rename to spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleAuthProvidersApplicationIntegrationTest.java diff --git a/spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java b/spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java similarity index 100% rename from spring-security-mvc-boot/spring-security-mvc-boot-default/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java rename to spring-security-mvc-boot/src/test/java/org/baeldung/web/MultipleEntryPointsIntegrationTest.java diff --git a/spring-security-mvc-login/src/main/java/com/baeldung/spring/SecSecurityConfig.java b/spring-security-mvc-login/src/main/java/com/baeldung/security/config/SecSecurityConfig.java similarity index 98% rename from spring-security-mvc-login/src/main/java/com/baeldung/spring/SecSecurityConfig.java rename to spring-security-mvc-login/src/main/java/com/baeldung/security/config/SecSecurityConfig.java index 08a83f8633..15fa06aa3e 100644 --- a/spring-security-mvc-login/src/main/java/com/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-mvc-login/src/main/java/com/baeldung/security/config/SecSecurityConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.spring; +package com.baeldung.security.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-security-mvc-login/src/test/java/com/baeldung/security/FormLoginUnitTest.java b/spring-security-mvc-login/src/test/java/com/baeldung/security/FormLoginUnitTest.java index b7d959bf36..01cb8e7b67 100644 --- a/spring-security-mvc-login/src/test/java/com/baeldung/security/FormLoginUnitTest.java +++ b/spring-security-mvc-login/src/test/java/com/baeldung/security/FormLoginUnitTest.java @@ -12,7 +12,7 @@ import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; -import com.baeldung.spring.SecSecurityConfig; +import com.baeldung.security.config.SecSecurityConfig; import javax.servlet.Filter; diff --git a/spring-security-rest/src/main/java/org/baeldung/spring/SecurityJavaConfig.java b/spring-security-rest/src/main/java/org/baeldung/security/SecurityJavaConfig.java similarity index 94% rename from spring-security-rest/src/main/java/org/baeldung/spring/SecurityJavaConfig.java rename to spring-security-rest/src/main/java/org/baeldung/security/SecurityJavaConfig.java index cc023110b6..74623080b5 100644 --- a/spring-security-rest/src/main/java/org/baeldung/spring/SecurityJavaConfig.java +++ b/spring-security-rest/src/main/java/org/baeldung/security/SecurityJavaConfig.java @@ -1,7 +1,7 @@ -package org.baeldung.spring; +package org.baeldung.security; -import org.baeldung.security.MySavedRequestAwareAuthenticationSuccessHandler; -import org.baeldung.security.RestAuthenticationEntryPoint; +import org.baeldung.security.web.MySavedRequestAwareAuthenticationSuccessHandler; +import org.baeldung.security.web.RestAuthenticationEntryPoint; import org.baeldung.web.error.CustomAccessDeniedHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; diff --git a/spring-security-rest/src/main/java/org/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java b/spring-security-rest/src/main/java/org/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java similarity index 98% rename from spring-security-rest/src/main/java/org/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java rename to spring-security-rest/src/main/java/org/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java index 6018264632..c56568e979 100644 --- a/spring-security-rest/src/main/java/org/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java +++ b/spring-security-rest/src/main/java/org/baeldung/security/web/MySavedRequestAwareAuthenticationSuccessHandler.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package org.baeldung.security.web; import java.io.IOException; diff --git a/spring-security-rest/src/main/java/org/baeldung/security/RestAuthenticationEntryPoint.java b/spring-security-rest/src/main/java/org/baeldung/security/web/RestAuthenticationEntryPoint.java similarity index 95% rename from spring-security-rest/src/main/java/org/baeldung/security/RestAuthenticationEntryPoint.java rename to spring-security-rest/src/main/java/org/baeldung/security/web/RestAuthenticationEntryPoint.java index e448e6537f..643e2f0575 100644 --- a/spring-security-rest/src/main/java/org/baeldung/security/RestAuthenticationEntryPoint.java +++ b/spring-security-rest/src/main/java/org/baeldung/security/web/RestAuthenticationEntryPoint.java @@ -1,4 +1,4 @@ -package org.baeldung.security; +package org.baeldung.security.web; import java.io.IOException; diff --git a/spring-security-rest/src/main/java/org/baeldung/spring/SwaggerConfig.java b/spring-security-rest/src/main/java/org/baeldung/swagger2/SwaggerConfig.java similarity index 98% rename from spring-security-rest/src/main/java/org/baeldung/spring/SwaggerConfig.java rename to spring-security-rest/src/main/java/org/baeldung/swagger2/SwaggerConfig.java index aa00e8455e..67c760353d 100644 --- a/spring-security-rest/src/main/java/org/baeldung/spring/SwaggerConfig.java +++ b/spring-security-rest/src/main/java/org/baeldung/swagger2/SwaggerConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring; +package org.baeldung.swagger2; import static com.google.common.collect.Lists.newArrayList; diff --git a/spring-security-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-security-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java index e2e9f2af2b..ae0d80bb45 100644 --- a/spring-security-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ b/spring-security-rest/src/test/java/org/baeldung/SpringContextIntegrationTest.java @@ -1,7 +1,7 @@ package org.baeldung; +import org.baeldung.security.SecurityJavaConfig; import org.baeldung.spring.ClientWebConfig; -import org.baeldung.spring.SecurityJavaConfig; import org.baeldung.spring.WebConfig; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java b/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java index d984cf5c35..11586ce670 100644 --- a/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java +++ b/spring-security-rest/src/test/java/org/baeldung/SpringContextTest.java @@ -1,7 +1,7 @@ package org.baeldung; +import org.baeldung.security.SecurityJavaConfig; import org.baeldung.spring.ClientWebConfig; -import org.baeldung.spring.SecurityJavaConfig; import org.baeldung.spring.WebConfig; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerIntegrationTest.java b/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerIntegrationTest.java index a09c225a4a..1e5e1b7d85 100644 --- a/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerIntegrationTest.java +++ b/spring-security-rest/src/test/java/org/baeldung/web/AsyncControllerIntegrationTest.java @@ -1,7 +1,7 @@ package org.baeldung.web; +import org.baeldung.security.SecurityJavaConfig; import org.baeldung.spring.ClientWebConfig; -import org.baeldung.spring.SecurityJavaConfig; import org.baeldung.spring.WebConfig; import org.baeldung.web.controller.AsyncController; import org.junit.Before; diff --git a/spring-thymeleaf-2/README.md b/spring-thymeleaf-2/README.md index 9e12f2d99f..ce83032cb5 100644 --- a/spring-thymeleaf-2/README.md +++ b/spring-thymeleaf-2/README.md @@ -2,3 +2,4 @@ - [Working with Enums in Thymeleaf](https://www.baeldung.com/thymeleaf-enums) - [Changing the Thymeleaf Template Directory in Spring Boot](https://www.baeldung.com/spring-thymeleaf-template-directory) +- [Spring Request Parameters with Thymeleaf](https://www.baeldung.com/spring-thymeleaf-request-parameters) diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ParticipantController.java b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/controller/ParticipantController.java similarity index 91% rename from spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ParticipantController.java rename to spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/controller/ParticipantController.java index eebe37e000..9a354e709c 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ParticipantController.java +++ b/spring-thymeleaf-2/src/main/java/com/baeldung/thymeleaf/controller/ParticipantController.java @@ -1,4 +1,4 @@ -package com.example.demo; +package com.baeldung.thymeleaf.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; @@ -12,7 +12,7 @@ import static java.util.Arrays.asList; @Controller public class ParticipantController { - @RequestMapping("/") + @RequestMapping("/participants") public String index( @RequestParam(value = "participant", required = false) String participant, @RequestParam(value = "country", required = false) String country, diff --git a/spring-thymeleaf/src/main/resources/templates/participants.html b/spring-thymeleaf-2/src/main/resources/templates-2/participants.html similarity index 86% rename from spring-thymeleaf/src/main/resources/templates/participants.html rename to spring-thymeleaf-2/src/main/resources/templates-2/participants.html index 8d4e552093..f7e017e777 100644 --- a/spring-thymeleaf/src/main/resources/templates/participants.html +++ b/spring-thymeleaf-2/src/main/resources/templates-2/participants.html @@ -4,7 +4,7 @@

    Enter participant

    -
    +